id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_857_0
/* * Copyright (c) 1997 - 2008 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. */ #include "krb5_locl.h" #ifndef WIN32 #include <heim-ipc.h> #endif /* WIN32 */ typedef struct krb5_get_init_creds_ctx { KDCOptions flags; krb5_creds cred; krb5_addresses *addrs; krb5_enctype *etypes; krb5_preauthtype *pre_auth_types; char *in_tkt_service; unsigned nonce; unsigned pk_nonce; krb5_data req_buffer; AS_REQ as_req; int pa_counter; /* password and keytab_data is freed on completion */ char *password; krb5_keytab_key_proc_args *keytab_data; krb5_pointer *keyseed; krb5_s2k_proc keyproc; krb5_get_init_creds_tristate req_pac; krb5_pk_init_ctx pk_init_ctx; int ic_flags; struct { unsigned change_password:1; } runflags; int used_pa_types; #define USED_PKINIT 1 #define USED_PKINIT_W2K 2 #define USED_ENC_TS_GUESS 4 #define USED_ENC_TS_INFO 8 METHOD_DATA md; KRB_ERROR error; AS_REP as_rep; EncKDCRepPart enc_part; krb5_prompter_fct prompter; void *prompter_data; struct pa_info_data *ppaid; struct fast_state { enum PA_FX_FAST_REQUEST_enum type; unsigned int flags; #define KRB5_FAST_REPLY_KEY_USE_TO_ENCRYPT_THE_REPLY 1 #define KRB5_FAST_REPLY_KEY_USE_IN_TRANSACTION 2 #define KRB5_FAST_KDC_REPLY_KEY_REPLACED 4 #define KRB5_FAST_REPLY_REPLY_VERIFED 8 #define KRB5_FAST_STRONG 16 #define KRB5_FAST_EXPECTED 32 /* in exchange with KDC, fast was discovered */ #define KRB5_FAST_REQUIRED 64 /* fast required by action of caller */ #define KRB5_FAST_DISABLED 128 #define KRB5_FAST_AP_ARMOR_SERVICE 256 krb5_keyblock *reply_key; krb5_ccache armor_ccache; krb5_principal armor_service; krb5_crypto armor_crypto; krb5_keyblock armor_key; krb5_keyblock *strengthen_key; } fast_state; } krb5_get_init_creds_ctx; struct pa_info_data { krb5_enctype etype; krb5_salt salt; krb5_data *s2kparams; }; static void free_paid(krb5_context context, struct pa_info_data *ppaid) { krb5_free_salt(context, ppaid->salt); if (ppaid->s2kparams) krb5_free_data(context, ppaid->s2kparams); } static krb5_error_code KRB5_CALLCONV default_s2k_func(krb5_context context, krb5_enctype type, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { krb5_error_code ret; krb5_data password; krb5_data opaque; _krb5_debug(context, 5, "krb5_get_init_creds: using default_s2k_func"); password.data = rk_UNCONST(keyseed); password.length = strlen(keyseed); if (s2kparms) opaque = *s2kparms; else krb5_data_zero(&opaque); *key = malloc(sizeof(**key)); if (*key == NULL) return ENOMEM; ret = krb5_string_to_key_data_salt_opaque(context, type, password, salt, opaque, *key); if (ret) { free(*key); *key = NULL; } return ret; } static void free_init_creds_ctx(krb5_context context, krb5_init_creds_context ctx) { if (ctx->etypes) free(ctx->etypes); if (ctx->pre_auth_types) free (ctx->pre_auth_types); if (ctx->in_tkt_service) free(ctx->in_tkt_service); if (ctx->keytab_data) free(ctx->keytab_data); if (ctx->password) { memset(ctx->password, 0, strlen(ctx->password)); free(ctx->password); } /* * FAST state (we don't close the armor_ccache because we might have * to destroy it, and how would we know? also, the caller should * take care of cleaning up the armor_ccache). */ if (ctx->fast_state.armor_service) krb5_free_principal(context, ctx->fast_state.armor_service); if (ctx->fast_state.armor_crypto) krb5_crypto_destroy(context, ctx->fast_state.armor_crypto); if (ctx->fast_state.strengthen_key) krb5_free_keyblock(context, ctx->fast_state.strengthen_key); krb5_free_keyblock_contents(context, &ctx->fast_state.armor_key); krb5_data_free(&ctx->req_buffer); krb5_free_cred_contents(context, &ctx->cred); free_METHOD_DATA(&ctx->md); free_AS_REP(&ctx->as_rep); free_EncKDCRepPart(&ctx->enc_part); free_KRB_ERROR(&ctx->error); free_AS_REQ(&ctx->as_req); if (ctx->ppaid) { free_paid(context, ctx->ppaid); free(ctx->ppaid); } memset(ctx, 0, sizeof(*ctx)); } static int get_config_time (krb5_context context, const char *realm, const char *name, int def) { int ret; ret = krb5_config_get_time (context, NULL, "realms", realm, name, NULL); if (ret >= 0) return ret; ret = krb5_config_get_time (context, NULL, "libdefaults", name, NULL); if (ret >= 0) return ret; return def; } static krb5_error_code init_cred (krb5_context context, krb5_creds *cred, krb5_principal client, krb5_deltat start_time, krb5_get_init_creds_opt *options) { krb5_error_code ret; int tmp; krb5_timestamp now; krb5_timeofday (context, &now); memset (cred, 0, sizeof(*cred)); if (client) ret = krb5_copy_principal(context, client, &cred->client); else ret = krb5_get_default_principal(context, &cred->client); if (ret) goto out; if (start_time) cred->times.starttime = now + start_time; if (options->flags & KRB5_GET_INIT_CREDS_OPT_TKT_LIFE) tmp = options->tkt_life; else tmp = KRB5_TKT_LIFETIME_DEFAULT; cred->times.endtime = now + tmp; if ((options->flags & KRB5_GET_INIT_CREDS_OPT_RENEW_LIFE)) { if (options->renew_life > 0) tmp = options->renew_life; else tmp = KRB5_TKT_RENEW_LIFETIME_DEFAULT; cred->times.renew_till = now + tmp; } return 0; out: krb5_free_cred_contents (context, cred); return ret; } /* * Print a message (str) to the user about the expiration in `lr' */ static void report_expiration (krb5_context context, krb5_prompter_fct prompter, krb5_data *data, const char *str, time_t now) { char *p = NULL; if (asprintf(&p, "%s%s", str, ctime(&now)) < 0 || p == NULL) return; (*prompter)(context, data, NULL, p, 0, NULL); free(p); } /* * Check the context, and in the case there is a expiration warning, * use the prompter to print the warning. * * @param context A Kerberos 5 context. * @param options An GIC options structure * @param ctx The krb5_init_creds_context check for expiration. */ krb5_error_code krb5_process_last_request(krb5_context context, krb5_get_init_creds_opt *options, krb5_init_creds_context ctx) { krb5_const_realm realm; LastReq *lr; krb5_boolean reported = FALSE; krb5_timestamp sec; time_t t; size_t i; /* * First check if there is a API consumer. */ realm = krb5_principal_get_realm (context, ctx->cred.client); lr = &ctx->enc_part.last_req; if (options && options->opt_private && options->opt_private->lr.func) { krb5_last_req_entry **lre; lre = calloc(lr->len + 1, sizeof(*lre)); if (lre == NULL) return krb5_enomem(context); for (i = 0; i < lr->len; i++) { lre[i] = calloc(1, sizeof(*lre[i])); if (lre[i] == NULL) break; lre[i]->lr_type = lr->val[i].lr_type; lre[i]->value = lr->val[i].lr_value; } (*options->opt_private->lr.func)(context, lre, options->opt_private->lr.ctx); for (i = 0; i < lr->len; i++) free(lre[i]); free(lre); } /* * Now check if we should prompt the user */ if (ctx->prompter == NULL) return 0; krb5_timeofday (context, &sec); t = sec + get_config_time (context, realm, "warn_pwexpire", 7 * 24 * 60 * 60); for (i = 0; i < lr->len; ++i) { if (lr->val[i].lr_value <= t) { switch (lr->val[i].lr_type) { case LR_PW_EXPTIME : report_expiration(context, ctx->prompter, ctx->prompter_data, "Your password will expire at ", lr->val[i].lr_value); reported = TRUE; break; case LR_ACCT_EXPTIME : report_expiration(context, ctx->prompter, ctx->prompter_data, "Your account will expire at ", lr->val[i].lr_value); reported = TRUE; break; default: break; } } } if (!reported && ctx->enc_part.key_expiration && *ctx->enc_part.key_expiration <= t) { report_expiration(context, ctx->prompter, ctx->prompter_data, "Your password/account will expire at ", *ctx->enc_part.key_expiration); } return 0; } static krb5_addresses no_addrs = { 0, NULL }; static krb5_error_code get_init_creds_common(krb5_context context, krb5_principal client, krb5_deltat start_time, krb5_get_init_creds_opt *options, krb5_init_creds_context ctx) { krb5_get_init_creds_opt *default_opt = NULL; krb5_error_code ret; krb5_enctype *etypes; krb5_preauthtype *pre_auth_types; memset(ctx, 0, sizeof(*ctx)); if (options == NULL) { const char *realm = krb5_principal_get_realm(context, client); krb5_get_init_creds_opt_alloc (context, &default_opt); options = default_opt; krb5_get_init_creds_opt_set_default_flags(context, NULL, realm, options); } if (options->opt_private) { if (options->opt_private->password) { ret = krb5_init_creds_set_password(context, ctx, options->opt_private->password); if (ret) goto out; } ctx->keyproc = options->opt_private->key_proc; ctx->req_pac = options->opt_private->req_pac; ctx->pk_init_ctx = options->opt_private->pk_init_ctx; ctx->ic_flags = options->opt_private->flags; } else ctx->req_pac = KRB5_INIT_CREDS_TRISTATE_UNSET; if (ctx->keyproc == NULL) ctx->keyproc = default_s2k_func; /* Enterprise name implicitly turns on canonicalize */ if ((ctx->ic_flags & KRB5_INIT_CREDS_CANONICALIZE) || krb5_principal_get_type(context, client) == KRB5_NT_ENTERPRISE_PRINCIPAL) ctx->flags.canonicalize = 1; ctx->pre_auth_types = NULL; ctx->addrs = NULL; ctx->etypes = NULL; ctx->pre_auth_types = NULL; ret = init_cred(context, &ctx->cred, client, start_time, options); if (ret) { if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return ret; } ret = krb5_init_creds_set_service(context, ctx, NULL); if (ret) goto out; if (options->flags & KRB5_GET_INIT_CREDS_OPT_FORWARDABLE) ctx->flags.forwardable = options->forwardable; if (options->flags & KRB5_GET_INIT_CREDS_OPT_PROXIABLE) ctx->flags.proxiable = options->proxiable; if (start_time) ctx->flags.postdated = 1; if (ctx->cred.times.renew_till) ctx->flags.renewable = 1; if (options->flags & KRB5_GET_INIT_CREDS_OPT_ADDRESS_LIST) { ctx->addrs = options->address_list; } else if (options->opt_private) { switch (options->opt_private->addressless) { case KRB5_INIT_CREDS_TRISTATE_UNSET: #if KRB5_ADDRESSLESS_DEFAULT == TRUE ctx->addrs = &no_addrs; #else ctx->addrs = NULL; #endif break; case KRB5_INIT_CREDS_TRISTATE_FALSE: ctx->addrs = NULL; break; case KRB5_INIT_CREDS_TRISTATE_TRUE: ctx->addrs = &no_addrs; break; } } if (options->flags & KRB5_GET_INIT_CREDS_OPT_ETYPE_LIST) { if (ctx->etypes) free(ctx->etypes); etypes = malloc((options->etype_list_length + 1) * sizeof(krb5_enctype)); if (etypes == NULL) { ret = krb5_enomem(context); goto out; } memcpy (etypes, options->etype_list, options->etype_list_length * sizeof(krb5_enctype)); etypes[options->etype_list_length] = ETYPE_NULL; ctx->etypes = etypes; } if (options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST) { pre_auth_types = malloc((options->preauth_list_length + 1) * sizeof(krb5_preauthtype)); if (pre_auth_types == NULL) { ret = krb5_enomem(context); goto out; } memcpy (pre_auth_types, options->preauth_list, options->preauth_list_length * sizeof(krb5_preauthtype)); pre_auth_types[options->preauth_list_length] = KRB5_PADATA_NONE; ctx->pre_auth_types = pre_auth_types; } if (options->flags & KRB5_GET_INIT_CREDS_OPT_ANONYMOUS) ctx->flags.request_anonymous = options->anonymous; if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return 0; out: if (default_opt) krb5_get_init_creds_opt_free(context, default_opt); return ret; } static krb5_error_code change_password (krb5_context context, krb5_principal client, const char *password, char *newpw, size_t newpw_sz, krb5_prompter_fct prompter, void *data, krb5_get_init_creds_opt *old_options) { krb5_prompt prompts[2]; krb5_error_code ret; krb5_creds cpw_cred; char buf1[BUFSIZ], buf2[BUFSIZ]; krb5_data password_data[2]; int result_code; krb5_data result_code_string; krb5_data result_string; char *p; krb5_get_init_creds_opt *options; heim_assert(prompter != NULL, "unexpected NULL prompter"); memset (&cpw_cred, 0, sizeof(cpw_cred)); ret = krb5_get_init_creds_opt_alloc(context, &options); if (ret) return ret; krb5_get_init_creds_opt_set_tkt_life (options, 60); krb5_get_init_creds_opt_set_forwardable (options, FALSE); krb5_get_init_creds_opt_set_proxiable (options, FALSE); if (old_options && (old_options->flags & KRB5_GET_INIT_CREDS_OPT_PREAUTH_LIST)) krb5_get_init_creds_opt_set_preauth_list(options, old_options->preauth_list, old_options->preauth_list_length); if (old_options && (old_options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT)) krb5_get_init_creds_opt_set_change_password_prompt(options, old_options->change_password_prompt); krb5_data_zero (&result_code_string); krb5_data_zero (&result_string); ret = krb5_get_init_creds_password (context, &cpw_cred, client, password, prompter, data, 0, "kadmin/changepw", options); krb5_get_init_creds_opt_free(context, options); if (ret) goto out; for(;;) { password_data[0].data = buf1; password_data[0].length = sizeof(buf1); prompts[0].hidden = 1; prompts[0].prompt = "New password: "; prompts[0].reply = &password_data[0]; prompts[0].type = KRB5_PROMPT_TYPE_NEW_PASSWORD; password_data[1].data = buf2; password_data[1].length = sizeof(buf2); prompts[1].hidden = 1; prompts[1].prompt = "Repeat new password: "; prompts[1].reply = &password_data[1]; prompts[1].type = KRB5_PROMPT_TYPE_NEW_PASSWORD_AGAIN; ret = (*prompter) (context, data, NULL, "Changing password", 2, prompts); if (ret) { memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); goto out; } if (strcmp (buf1, buf2) == 0) break; memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); } ret = krb5_set_password (context, &cpw_cred, buf1, client, &result_code, &result_code_string, &result_string); if (ret) goto out; if (asprintf(&p, "%s: %.*s\n", result_code ? "Error" : "Success", (int)result_string.length, result_string.length > 0 ? (char*)result_string.data : "") < 0) { ret = ENOMEM; goto out; } /* return the result */ (*prompter) (context, data, NULL, p, 0, NULL); free (p); if (result_code == 0) { strlcpy (newpw, buf1, newpw_sz); ret = 0; } else { ret = ENOTTY; krb5_set_error_message(context, ret, N_("failed changing password", "")); } out: memset (buf1, 0, sizeof(buf1)); memset (buf2, 0, sizeof(buf2)); krb5_data_free (&result_string); krb5_data_free (&result_code_string); krb5_free_cred_contents (context, &cpw_cred); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_keyblock_key_proc (krb5_context context, krb5_keytype type, krb5_data *salt, krb5_const_pointer keyseed, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } /* * */ static krb5_error_code init_as_req (krb5_context context, KDCOptions opts, const krb5_creds *creds, const krb5_addresses *addrs, const krb5_enctype *etypes, AS_REQ *a) { krb5_error_code ret; memset(a, 0, sizeof(*a)); a->pvno = 5; a->msg_type = krb_as_req; a->req_body.kdc_options = opts; a->req_body.cname = malloc(sizeof(*a->req_body.cname)); if (a->req_body.cname == NULL) { ret = krb5_enomem(context); goto fail; } a->req_body.sname = malloc(sizeof(*a->req_body.sname)); if (a->req_body.sname == NULL) { ret = krb5_enomem(context); goto fail; } ret = _krb5_principal2principalname (a->req_body.cname, creds->client); if (ret) goto fail; ret = copy_Realm(&creds->client->realm, &a->req_body.realm); if (ret) goto fail; ret = _krb5_principal2principalname (a->req_body.sname, creds->server); if (ret) goto fail; if(creds->times.starttime) { a->req_body.from = malloc(sizeof(*a->req_body.from)); if (a->req_body.from == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.from = creds->times.starttime; } if(creds->times.endtime){ if ((ALLOC(a->req_body.till, 1)) != NULL) *a->req_body.till = creds->times.endtime; else { ret = krb5_enomem(context); goto fail; } } if(creds->times.renew_till){ a->req_body.rtime = malloc(sizeof(*a->req_body.rtime)); if (a->req_body.rtime == NULL) { ret = krb5_enomem(context); goto fail; } *a->req_body.rtime = creds->times.renew_till; } a->req_body.nonce = 0; ret = _krb5_init_etype(context, KRB5_PDU_AS_REQUEST, &a->req_body.etype.len, &a->req_body.etype.val, etypes); if (ret) goto fail; /* * This means no addresses */ if (addrs && addrs->len == 0) { a->req_body.addresses = NULL; } else { a->req_body.addresses = malloc(sizeof(*a->req_body.addresses)); if (a->req_body.addresses == NULL) { ret = krb5_enomem(context); goto fail; } if (addrs) ret = krb5_copy_addresses(context, addrs, a->req_body.addresses); else { ret = krb5_get_all_client_addrs (context, a->req_body.addresses); if(ret == 0 && a->req_body.addresses->len == 0) { free(a->req_body.addresses); a->req_body.addresses = NULL; } } if (ret) goto fail; } a->req_body.enc_authorization_data = NULL; a->req_body.additional_tickets = NULL; a->padata = NULL; return 0; fail: free_AS_REQ(a); memset(a, 0, sizeof(*a)); return ret; } static krb5_error_code set_paid(struct pa_info_data *paid, krb5_context context, krb5_enctype etype, krb5_salttype salttype, void *salt_string, size_t salt_len, krb5_data *s2kparams) { paid->etype = etype; paid->salt.salttype = salttype; paid->salt.saltvalue.data = malloc(salt_len + 1); if (paid->salt.saltvalue.data == NULL) { krb5_clear_error_message(context); return ENOMEM; } memcpy(paid->salt.saltvalue.data, salt_string, salt_len); ((char *)paid->salt.saltvalue.data)[salt_len] = '\0'; paid->salt.saltvalue.length = salt_len; if (s2kparams) { krb5_error_code ret; ret = krb5_copy_data(context, s2kparams, &paid->s2kparams); if (ret) { krb5_clear_error_message(context); krb5_free_salt(context, paid->salt); return ret; } } else paid->s2kparams = NULL; return 0; } static struct pa_info_data * pa_etype_info2(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; ETYPE_INFO2 e; size_t sz; size_t i, j; memset(&e, 0, sizeof(e)); ret = decode_ETYPE_INFO2(data->data, data->length, &e, &sz); if (ret) goto out; if (e.len == 0) goto out; for (j = 0; j < asreq->req_body.etype.len; j++) { for (i = 0; i < e.len; i++) { if (asreq->req_body.etype.val[j] == e.val[i].etype) { krb5_salt salt; if (e.val[i].salt == NULL) ret = krb5_get_pw_salt(context, client, &salt); else { salt.saltvalue.data = *e.val[i].salt; salt.saltvalue.length = strlen(*e.val[i].salt); ret = 0; } if (ret == 0) ret = set_paid(paid, context, e.val[i].etype, KRB5_PW_SALT, salt.saltvalue.data, salt.saltvalue.length, e.val[i].s2kparams); if (e.val[i].salt == NULL) krb5_free_salt(context, salt); if (ret == 0) { free_ETYPE_INFO2(&e); return paid; } } } } out: free_ETYPE_INFO2(&e); return NULL; } static struct pa_info_data * pa_etype_info(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; ETYPE_INFO e; size_t sz; size_t i, j; memset(&e, 0, sizeof(e)); ret = decode_ETYPE_INFO(data->data, data->length, &e, &sz); if (ret) goto out; if (e.len == 0) goto out; for (j = 0; j < asreq->req_body.etype.len; j++) { for (i = 0; i < e.len; i++) { if (asreq->req_body.etype.val[j] == e.val[i].etype) { krb5_salt salt; salt.salttype = KRB5_PW_SALT; if (e.val[i].salt == NULL) ret = krb5_get_pw_salt(context, client, &salt); else { salt.saltvalue = *e.val[i].salt; ret = 0; } if (e.val[i].salttype) salt.salttype = *e.val[i].salttype; if (ret == 0) { ret = set_paid(paid, context, e.val[i].etype, salt.salttype, salt.saltvalue.data, salt.saltvalue.length, NULL); if (e.val[i].salt == NULL) krb5_free_salt(context, salt); } if (ret == 0) { free_ETYPE_INFO(&e); return paid; } } } } out: free_ETYPE_INFO(&e); return NULL; } static struct pa_info_data * pa_pw_or_afs3_salt(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, heim_octet_string *data) { krb5_error_code ret; if (paid->etype == KRB5_ENCTYPE_NULL) return NULL; ret = set_paid(paid, context, paid->etype, paid->salt.salttype, data->data, data->length, NULL); if (ret) return NULL; return paid; } struct pa_info { krb5_preauthtype type; struct pa_info_data *(*salt_info)(krb5_context, const krb5_principal, const AS_REQ *, struct pa_info_data *, heim_octet_string *); }; static struct pa_info pa_prefs[] = { { KRB5_PADATA_ETYPE_INFO2, pa_etype_info2 }, { KRB5_PADATA_ETYPE_INFO, pa_etype_info }, { KRB5_PADATA_PW_SALT, pa_pw_or_afs3_salt }, { KRB5_PADATA_AFS3_SALT, pa_pw_or_afs3_salt } }; static PA_DATA * find_pa_data(const METHOD_DATA *md, unsigned type) { size_t i; if (md == NULL) return NULL; for (i = 0; i < md->len; i++) if (md->val[i].padata_type == type) return &md->val[i]; return NULL; } static struct pa_info_data * process_pa_info(krb5_context context, const krb5_principal client, const AS_REQ *asreq, struct pa_info_data *paid, METHOD_DATA *md) { struct pa_info_data *p = NULL; size_t i; for (i = 0; p == NULL && i < sizeof(pa_prefs)/sizeof(pa_prefs[0]); i++) { PA_DATA *pa = find_pa_data(md, pa_prefs[i].type); if (pa == NULL) continue; paid->salt.salttype = (krb5_salttype)pa_prefs[i].type; p = (*pa_prefs[i].salt_info)(context, client, asreq, paid, &pa->padata_value); } return p; } static krb5_error_code make_pa_enc_timestamp(krb5_context context, METHOD_DATA *md, krb5_enctype etype, krb5_keyblock *key) { PA_ENC_TS_ENC p; unsigned char *buf; size_t buf_size; size_t len = 0; EncryptedData encdata; krb5_error_code ret; int32_t usec; int usec2; krb5_crypto crypto; krb5_us_timeofday (context, &p.patimestamp, &usec); usec2 = usec; p.pausec = &usec2; ASN1_MALLOC_ENCODE(PA_ENC_TS_ENC, buf, buf_size, &p, &len, ret); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_crypto_init(context, key, 0, &crypto); if (ret) { free(buf); return ret; } ret = krb5_encrypt_EncryptedData(context, crypto, KRB5_KU_PA_ENC_TIMESTAMP, buf, len, 0, &encdata); free(buf); krb5_crypto_destroy(context, crypto); if (ret) return ret; ASN1_MALLOC_ENCODE(EncryptedData, buf, buf_size, &encdata, &len, ret); free_EncryptedData(&encdata); if (ret) return ret; if(buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_padata_add(context, md, KRB5_PADATA_ENC_TIMESTAMP, buf, len); if (ret) free(buf); return ret; } static krb5_error_code add_enc_ts_padata(krb5_context context, METHOD_DATA *md, krb5_principal client, krb5_s2k_proc keyproc, krb5_const_pointer keyseed, krb5_enctype *enctypes, unsigned netypes, krb5_salt *salt, krb5_data *s2kparams) { krb5_error_code ret; krb5_salt salt2; krb5_enctype *ep; size_t i; if(salt == NULL) { /* default to standard salt */ ret = krb5_get_pw_salt (context, client, &salt2); if (ret) return ret; salt = &salt2; } if (!enctypes) { enctypes = context->etypes; netypes = 0; for (ep = enctypes; *ep != (krb5_enctype)ETYPE_NULL; ep++) netypes++; } for (i = 0; i < netypes; ++i) { krb5_keyblock *key; _krb5_debug(context, 5, "krb5_get_init_creds: using ENC-TS with enctype %d", enctypes[i]); ret = (*keyproc)(context, enctypes[i], keyseed, *salt, s2kparams, &key); if (ret) continue; ret = make_pa_enc_timestamp (context, md, enctypes[i], key); krb5_free_keyblock (context, key); if (ret) return ret; } if(salt == &salt2) krb5_free_salt(context, salt2); return 0; } static krb5_error_code pa_data_to_md_ts_enc(krb5_context context, const AS_REQ *a, const krb5_principal client, krb5_get_init_creds_ctx *ctx, struct pa_info_data *ppaid, METHOD_DATA *md) { if (ctx->keyproc == NULL || ctx->keyseed == NULL) return 0; if (ppaid) { add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, &ppaid->etype, 1, &ppaid->salt, ppaid->s2kparams); } else { krb5_salt salt; _krb5_debug(context, 5, "krb5_get_init_creds: pa-info not found, guessing salt"); /* make a v5 salted pa-data */ add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, a->req_body.etype.val, a->req_body.etype.len, NULL, NULL); /* make a v4 salted pa-data */ salt.salttype = KRB5_PW_SALT; krb5_data_zero(&salt.saltvalue); add_enc_ts_padata(context, md, client, ctx->keyproc, ctx->keyseed, a->req_body.etype.val, a->req_body.etype.len, &salt, NULL); } return 0; } static krb5_error_code pa_data_to_key_plain(krb5_context context, const krb5_principal client, krb5_get_init_creds_ctx *ctx, krb5_salt salt, krb5_data *s2kparams, krb5_enctype etype, krb5_keyblock **key) { krb5_error_code ret; ret = (*ctx->keyproc)(context, etype, ctx->keyseed, salt, s2kparams, key); return ret; } static krb5_error_code pa_data_to_md_pkinit(krb5_context context, const AS_REQ *a, const krb5_principal client, int win2k, krb5_get_init_creds_ctx *ctx, METHOD_DATA *md) { if (ctx->pk_init_ctx == NULL) return 0; #ifdef PKINIT return _krb5_pk_mk_padata(context, ctx->pk_init_ctx, ctx->ic_flags, win2k, &a->req_body, ctx->pk_nonce, md); #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } static krb5_error_code pa_data_add_pac_request(krb5_context context, krb5_get_init_creds_ctx *ctx, METHOD_DATA *md) { size_t len = 0, length; krb5_error_code ret; PA_PAC_REQUEST req; void *buf; switch (ctx->req_pac) { case KRB5_INIT_CREDS_TRISTATE_UNSET: return 0; /* don't bother */ case KRB5_INIT_CREDS_TRISTATE_TRUE: req.include_pac = 1; break; case KRB5_INIT_CREDS_TRISTATE_FALSE: req.include_pac = 0; } ASN1_MALLOC_ENCODE(PA_PAC_REQUEST, buf, length, &req, &len, ret); if (ret) return ret; if(len != length) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_padata_add(context, md, KRB5_PADATA_PA_PAC_REQUEST, buf, len); if (ret) free(buf); return 0; } /* * Assumes caller always will free `out_md', even on error. */ static krb5_error_code process_pa_data_to_md(krb5_context context, const krb5_creds *creds, const AS_REQ *a, krb5_get_init_creds_ctx *ctx, METHOD_DATA *in_md, METHOD_DATA **out_md, krb5_prompter_fct prompter, void *prompter_data) { krb5_error_code ret; ALLOC(*out_md, 1); if (*out_md == NULL) return krb5_enomem(context); (*out_md)->len = 0; (*out_md)->val = NULL; if (_krb5_have_debug(context, 5)) { unsigned i; _krb5_debug(context, 5, "KDC send %d patypes", in_md->len); for (i = 0; i < in_md->len; i++) _krb5_debug(context, 5, "KDC send PA-DATA type: %d", in_md->val[i].padata_type); } /* * Make sure we don't sent both ENC-TS and PK-INIT pa data, no * need to expose our password protecting our PKCS12 key. */ if (ctx->pk_init_ctx) { _krb5_debug(context, 5, "krb5_get_init_creds: " "prepareing PKINIT padata (%s)", (ctx->used_pa_types & USED_PKINIT_W2K) ? "win2k" : "ietf"); if (ctx->used_pa_types & USED_PKINIT_W2K) { krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, "Already tried pkinit, looping"); return KRB5_GET_IN_TKT_LOOP; } ret = pa_data_to_md_pkinit(context, a, creds->client, (ctx->used_pa_types & USED_PKINIT), ctx, *out_md); if (ret) return ret; if (ctx->used_pa_types & USED_PKINIT) ctx->used_pa_types |= USED_PKINIT_W2K; else ctx->used_pa_types |= USED_PKINIT; } else if (in_md->len != 0) { struct pa_info_data *paid, *ppaid; unsigned flag; paid = calloc(1, sizeof(*paid)); if (paid == NULL) return krb5_enomem(context); paid->etype = KRB5_ENCTYPE_NULL; ppaid = process_pa_info(context, creds->client, a, paid, in_md); if (ppaid) flag = USED_ENC_TS_INFO; else flag = USED_ENC_TS_GUESS; if (ctx->used_pa_types & flag) { if (ppaid) free_paid(context, ppaid); free(paid); krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, "Already tried ENC-TS-%s, looping", flag == USED_ENC_TS_INFO ? "info" : "guess"); return KRB5_GET_IN_TKT_LOOP; } pa_data_to_md_ts_enc(context, a, creds->client, ctx, ppaid, *out_md); ctx->used_pa_types |= flag; if (ppaid) { if (ctx->ppaid) { free_paid(context, ctx->ppaid); free(ctx->ppaid); } ctx->ppaid = ppaid; } else free(paid); } pa_data_add_pac_request(context, ctx, *out_md); if ((ctx->fast_state.flags & KRB5_FAST_DISABLED) == 0) { ret = krb5_padata_add(context, *out_md, KRB5_PADATA_REQ_ENC_PA_REP, NULL, 0); if (ret) return ret; } if ((*out_md)->len == 0) { free(*out_md); *out_md = NULL; } return 0; } static krb5_error_code process_pa_data_to_key(krb5_context context, krb5_get_init_creds_ctx *ctx, krb5_creds *creds, AS_REQ *a, AS_REP *rep, const krb5_krbhst_info *hi, krb5_keyblock **key) { struct pa_info_data paid, *ppaid = NULL; krb5_error_code ret; krb5_enctype etype; PA_DATA *pa; memset(&paid, 0, sizeof(paid)); etype = rep->enc_part.etype; if (rep->padata) { paid.etype = etype; ppaid = process_pa_info(context, creds->client, a, &paid, rep->padata); } if (ppaid == NULL) ppaid = ctx->ppaid; if (ppaid == NULL) { ret = krb5_get_pw_salt (context, creds->client, &paid.salt); if (ret) return ret; paid.etype = etype; paid.s2kparams = NULL; ppaid = &paid; } pa = NULL; if (rep->padata) { int idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP, &idx); if (pa == NULL) { idx = 0; pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_PK_AS_REP_19, &idx); } } if (pa && ctx->pk_init_ctx) { #ifdef PKINIT _krb5_debug(context, 5, "krb5_get_init_creds: using PKINIT"); ret = _krb5_pk_rd_pa_reply(context, a->req_body.realm, ctx->pk_init_ctx, etype, hi, ctx->pk_nonce, &ctx->req_buffer, pa, key); #else ret = EINVAL; krb5_set_error_message(context, ret, N_("no support for PKINIT compiled in", "")); #endif } else if (ctx->keyseed) { _krb5_debug(context, 5, "krb5_get_init_creds: using keyproc"); ret = pa_data_to_key_plain(context, creds->client, ctx, ppaid->salt, ppaid->s2kparams, etype, key); } else { ret = EINVAL; krb5_set_error_message(context, ret, N_("No usable pa data type", "")); } free_paid(context, &paid); return ret; } /** * Start a new context to get a new initial credential. * * @param context A Kerberos 5 context. * @param client The Kerberos principal to get the credential for, if * NULL is given, the default principal is used as determined by * krb5_get_default_principal(). * @param prompter * @param prompter_data * @param start_time the time the ticket should start to be valid or 0 for now. * @param options a options structure, can be NULL for default options. * @param rctx A new allocated free with krb5_init_creds_free(). * * @return 0 for success or an Kerberos 5 error code, see krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_init(krb5_context context, krb5_principal client, krb5_prompter_fct prompter, void *prompter_data, krb5_deltat start_time, krb5_get_init_creds_opt *options, krb5_init_creds_context *rctx) { krb5_init_creds_context ctx; krb5_error_code ret; *rctx = NULL; ctx = calloc(1, sizeof(*ctx)); if (ctx == NULL) return krb5_enomem(context); ret = get_init_creds_common(context, client, start_time, options, ctx); if (ret) { free(ctx); return ret; } /* Set a new nonce. */ krb5_generate_random_block (&ctx->nonce, sizeof(ctx->nonce)); ctx->nonce &= 0x7fffffff; /* XXX these just needs to be the same when using Windows PK-INIT */ ctx->pk_nonce = ctx->nonce; ctx->prompter = prompter; ctx->prompter_data = prompter_data; *rctx = ctx; return ret; } /** * Sets the service that the is requested. This call is only neede for * special initial tickets, by default the a krbtgt is fetched in the default realm. * * @param context a Kerberos 5 context. * @param ctx a krb5_init_creds_context context. * @param service the service given as a string, for example * "kadmind/admin". If NULL, the default krbtgt in the clients * realm is set. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_service(krb5_context context, krb5_init_creds_context ctx, const char *service) { krb5_const_realm client_realm; krb5_principal principal; krb5_error_code ret; client_realm = krb5_principal_get_realm (context, ctx->cred.client); if (service) { ret = krb5_parse_name (context, service, &principal); if (ret) return ret; krb5_principal_set_realm (context, principal, client_realm); } else { ret = krb5_make_principal(context, &principal, client_realm, KRB5_TGS_NAME, client_realm, NULL); if (ret) return ret; } /* * This is for Windows RODC that are picky about what name type * the server principal have, and the really strange part is that * they are picky about the AS-REQ name type and not the TGS-REQ * later. Oh well. */ if (krb5_principal_is_krbtgt(context, principal)) krb5_principal_set_type(context, principal, KRB5_NT_SRV_INST); krb5_free_principal(context, ctx->cred.server); ctx->cred.server = principal; return 0; } /** * Sets the password that will use for the request. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param password the password to use. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_password(krb5_context context, krb5_init_creds_context ctx, const char *password) { if (ctx->password) { memset(ctx->password, 0, strlen(ctx->password)); free(ctx->password); } if (password) { ctx->password = strdup(password); if (ctx->password == NULL) return krb5_enomem(context); ctx->keyseed = (void *) ctx->password; } else { ctx->keyseed = NULL; ctx->password = NULL; } return 0; } static krb5_error_code KRB5_CALLCONV keytab_key_proc(krb5_context context, krb5_enctype enctype, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { krb5_keytab_key_proc_args *args = rk_UNCONST(keyseed); krb5_keytab keytab = args->keytab; krb5_principal principal = args->principal; krb5_error_code ret; krb5_keytab real_keytab; krb5_keytab_entry entry; if(keytab == NULL) krb5_kt_default(context, &real_keytab); else real_keytab = keytab; ret = krb5_kt_get_entry (context, real_keytab, principal, 0, enctype, &entry); if (keytab == NULL) krb5_kt_close (context, real_keytab); if (ret) return ret; ret = krb5_copy_keyblock (context, &entry.keyblock, key); krb5_kt_free_entry(context, &entry); return ret; } /** * Set the keytab to use for authentication. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param keytab the keytab to read the key from. * * @return 0 for success, or an Kerberos 5 error code, see krb5_get_error_message(). * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keytab(krb5_context context, krb5_init_creds_context ctx, krb5_keytab keytab) { krb5_keytab_key_proc_args *a; krb5_keytab_entry entry; krb5_kt_cursor cursor; krb5_enctype *etypes = NULL; krb5_error_code ret; size_t netypes = 0; int kvno = 0, found = 0; a = malloc(sizeof(*a)); if (a == NULL) return krb5_enomem(context); a->principal = ctx->cred.client; a->keytab = keytab; ctx->keytab_data = a; ctx->keyseed = (void *)a; ctx->keyproc = keytab_key_proc; /* * We need to the KDC what enctypes we support for this keytab, * esp if the keytab is really a password based entry, then the * KDC might have more enctypes in the database then what we have * in the keytab. */ ret = krb5_kt_start_seq_get(context, keytab, &cursor); if(ret) goto out; while(krb5_kt_next_entry(context, keytab, &entry, &cursor) == 0){ void *ptr; if (!krb5_principal_compare(context, entry.principal, ctx->cred.client)) goto next; found = 1; /* check if we ahve this kvno already */ if (entry.vno > kvno) { /* remove old list of etype */ if (etypes) free(etypes); etypes = NULL; netypes = 0; kvno = entry.vno; } else if (entry.vno != kvno) goto next; /* check if enctype is supported */ if (krb5_enctype_valid(context, entry.keyblock.keytype) != 0) goto next; /* add enctype to supported list */ ptr = realloc(etypes, sizeof(etypes[0]) * (netypes + 2)); if (ptr == NULL) { free(etypes); ret = krb5_enomem(context); goto out; } etypes = ptr; etypes[netypes] = entry.keyblock.keytype; etypes[netypes + 1] = ETYPE_NULL; netypes++; next: krb5_kt_free_entry(context, &entry); } krb5_kt_end_seq_get(context, keytab, &cursor); if (etypes) { if (ctx->etypes) free(ctx->etypes); ctx->etypes = etypes; } out: if (!found) { if (ret == 0) ret = KRB5_KT_NOTFOUND; _krb5_kt_principal_not_found(context, ret, keytab, ctx->cred.client, 0, 0); } return ret; } static krb5_error_code KRB5_CALLCONV keyblock_key_proc(krb5_context context, krb5_enctype enctype, krb5_const_pointer keyseed, krb5_salt salt, krb5_data *s2kparms, krb5_keyblock **key) { return krb5_copy_keyblock (context, keyseed, key); } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_keyblock(krb5_context context, krb5_init_creds_context ctx, krb5_keyblock *keyblock) { ctx->keyseed = (void *)keyblock; ctx->keyproc = keyblock_key_proc; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ccache(krb5_context context, krb5_init_creds_context ctx, krb5_ccache fast_ccache) { ctx->fast_state.armor_ccache = fast_ccache; ctx->fast_state.flags |= KRB5_FAST_REQUIRED; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_set_fast_ap_armor_service(krb5_context context, krb5_init_creds_context ctx, krb5_const_principal armor_service) { krb5_error_code ret; if (ctx->fast_state.armor_service) krb5_free_principal(context, ctx->fast_state.armor_service); if (armor_service) { ret = krb5_copy_principal(context, armor_service, &ctx->fast_state.armor_service); if (ret) return ret; } else { ctx->fast_state.armor_service = NULL; } ctx->fast_state.flags |= KRB5_FAST_REQUIRED | KRB5_FAST_AP_ARMOR_SERVICE; return 0; } /* * FAST */ static krb5_error_code check_fast(krb5_context context, struct fast_state *state) { if (state->flags & KRB5_FAST_EXPECTED) { krb5_set_error_message(context, KRB5KRB_AP_ERR_MODIFIED, "Expected FAST, but no FAST " "was in the response from the KDC"); return KRB5KRB_AP_ERR_MODIFIED; } return 0; } static krb5_error_code fast_unwrap_as_rep(krb5_context context, int32_t nonce, krb5_data *chksumdata, struct fast_state *state, AS_REP *rep) { PA_FX_FAST_REPLY fxfastrep; KrbFastResponse fastrep; krb5_error_code ret; PA_DATA *pa = NULL; int idx = 0; if (state->armor_crypto == NULL || rep->padata == NULL) return check_fast(context, state); /* find PA_FX_FAST_REPLY */ pa = krb5_find_padata(rep->padata->val, rep->padata->len, KRB5_PADATA_FX_FAST, &idx); if (pa == NULL) return check_fast(context, state); memset(&fxfastrep, 0, sizeof(fxfastrep)); memset(&fastrep, 0, sizeof(fastrep)); ret = decode_PA_FX_FAST_REPLY(pa->padata_value.data, pa->padata_value.length, &fxfastrep, NULL); if (ret) return ret; if (fxfastrep.element == choice_PA_FX_FAST_REPLY_armored_data) { krb5_data data; ret = krb5_decrypt_EncryptedData(context, state->armor_crypto, KRB5_KU_FAST_REP, &fxfastrep.u.armored_data.enc_fast_rep, &data); if (ret) goto out; ret = decode_KrbFastResponse(data.data, data.length, &fastrep, NULL); krb5_data_free(&data); if (ret) goto out; } else { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } free_METHOD_DATA(rep->padata); ret = copy_METHOD_DATA(&fastrep.padata, rep->padata); if (ret) goto out; if (fastrep.strengthen_key) { if (state->strengthen_key) krb5_free_keyblock(context, state->strengthen_key); ret = krb5_copy_keyblock(context, fastrep.strengthen_key, &state->strengthen_key); if (ret) goto out; } if (nonce != fastrep.nonce) { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } if (fastrep.finished) { PrincipalName cname; krb5_realm crealm = NULL; if (chksumdata == NULL) { ret = KRB5KDC_ERR_PREAUTH_FAILED; goto out; } ret = krb5_verify_checksum(context, state->armor_crypto, KRB5_KU_FAST_FINISHED, chksumdata->data, chksumdata->length, &fastrep.finished->ticket_checksum); if (ret) goto out; /* update */ ret = copy_Realm(&fastrep.finished->crealm, &crealm); if (ret) goto out; free_Realm(&rep->crealm); rep->crealm = crealm; ret = copy_PrincipalName(&fastrep.finished->cname, &cname); if (ret) goto out; free_PrincipalName(&rep->cname); rep->cname = cname; #if 0 /* store authenticated checksum as kdc-offset */ fastrep->finished.timestamp; fastrep->finished.usec = 0; #endif } else if (chksumdata) { /* expected fastrep.finish but didn't get it */ ret = KRB5KDC_ERR_PREAUTH_FAILED; } out: free_PA_FX_FAST_REPLY(&fxfastrep); return ret; } static krb5_error_code fast_unwrap_error(krb5_context context, struct fast_state *state, KRB_ERROR *error) { if (state->armor_crypto == NULL) return check_fast(context, state); return 0; } krb5_error_code _krb5_make_fast_ap_fxarmor(krb5_context context, krb5_ccache armor_ccache, krb5_data *armor_value, krb5_keyblock *armor_key, krb5_crypto *armor_crypto) { krb5_auth_context auth_context = NULL; krb5_creds cred, *credp = NULL; krb5_error_code ret; krb5_data empty; krb5_data_zero(&empty); memset(&cred, 0, sizeof(cred)); ret = krb5_auth_con_init (context, &auth_context); if (ret) goto out; ret = krb5_cc_get_principal(context, armor_ccache, &cred.client); if (ret) goto out; ret = krb5_make_principal(context, &cred.server, cred.client->realm, KRB5_TGS_NAME, cred.client->realm, NULL); if (ret) { krb5_free_principal(context, cred.client); goto out; } ret = krb5_get_credentials(context, 0, armor_ccache, &cred, &credp); krb5_free_principal(context, cred.server); krb5_free_principal(context, cred.client); if (ret) goto out; ret = krb5_auth_con_add_AuthorizationData(context, auth_context, KRB5_PADATA_FX_FAST_ARMOR, &empty); if (ret) goto out; ret = krb5_mk_req_extended(context, &auth_context, AP_OPTS_USE_SUBKEY, NULL, credp, armor_value); krb5_free_creds(context, credp); if (ret) goto out; ret = _krb5_fast_armor_key(context, auth_context->local_subkey, auth_context->keyblock, armor_key, armor_crypto); if (ret) goto out; out: krb5_auth_con_free(context, auth_context); return ret; } #ifndef WIN32 static heim_base_once_t armor_service_once = HEIM_BASE_ONCE_INIT; static heim_ipc armor_service = NULL; static void fast_armor_init_ipc(void *ctx) { heim_ipc *ipc = ctx; heim_ipc_init_context("ANY:org.h5l.armor-service", ipc); } #endif /* WIN32 */ static krb5_error_code make_fast_ap_fxarmor(krb5_context context, struct fast_state *state, const char *realm, KrbFastArmor **armor) { KrbFastArmor *fxarmor = NULL; krb5_error_code ret; if (state->armor_crypto) krb5_crypto_destroy(context, state->armor_crypto); krb5_free_keyblock_contents(context, &state->armor_key); ALLOC(fxarmor, 1); if (fxarmor == NULL) return krb5_enomem(context); if (state->flags & KRB5_FAST_AP_ARMOR_SERVICE) { #ifdef WIN32 krb5_set_error_message(context, ENOTSUP, "Fast armor IPC service not supportted yet on Windows"); ret = ENOTSUP; goto out; #else /* WIN32 */ KERB_ARMOR_SERVICE_REPLY msg; krb5_data request, reply; heim_base_once_f(&armor_service_once, &armor_service, fast_armor_init_ipc); if (armor_service == NULL) { krb5_set_error_message(context, ENOENT, "Failed to open fast armor service"); ret = ENOENT; goto out; } krb5_data_zero(&reply); request.data = rk_UNCONST(realm); request.length = strlen(realm); ret = heim_ipc_call(armor_service, &request, &reply, NULL); heim_release(send); if (ret) { krb5_set_error_message(context, ret, "Failed to get armor service credential"); goto out; } ret = decode_KERB_ARMOR_SERVICE_REPLY(reply.data, reply.length, &msg, NULL); krb5_data_free(&reply); if (ret) goto out; ret = copy_KrbFastArmor(fxarmor, &msg.armor); if (ret) { free_KERB_ARMOR_SERVICE_REPLY(&msg); goto out; } ret = krb5_copy_keyblock_contents(context, &msg.armor_key, &state->armor_key); free_KERB_ARMOR_SERVICE_REPLY(&msg); if (ret) goto out; ret = krb5_crypto_init(context, &state->armor_key, 0, &state->armor_crypto); if (ret) goto out; #endif /* WIN32 */ } else { fxarmor->armor_type = 1; ret = _krb5_make_fast_ap_fxarmor(context, state->armor_ccache, &fxarmor->armor_value, &state->armor_key, &state->armor_crypto); if (ret) goto out; } *armor = fxarmor; fxarmor = NULL; out: if (fxarmor) { free_KrbFastArmor(fxarmor); free(fxarmor); } return ret; } static krb5_error_code fast_wrap_req(krb5_context context, struct fast_state *state, KDC_REQ *req) { KrbFastArmor *fxarmor = NULL; PA_FX_FAST_REQUEST fxreq; krb5_error_code ret; KrbFastReq fastreq; krb5_data data; size_t size; if (state->flags & KRB5_FAST_DISABLED) { _krb5_debug(context, 10, "fast disabled, not doing any fast wrapping"); return 0; } memset(&fxreq, 0, sizeof(fxreq)); memset(&fastreq, 0, sizeof(fastreq)); krb5_data_zero(&data); if (state->armor_crypto == NULL) { if (state->armor_ccache) { /* * Instead of keeping state in FX_COOKIE in the KDC, we * rebuild a new armor key for every request, because this * is what the MIT KDC expect and RFC6113 is vage about * what the behavior should be. */ state->type = choice_PA_FX_FAST_REQUEST_armored_data; } else { return check_fast(context, state); } } state->flags |= KRB5_FAST_EXPECTED; fastreq.fast_options.hide_client_names = 1; ret = copy_KDC_REQ_BODY(&req->req_body, &fastreq.req_body); free_KDC_REQ_BODY(&req->req_body); req->req_body.realm = strdup(KRB5_ANON_REALM); if ((ALLOC(req->req_body.cname, 1)) != NULL) { req->req_body.cname->name_type = KRB5_NT_WELLKNOWN; if ((ALLOC(req->req_body.cname->name_string.val, 2)) != NULL) { req->req_body.cname->name_string.len = 2; req->req_body.cname->name_string.val[0] = strdup(KRB5_WELLKNOWN_NAME); req->req_body.cname->name_string.val[1] = strdup(KRB5_ANON_NAME); if (req->req_body.cname->name_string.val[0] == NULL || req->req_body.cname->name_string.val[1] == NULL) ret = krb5_enomem(context); } else ret = krb5_enomem(context); } else ret = krb5_enomem(context); if ((ALLOC(req->req_body.till, 1)) != NULL) *req->req_body.till = 0; else ret = krb5_enomem(context); if (ret) goto out; if (req->padata) { ret = copy_METHOD_DATA(req->padata, &fastreq.padata); free_METHOD_DATA(req->padata); } else { if ((ALLOC(req->padata, 1)) == NULL) ret = krb5_enomem(context); } if (ret) goto out; ASN1_MALLOC_ENCODE(KrbFastReq, data.data, data.length, &fastreq, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); fxreq.element = state->type; if (state->type == choice_PA_FX_FAST_REQUEST_armored_data) { size_t len; void *buf; ret = make_fast_ap_fxarmor(context, state, fastreq.req_body.realm, &fxreq.u.armored_data.armor); if (ret) goto out; heim_assert(state->armor_crypto != NULL, "FAST armor key missing when FAST started"); ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, len, &req->req_body, &size, ret); if (ret) goto out; heim_assert(len == size, "ASN.1 internal error"); ret = krb5_create_checksum(context, state->armor_crypto, KRB5_KU_FAST_REQ_CHKSUM, 0, buf, len, &fxreq.u.armored_data.req_checksum); free(buf); if (ret) goto out; ret = krb5_encrypt_EncryptedData(context, state->armor_crypto, KRB5_KU_FAST_ENC, data.data, data.length, 0, &fxreq.u.armored_data.enc_fast_req); krb5_data_free(&data); if (ret) goto out; } else { krb5_data_free(&data); heim_assert(false, "unknown FAST type, internal error"); } ASN1_MALLOC_ENCODE(PA_FX_FAST_REQUEST, data.data, data.length, &fxreq, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); ret = krb5_padata_add(context, req->padata, KRB5_PADATA_FX_FAST, data.data, data.length); if (ret) goto out; krb5_data_zero(&data); out: free_PA_FX_FAST_REQUEST(&fxreq); free_KrbFastReq(&fastreq); if (fxarmor) { free_KrbFastArmor(fxarmor); free(fxarmor); } krb5_data_free(&data); return ret; } /** * The core loop if krb5_get_init_creds() function family. Create the * packets and have the caller send them off to the KDC. * * If the caller want all work been done for them, use * krb5_init_creds_get() instead. * * @param context a Kerberos 5 context. * @param ctx ctx krb5_init_creds_context context. * @param in input data from KDC, first round it should be reset by krb5_data_zer(). * @param out reply to KDC. * @param hostinfo KDC address info, first round it can be NULL. * @param flags status of the round, if * KRB5_INIT_CREDS_STEP_FLAG_CONTINUE is set, continue one more round. * * @return 0 for success, or an Kerberos 5 error code, see * krb5_get_error_message(). * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_step(krb5_context context, krb5_init_creds_context ctx, krb5_data *in, krb5_data *out, krb5_krbhst_info *hostinfo, unsigned int *flags) { krb5_error_code ret; size_t len = 0; size_t size; AS_REQ req2; krb5_data_zero(out); if (ctx->as_req.req_body.cname == NULL) { ret = init_as_req(context, ctx->flags, &ctx->cred, ctx->addrs, ctx->etypes, &ctx->as_req); if (ret) { free_init_creds_ctx(context, ctx); return ret; } } #define MAX_PA_COUNTER 10 if (ctx->pa_counter > MAX_PA_COUNTER) { krb5_set_error_message(context, KRB5_GET_IN_TKT_LOOP, N_("Looping %d times while getting " "initial credentials", ""), ctx->pa_counter); return KRB5_GET_IN_TKT_LOOP; } ctx->pa_counter++; _krb5_debug(context, 5, "krb5_get_init_creds: loop %d", ctx->pa_counter); /* Lets process the input packet */ if (in && in->length) { krb5_kdc_rep rep; memset(&rep, 0, sizeof(rep)); _krb5_debug(context, 5, "krb5_get_init_creds: processing input"); ret = decode_AS_REP(in->data, in->length, &rep.kdc_rep, &size); if (ret == 0) { unsigned eflags = EXTRACT_TICKET_AS_REQ | EXTRACT_TICKET_TIMESYNC; krb5_data data; /* * Unwrap AS-REP */ ASN1_MALLOC_ENCODE(Ticket, data.data, data.length, &rep.kdc_rep.ticket, &size, ret); if (ret) goto out; heim_assert(data.length == size, "ASN.1 internal error"); ret = fast_unwrap_as_rep(context, ctx->nonce, &data, &ctx->fast_state, &rep.kdc_rep); krb5_data_free(&data); if (ret) goto out; /* * Now check and extract the ticket */ if (ctx->flags.canonicalize) { eflags |= EXTRACT_TICKET_ALLOW_SERVER_MISMATCH; eflags |= EXTRACT_TICKET_MATCH_REALM; } if (ctx->ic_flags & KRB5_INIT_CREDS_NO_C_CANON_CHECK) eflags |= EXTRACT_TICKET_ALLOW_CNAME_MISMATCH; ret = process_pa_data_to_key(context, ctx, &ctx->cred, &ctx->as_req, &rep.kdc_rep, hostinfo, &ctx->fast_state.reply_key); if (ret) { free_AS_REP(&rep.kdc_rep); goto out; } _krb5_debug(context, 5, "krb5_get_init_creds: extracting ticket"); ret = _krb5_extract_ticket(context, &rep, &ctx->cred, ctx->fast_state.reply_key, NULL, KRB5_KU_AS_REP_ENC_PART, NULL, ctx->nonce, eflags, &ctx->req_buffer, NULL, NULL); if (ret == 0) ret = copy_EncKDCRepPart(&rep.enc_part, &ctx->enc_part); krb5_free_keyblock(context, ctx->fast_state.reply_key); ctx->fast_state.reply_key = NULL; *flags = 0; free_AS_REP(&rep.kdc_rep); free_EncASRepPart(&rep.enc_part); return ret; } else { /* let's try to parse it as a KRB-ERROR */ _krb5_debug(context, 5, "krb5_get_init_creds: got an error"); free_KRB_ERROR(&ctx->error); ret = krb5_rd_error(context, in, &ctx->error); if(ret && in->length && ((char*)in->data)[0] == 4) ret = KRB5KRB_AP_ERR_V4_REPLY; if (ret) { _krb5_debug(context, 5, "krb5_get_init_creds: failed to read error"); goto out; } /* * Unwrap KRB-ERROR */ ret = fast_unwrap_error(context, &ctx->fast_state, &ctx->error); if (ret) goto out; /* * */ ret = krb5_error_from_rd_error(context, &ctx->error, &ctx->cred); _krb5_debug(context, 5, "krb5_get_init_creds: KRB-ERROR %d", ret); /* * If no preauth was set and KDC requires it, give it one * more try. */ if (ret == KRB5KDC_ERR_PREAUTH_REQUIRED) { free_METHOD_DATA(&ctx->md); memset(&ctx->md, 0, sizeof(ctx->md)); if (ctx->error.e_data) { ret = decode_METHOD_DATA(ctx->error.e_data->data, ctx->error.e_data->length, &ctx->md, NULL); if (ret) krb5_set_error_message(context, ret, N_("Failed to decode METHOD-DATA", "")); } else { krb5_set_error_message(context, ret, N_("Preauth required but no preauth " "options send by KDC", "")); } } else if (ret == KRB5KRB_AP_ERR_SKEW && context->kdc_sec_offset == 0) { /* * Try adapt to timeskrew when we are using pre-auth, and * if there was a time skew, try again. */ krb5_set_real_time(context, ctx->error.stime, -1); if (context->kdc_sec_offset) ret = 0; _krb5_debug(context, 10, "init_creds: err skew updateing kdc offset to %d", context->kdc_sec_offset); ctx->used_pa_types = 0; } else if (ret == KRB5_KDC_ERR_WRONG_REALM && ctx->flags.canonicalize) { /* client referal to a new realm */ if (ctx->error.crealm == NULL) { krb5_set_error_message(context, ret, N_("Got a client referral, not but no realm", "")); goto out; } _krb5_debug(context, 5, "krb5_get_init_creds: got referal to realm %s", *ctx->error.crealm); ret = krb5_principal_set_realm(context, ctx->cred.client, *ctx->error.crealm); if (ret) goto out; if (krb5_principal_is_krbtgt(context, ctx->cred.server)) { ret = krb5_init_creds_set_service(context, ctx, NULL); if (ret) goto out; } free_AS_REQ(&ctx->as_req); memset(&ctx->as_req, 0, sizeof(ctx->as_req)); ctx->used_pa_types = 0; } else if (ret == KRB5KDC_ERR_KEY_EXP && ctx->runflags.change_password == 0 && ctx->prompter) { char buf2[1024]; ctx->runflags.change_password = 1; ctx->prompter(context, ctx->prompter_data, NULL, N_("Password has expired", ""), 0, NULL); /* try to avoid recursion */ if (ctx->in_tkt_service != NULL && strcmp(ctx->in_tkt_service, "kadmin/changepw") == 0) goto out; /* don't try to change password where then where none */ if (ctx->prompter == NULL) goto out; ret = change_password(context, ctx->cred.client, ctx->password, buf2, sizeof(buf2), ctx->prompter, ctx->prompter_data, NULL); if (ret) goto out; krb5_init_creds_set_password(context, ctx, buf2); ctx->used_pa_types = 0; ret = 0; } else if (ret == KRB5KDC_ERR_PREAUTH_FAILED) { if (ctx->fast_state.flags & KRB5_FAST_DISABLED) goto out; if (ctx->fast_state.flags & (KRB5_FAST_REQUIRED | KRB5_FAST_EXPECTED)) goto out; _krb5_debug(context, 10, "preauth failed with FAST, " "and told by KD or user, trying w/o FAST"); ctx->fast_state.flags |= KRB5_FAST_DISABLED; ctx->used_pa_types = 0; ret = 0; } if (ret) goto out; } } if (ctx->as_req.req_body.cname == NULL) { ret = init_as_req(context, ctx->flags, &ctx->cred, ctx->addrs, ctx->etypes, &ctx->as_req); if (ret) { free_init_creds_ctx(context, ctx); return ret; } } if (ctx->as_req.padata) { free_METHOD_DATA(ctx->as_req.padata); free(ctx->as_req.padata); ctx->as_req.padata = NULL; } /* Set a new nonce. */ ctx->as_req.req_body.nonce = ctx->nonce; /* fill_in_md_data */ ret = process_pa_data_to_md(context, &ctx->cred, &ctx->as_req, ctx, &ctx->md, &ctx->as_req.padata, ctx->prompter, ctx->prompter_data); if (ret) goto out; /* * Wrap with FAST */ copy_AS_REQ(&ctx->as_req, &req2); ret = fast_wrap_req(context, &ctx->fast_state, &req2); if (ret) { free_AS_REQ(&req2); goto out; } krb5_data_free(&ctx->req_buffer); ASN1_MALLOC_ENCODE(AS_REQ, ctx->req_buffer.data, ctx->req_buffer.length, &req2, &len, ret); free_AS_REQ(&req2); if (ret) goto out; if(len != ctx->req_buffer.length) krb5_abortx(context, "internal error in ASN.1 encoder"); out->data = ctx->req_buffer.data; out->length = ctx->req_buffer.length; *flags = KRB5_INIT_CREDS_STEP_FLAG_CONTINUE; return 0; out: return ret; } /** * Extract the newly acquired credentials from krb5_init_creds_context * context. * * @param context A Kerberos 5 context. * @param ctx * @param cred credentials, free with krb5_free_cred_contents(). * * @return 0 for sucess or An Kerberos error code, see krb5_get_error_message(). */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_creds(krb5_context context, krb5_init_creds_context ctx, krb5_creds *cred) { return krb5_copy_creds_contents(context, &ctx->cred, cred); } /** * Get the last error from the transaction. * * @return Returns 0 or an error code * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get_error(krb5_context context, krb5_init_creds_context ctx, KRB_ERROR *error) { krb5_error_code ret; ret = copy_KRB_ERROR(&ctx->error, error); if (ret) krb5_enomem(context); return ret; } /** * * @ingroup krb5_credential */ krb5_error_code krb5_init_creds_store(krb5_context context, krb5_init_creds_context ctx, krb5_ccache id) { krb5_error_code ret; if (ctx->cred.client == NULL) { ret = KRB5KDC_ERR_PREAUTH_REQUIRED; krb5_set_error_message(context, ret, "init creds not completed yet"); return ret; } ret = krb5_cc_initialize(context, id, ctx->cred.client); if (ret) return ret; ret = krb5_cc_store_cred(context, id, &ctx->cred); if (ret) return ret; if (ctx->cred.flags.b.enc_pa_rep) { krb5_data data = { 3, rk_UNCONST("yes") }; ret = krb5_cc_set_config(context, id, ctx->cred.server, "fast_avail", &data); if (ret) return ret; } return ret; } /** * Free the krb5_init_creds_context allocated by krb5_init_creds_init(). * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to free. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL krb5_init_creds_free(krb5_context context, krb5_init_creds_context ctx) { free_init_creds_ctx(context, ctx); free(ctx); } /** * Get new credentials as setup by the krb5_init_creds_context. * * @param context A Kerberos 5 context. * @param ctx The krb5_init_creds_context to process. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_init_creds_get(krb5_context context, krb5_init_creds_context ctx) { krb5_sendto_ctx stctx = NULL; krb5_krbhst_info *hostinfo = NULL; krb5_error_code ret; krb5_data in, out; unsigned int flags = 0; krb5_data_zero(&in); krb5_data_zero(&out); ret = krb5_sendto_ctx_alloc(context, &stctx); if (ret) goto out; krb5_sendto_ctx_set_func(stctx, _krb5_kdc_retry, NULL); while (1) { flags = 0; ret = krb5_init_creds_step(context, ctx, &in, &out, hostinfo, &flags); krb5_data_free(&in); if (ret) goto out; if ((flags & 1) == 0) break; ret = krb5_sendto_context (context, stctx, &out, ctx->cred.client->realm, &in); if (ret) goto out; } out: if (stctx) krb5_sendto_ctx_free(context, stctx); return ret; } /** * Get new credentials using password. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_password(krb5_context context, krb5_creds *creds, krb5_principal client, const char *password, krb5_prompter_fct prompter, void *data, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; char buf[BUFSIZ], buf2[BUFSIZ]; krb5_error_code ret; int chpw = 0; again: ret = krb5_init_creds_init(context, client, prompter, data, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; if (prompter != NULL && ctx->password == NULL && password == NULL) { krb5_prompt prompt; krb5_data password_data; char *p, *q = NULL; int aret; ret = krb5_unparse_name(context, client, &p); if (ret) goto out; aret = asprintf(&q, "%s's Password: ", p); free (p); if (aret == -1 || q == NULL) { ret = krb5_enomem(context); goto out; } prompt.prompt = q; password_data.data = buf; password_data.length = sizeof(buf); prompt.hidden = 1; prompt.reply = &password_data; prompt.type = KRB5_PROMPT_TYPE_PASSWORD; ret = (*prompter) (context, data, NULL, NULL, 1, &prompt); free (q); if (ret) { memset (buf, 0, sizeof(buf)); ret = KRB5_LIBOS_PWDINTR; krb5_clear_error_message (context); goto out; } password = password_data.data; } if (password) { ret = krb5_init_creds_set_password(context, ctx, password); if (ret) goto out; } ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); if (ret == KRB5KDC_ERR_KEY_EXPIRED && chpw == 0) { /* try to avoid recursion */ if (in_tkt_service != NULL && strcmp(in_tkt_service, "kadmin/changepw") == 0) goto out; /* don't try to change password where then where none */ if (prompter == NULL) goto out; if ((options->flags & KRB5_GET_INIT_CREDS_OPT_CHANGE_PASSWORD_PROMPT) && !options->change_password_prompt) goto out; ret = change_password (context, client, ctx->password, buf2, sizeof(buf2), prompter, data, options); if (ret) goto out; password = buf2; chpw = 1; krb5_init_creds_free(context, ctx); goto again; } out: if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); memset(buf, 0, sizeof(buf)); memset(buf2, 0, sizeof(buf2)); return ret; } /** * Get new credentials using keyblock. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keyblock(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_keyblock *keyblock, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; krb5_error_code ret; memset(creds, 0, sizeof(*creds)); ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; ret = krb5_init_creds_set_keyblock(context, ctx, keyblock); if (ret) goto out; ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); out: if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); return ret; } /** * Get new credentials using keytab. * * @ingroup krb5_credential */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_keytab(krb5_context context, krb5_creds *creds, krb5_principal client, krb5_keytab keytab, krb5_deltat start_time, const char *in_tkt_service, krb5_get_init_creds_opt *options) { krb5_init_creds_context ctx; krb5_keytab_entry ktent; krb5_error_code ret; memset(&ktent, 0, sizeof(ktent)); memset(creds, 0, sizeof(*creds)); if (strcmp(client->realm, "") == 0) { /* * Referral realm. We have a keytab, so pick a realm by * matching in the keytab. */ ret = krb5_kt_get_entry(context, keytab, client, 0, 0, &ktent); if (ret == 0) client = ktent.principal; } ret = krb5_init_creds_init(context, client, NULL, NULL, start_time, options, &ctx); if (ret) goto out; ret = krb5_init_creds_set_service(context, ctx, in_tkt_service); if (ret) goto out; ret = krb5_init_creds_set_keytab(context, ctx, keytab); if (ret) goto out; ret = krb5_init_creds_get(context, ctx); if (ret == 0) krb5_process_last_request(context, options, ctx); out: krb5_kt_free_entry(context, &ktent); if (ret == 0) krb5_init_creds_get_creds(context, ctx, creds); if (ctx) krb5_init_creds_free(context, ctx); return ret; }
./CrossVul/dataset_final_sorted/CWE-320/c/bad_857_0
crossvul-cpp_data_good_857_2
/* * Copyright (c) 2003 - 2016 Kungliga Tekniska Högskolan * (Royal Institute of Technology, Stockholm, Sweden). * All rights reserved. * * Portions Copyright (c) 2009 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE 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. */ #include "krb5_locl.h" struct krb5_dh_moduli { char *name; unsigned long bits; heim_integer p; heim_integer g; heim_integer q; }; #ifdef PKINIT #include <cms_asn1.h> #include <pkcs8_asn1.h> #include <pkcs9_asn1.h> #include <pkcs12_asn1.h> #include <pkinit_asn1.h> #include <asn1_err.h> #include <der.h> struct krb5_pk_cert { hx509_cert cert; }; static void pk_copy_error(krb5_context context, hx509_context hx509ctx, int hxret, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 4, 5))); /* * */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_pk_cert_free(struct krb5_pk_cert *cert) { if (cert->cert) { hx509_cert_free(cert->cert); } free(cert); } static krb5_error_code BN_to_integer(krb5_context context, BIGNUM *bn, heim_integer *integer) { integer->length = BN_num_bytes(bn); integer->data = malloc(integer->length); if (integer->data == NULL) { krb5_clear_error_message(context); return ENOMEM; } BN_bn2bin(bn, integer->data); integer->negative = BN_is_negative(bn); return 0; } static BIGNUM * integer_to_BN(krb5_context context, const char *field, const heim_integer *f) { BIGNUM *bn; bn = BN_bin2bn((const unsigned char *)f->data, f->length, NULL); if (bn == NULL) { krb5_set_error_message(context, ENOMEM, N_("PKINIT: parsing BN failed %s", ""), field); return NULL; } BN_set_negative(bn, f->negative); return bn; } static krb5_error_code select_dh_group(krb5_context context, DH *dh, unsigned long bits, struct krb5_dh_moduli **moduli) { const struct krb5_dh_moduli *m; if (bits == 0) { m = moduli[1]; /* XXX */ if (m == NULL) m = moduli[0]; /* XXX */ } else { int i; for (i = 0; moduli[i] != NULL; i++) { if (bits < moduli[i]->bits) break; } if (moduli[i] == NULL) { krb5_set_error_message(context, EINVAL, N_("Did not find a DH group parameter " "matching requirement of %lu bits", ""), bits); return EINVAL; } m = moduli[i]; } dh->p = integer_to_BN(context, "p", &m->p); if (dh->p == NULL) return ENOMEM; dh->g = integer_to_BN(context, "g", &m->g); if (dh->g == NULL) return ENOMEM; dh->q = integer_to_BN(context, "q", &m->q); if (dh->q == NULL) return ENOMEM; return 0; } struct certfind { const char *type; const heim_oid *oid; }; /* * Try searchin the key by to use by first looking for for PK-INIT * EKU, then the Microsoft smart card EKU and last, no special EKU at all. */ static krb5_error_code find_cert(krb5_context context, struct krb5_pk_identity *id, hx509_query *q, hx509_cert *cert) { struct certfind cf[4] = { { "MobileMe EKU", NULL }, { "PKINIT EKU", NULL }, { "MS EKU", NULL }, { "any (or no)", NULL } }; int ret = HX509_CERT_NOT_FOUND; size_t i, start = 1; unsigned oids[] = { 1, 2, 840, 113635, 100, 3, 2, 1 }; const heim_oid mobileMe = { sizeof(oids)/sizeof(oids[0]), oids }; if (id->flags & PKINIT_BTMM) start = 0; cf[0].oid = &mobileMe; cf[1].oid = &asn1_oid_id_pkekuoid; cf[2].oid = &asn1_oid_id_pkinit_ms_eku; cf[3].oid = NULL; for (i = start; i < sizeof(cf)/sizeof(cf[0]); i++) { ret = hx509_query_match_eku(q, cf[i].oid); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed setting %s OID", cf[i].type); return ret; } ret = hx509_certs_find(context->hx509ctx, id->certs, q, cert); if (ret == 0) break; pk_copy_error(context, context->hx509ctx, ret, "Failed finding certificate with %s OID", cf[i].type); } return ret; } static krb5_error_code create_signature(krb5_context context, const heim_oid *eContentType, krb5_data *eContent, struct krb5_pk_identity *id, hx509_peer_info peer, krb5_data *sd_data) { int ret, flags = 0; if (id->cert == NULL) flags |= HX509_CMS_SIGNATURE_NO_SIGNER; ret = hx509_cms_create_signed_1(context->hx509ctx, flags, eContentType, eContent->data, eContent->length, NULL, id->cert, peer, NULL, id->certs, sd_data); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Create CMS signedData"); return ret; } return 0; } static int cert2epi(hx509_context context, void *ctx, hx509_cert c) { ExternalPrincipalIdentifiers *ids = ctx; ExternalPrincipalIdentifier id; hx509_name subject = NULL; void *p; int ret; if (ids->len > 10) return 0; memset(&id, 0, sizeof(id)); ret = hx509_cert_get_subject(c, &subject); if (ret) return ret; if (hx509_name_is_null_p(subject) != 0) { id.subjectName = calloc(1, sizeof(*id.subjectName)); if (id.subjectName == NULL) { hx509_name_free(&subject); free_ExternalPrincipalIdentifier(&id); return ENOMEM; } ret = hx509_name_binary(subject, id.subjectName); if (ret) { hx509_name_free(&subject); free_ExternalPrincipalIdentifier(&id); return ret; } } hx509_name_free(&subject); id.issuerAndSerialNumber = calloc(1, sizeof(*id.issuerAndSerialNumber)); if (id.issuerAndSerialNumber == NULL) { free_ExternalPrincipalIdentifier(&id); return ENOMEM; } { IssuerAndSerialNumber iasn; hx509_name issuer; size_t size = 0; memset(&iasn, 0, sizeof(iasn)); ret = hx509_cert_get_issuer(c, &issuer); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } ret = hx509_name_to_Name(issuer, &iasn.issuer); hx509_name_free(&issuer); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } ret = hx509_cert_get_serialnumber(c, &iasn.serialNumber); if (ret) { free_IssuerAndSerialNumber(&iasn); free_ExternalPrincipalIdentifier(&id); return ret; } ASN1_MALLOC_ENCODE(IssuerAndSerialNumber, id.issuerAndSerialNumber->data, id.issuerAndSerialNumber->length, &iasn, &size, ret); free_IssuerAndSerialNumber(&iasn); if (ret) { free_ExternalPrincipalIdentifier(&id); return ret; } if (id.issuerAndSerialNumber->length != size) abort(); } id.subjectKeyIdentifier = NULL; p = realloc(ids->val, sizeof(ids->val[0]) * (ids->len + 1)); if (p == NULL) { free_ExternalPrincipalIdentifier(&id); return ENOMEM; } ids->val = p; ids->val[ids->len] = id; ids->len++; return 0; } static krb5_error_code build_edi(krb5_context context, hx509_context hx509ctx, hx509_certs certs, ExternalPrincipalIdentifiers *ids) { return hx509_certs_iter_f(hx509ctx, certs, cert2epi, ids); } static krb5_error_code build_auth_pack(krb5_context context, unsigned nonce, krb5_pk_init_ctx ctx, const KDC_REQ_BODY *body, AuthPack *a) { size_t buf_size, len = 0; krb5_error_code ret; void *buf; krb5_timestamp sec; int32_t usec; Checksum checksum; krb5_clear_error_message(context); memset(&checksum, 0, sizeof(checksum)); krb5_us_timeofday(context, &sec, &usec); a->pkAuthenticator.ctime = sec; a->pkAuthenticator.nonce = nonce; ASN1_MALLOC_ENCODE(KDC_REQ_BODY, buf, buf_size, body, &len, ret); if (ret) return ret; if (buf_size != len) krb5_abortx(context, "internal error in ASN.1 encoder"); ret = krb5_create_checksum(context, NULL, 0, CKSUMTYPE_SHA1, buf, len, &checksum); free(buf); if (ret) return ret; ALLOC(a->pkAuthenticator.paChecksum, 1); if (a->pkAuthenticator.paChecksum == NULL) { return krb5_enomem(context); } ret = krb5_data_copy(a->pkAuthenticator.paChecksum, checksum.checksum.data, checksum.checksum.length); free_Checksum(&checksum); if (ret) return ret; if (ctx->keyex == USE_DH || ctx->keyex == USE_ECDH) { const char *moduli_file; unsigned long dh_min_bits; krb5_data dhbuf; size_t size = 0; krb5_data_zero(&dhbuf); moduli_file = krb5_config_get_string(context, NULL, "libdefaults", "moduli", NULL); dh_min_bits = krb5_config_get_int_default(context, NULL, 0, "libdefaults", "pkinit_dh_min_bits", NULL); ret = _krb5_parse_moduli(context, moduli_file, &ctx->m); if (ret) return ret; ctx->u.dh = DH_new(); if (ctx->u.dh == NULL) return krb5_enomem(context); ret = select_dh_group(context, ctx->u.dh, dh_min_bits, ctx->m); if (ret) return ret; if (DH_generate_key(ctx->u.dh) != 1) { krb5_set_error_message(context, ENOMEM, N_("pkinit: failed to generate DH key", "")); return ENOMEM; } if (1 /* support_cached_dh */) { ALLOC(a->clientDHNonce, 1); if (a->clientDHNonce == NULL) { krb5_clear_error_message(context); return ENOMEM; } ret = krb5_data_alloc(a->clientDHNonce, 40); if (a->clientDHNonce == NULL) { krb5_clear_error_message(context); return ret; } RAND_bytes(a->clientDHNonce->data, a->clientDHNonce->length); ret = krb5_copy_data(context, a->clientDHNonce, &ctx->clientDHNonce); if (ret) return ret; } ALLOC(a->clientPublicValue, 1); if (a->clientPublicValue == NULL) return ENOMEM; if (ctx->keyex == USE_DH) { DH *dh = ctx->u.dh; DomainParameters dp; heim_integer dh_pub_key; ret = der_copy_oid(&asn1_oid_id_dhpublicnumber, &a->clientPublicValue->algorithm.algorithm); if (ret) return ret; memset(&dp, 0, sizeof(dp)); ret = BN_to_integer(context, dh->p, &dp.p); if (ret) { free_DomainParameters(&dp); return ret; } ret = BN_to_integer(context, dh->g, &dp.g); if (ret) { free_DomainParameters(&dp); return ret; } dp.q = calloc(1, sizeof(*dp.q)); if (dp.q == NULL) { free_DomainParameters(&dp); return ENOMEM; } ret = BN_to_integer(context, dh->q, dp.q); if (ret) { free_DomainParameters(&dp); return ret; } dp.j = NULL; dp.validationParms = NULL; a->clientPublicValue->algorithm.parameters = malloc(sizeof(*a->clientPublicValue->algorithm.parameters)); if (a->clientPublicValue->algorithm.parameters == NULL) { free_DomainParameters(&dp); return ret; } ASN1_MALLOC_ENCODE(DomainParameters, a->clientPublicValue->algorithm.parameters->data, a->clientPublicValue->algorithm.parameters->length, &dp, &size, ret); free_DomainParameters(&dp); if (ret) return ret; if (size != a->clientPublicValue->algorithm.parameters->length) krb5_abortx(context, "Internal ASN1 encoder error"); ret = BN_to_integer(context, dh->pub_key, &dh_pub_key); if (ret) return ret; ASN1_MALLOC_ENCODE(DHPublicKey, dhbuf.data, dhbuf.length, &dh_pub_key, &size, ret); der_free_heim_integer(&dh_pub_key); if (ret) return ret; if (size != dhbuf.length) krb5_abortx(context, "asn1 internal error"); a->clientPublicValue->subjectPublicKey.length = dhbuf.length * 8; a->clientPublicValue->subjectPublicKey.data = dhbuf.data; } else if (ctx->keyex == USE_ECDH) { ret = _krb5_build_authpack_subjectPK_EC(context, ctx, a); if (ret) return ret; } else krb5_abortx(context, "internal error"); } { a->supportedCMSTypes = calloc(1, sizeof(*a->supportedCMSTypes)); if (a->supportedCMSTypes == NULL) return ENOMEM; ret = hx509_crypto_available(context->hx509ctx, HX509_SELECT_ALL, ctx->id->cert, &a->supportedCMSTypes->val, &a->supportedCMSTypes->len); if (ret) return ret; } return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_ContentInfo(krb5_context context, const krb5_data *buf, const heim_oid *oid, struct ContentInfo *content_info) { krb5_error_code ret; ret = der_copy_oid(oid, &content_info->contentType); if (ret) return ret; ALLOC(content_info->content, 1); if (content_info->content == NULL) return ENOMEM; content_info->content->data = malloc(buf->length); if (content_info->content->data == NULL) return ENOMEM; memcpy(content_info->content->data, buf->data, buf->length); content_info->content->length = buf->length; return 0; } static krb5_error_code pk_mk_padata(krb5_context context, krb5_pk_init_ctx ctx, const KDC_REQ_BODY *req_body, unsigned nonce, METHOD_DATA *md) { struct ContentInfo content_info; krb5_error_code ret; const heim_oid *oid = NULL; size_t size = 0; krb5_data buf, sd_buf; int pa_type = -1; krb5_data_zero(&buf); krb5_data_zero(&sd_buf); memset(&content_info, 0, sizeof(content_info)); if (ctx->type == PKINIT_WIN2K) { AuthPack_Win2k ap; krb5_timestamp sec; int32_t usec; memset(&ap, 0, sizeof(ap)); /* fill in PKAuthenticator */ ret = copy_PrincipalName(req_body->sname, &ap.pkAuthenticator.kdcName); if (ret) { free_AuthPack_Win2k(&ap); krb5_clear_error_message(context); goto out; } ret = copy_Realm(&req_body->realm, &ap.pkAuthenticator.kdcRealm); if (ret) { free_AuthPack_Win2k(&ap); krb5_clear_error_message(context); goto out; } krb5_us_timeofday(context, &sec, &usec); ap.pkAuthenticator.ctime = sec; ap.pkAuthenticator.cusec = usec; ap.pkAuthenticator.nonce = nonce; ASN1_MALLOC_ENCODE(AuthPack_Win2k, buf.data, buf.length, &ap, &size, ret); free_AuthPack_Win2k(&ap); if (ret) { krb5_set_error_message(context, ret, N_("Failed encoding AuthPackWin: %d", ""), (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "internal ASN1 encoder error"); oid = &asn1_oid_id_pkcs7_data; } else if (ctx->type == PKINIT_27) { AuthPack ap; memset(&ap, 0, sizeof(ap)); ret = build_auth_pack(context, nonce, ctx, req_body, &ap); if (ret) { free_AuthPack(&ap); goto out; } ASN1_MALLOC_ENCODE(AuthPack, buf.data, buf.length, &ap, &size, ret); free_AuthPack(&ap); if (ret) { krb5_set_error_message(context, ret, N_("Failed encoding AuthPack: %d", ""), (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "internal ASN1 encoder error"); oid = &asn1_oid_id_pkauthdata; } else krb5_abortx(context, "internal pkinit error"); ret = create_signature(context, oid, &buf, ctx->id, ctx->peer, &sd_buf); krb5_data_free(&buf); if (ret) goto out; ret = hx509_cms_wrap_ContentInfo(&asn1_oid_id_pkcs7_signedData, &sd_buf, &buf); krb5_data_free(&sd_buf); if (ret) { krb5_set_error_message(context, ret, N_("ContentInfo wrapping of signedData failed","")); goto out; } if (ctx->type == PKINIT_WIN2K) { PA_PK_AS_REQ_Win2k winreq; pa_type = KRB5_PADATA_PK_AS_REQ_WIN; memset(&winreq, 0, sizeof(winreq)); winreq.signed_auth_pack = buf; ASN1_MALLOC_ENCODE(PA_PK_AS_REQ_Win2k, buf.data, buf.length, &winreq, &size, ret); free_PA_PK_AS_REQ_Win2k(&winreq); } else if (ctx->type == PKINIT_27) { PA_PK_AS_REQ req; pa_type = KRB5_PADATA_PK_AS_REQ; memset(&req, 0, sizeof(req)); req.signedAuthPack = buf; if (ctx->trustedCertifiers) { req.trustedCertifiers = calloc(1, sizeof(*req.trustedCertifiers)); if (req.trustedCertifiers == NULL) { ret = krb5_enomem(context); free_PA_PK_AS_REQ(&req); goto out; } ret = build_edi(context, context->hx509ctx, ctx->id->anchors, req.trustedCertifiers); if (ret) { krb5_set_error_message(context, ret, N_("pk-init: failed to build " "trustedCertifiers", "")); free_PA_PK_AS_REQ(&req); goto out; } } req.kdcPkId = NULL; ASN1_MALLOC_ENCODE(PA_PK_AS_REQ, buf.data, buf.length, &req, &size, ret); free_PA_PK_AS_REQ(&req); } else krb5_abortx(context, "internal pkinit error"); if (ret) { krb5_set_error_message(context, ret, "PA-PK-AS-REQ %d", (int)ret); goto out; } if (buf.length != size) krb5_abortx(context, "Internal ASN1 encoder error"); ret = krb5_padata_add(context, md, pa_type, buf.data, buf.length); if (ret) free(buf.data); if (ret == 0) krb5_padata_add(context, md, KRB5_PADATA_PK_AS_09_BINDING, NULL, 0); out: free_ContentInfo(&content_info); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_mk_padata(krb5_context context, void *c, int ic_flags, int win2k, const KDC_REQ_BODY *req_body, unsigned nonce, METHOD_DATA *md) { krb5_pk_init_ctx ctx = c; int win2k_compat; if (ctx->id->certs == NULL && ctx->anonymous == 0) { krb5_set_error_message(context, HEIM_PKINIT_NO_PRIVATE_KEY, N_("PKINIT: No user certificate given", "")); return HEIM_PKINIT_NO_PRIVATE_KEY; } win2k_compat = krb5_config_get_bool_default(context, NULL, win2k, "realms", req_body->realm, "pkinit_win2k", NULL); if (win2k_compat) { ctx->require_binding = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_win2k_require_binding", NULL); ctx->type = PKINIT_WIN2K; } else ctx->type = PKINIT_27; ctx->require_eku = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_require_eku", NULL); if (ic_flags & KRB5_INIT_CREDS_NO_C_NO_EKU_CHECK) ctx->require_eku = 0; if (ctx->id->flags & PKINIT_BTMM) ctx->require_eku = 0; ctx->require_krbtgt_otherName = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_require_krbtgt_otherName", NULL); ctx->require_hostname_match = krb5_config_get_bool_default(context, NULL, FALSE, "realms", req_body->realm, "pkinit_require_hostname_match", NULL); ctx->trustedCertifiers = krb5_config_get_bool_default(context, NULL, TRUE, "realms", req_body->realm, "pkinit_trustedCertifiers", NULL); return pk_mk_padata(context, ctx, req_body, nonce, md); } static krb5_error_code pk_verify_sign(krb5_context context, const void *data, size_t length, struct krb5_pk_identity *id, heim_oid *contentType, krb5_data *content, struct krb5_pk_cert **signer) { hx509_certs signer_certs; int ret, flags = 0; /* BTMM is broken in Leo and SnowLeo */ if (id->flags & PKINIT_BTMM) { flags |= HX509_CMS_VS_ALLOW_DATA_OID_MISMATCH; flags |= HX509_CMS_VS_NO_KU_CHECK; flags |= HX509_CMS_VS_NO_VALIDATE; } *signer = NULL; ret = hx509_cms_verify_signed(context->hx509ctx, id->verify_ctx, flags, data, length, NULL, id->certpool, contentType, content, &signer_certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "CMS verify signed failed"); return ret; } *signer = calloc(1, sizeof(**signer)); if (*signer == NULL) { krb5_clear_error_message(context); ret = ENOMEM; goto out; } ret = hx509_get_one_cert(context->hx509ctx, signer_certs, &(*signer)->cert); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get on of the signer certs"); goto out; } out: hx509_certs_free(&signer_certs); if (ret) { if (*signer) { hx509_cert_free((*signer)->cert); free(*signer); *signer = NULL; } } return ret; } static krb5_error_code get_reply_key_win(krb5_context context, const krb5_data *content, unsigned nonce, krb5_keyblock **key) { ReplyKeyPack_Win2k key_pack; krb5_error_code ret; size_t size; ret = decode_ReplyKeyPack_Win2k(content->data, content->length, &key_pack, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT decoding reply key failed", "")); free_ReplyKeyPack_Win2k(&key_pack); return ret; } if ((unsigned)key_pack.nonce != nonce) { krb5_set_error_message(context, ret, N_("PKINIT enckey nonce is wrong", "")); free_ReplyKeyPack_Win2k(&key_pack); return KRB5KRB_AP_ERR_MODIFIED; } *key = malloc (sizeof (**key)); if (*key == NULL) { free_ReplyKeyPack_Win2k(&key_pack); return krb5_enomem(context); } ret = copy_EncryptionKey(&key_pack.replyKey, *key); free_ReplyKeyPack_Win2k(&key_pack); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT failed copying reply key", "")); free(*key); *key = NULL; } return ret; } static krb5_error_code get_reply_key(krb5_context context, const krb5_data *content, const krb5_data *req_buffer, krb5_keyblock **key) { ReplyKeyPack key_pack; krb5_error_code ret; size_t size; ret = decode_ReplyKeyPack(content->data, content->length, &key_pack, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT decoding reply key failed", "")); free_ReplyKeyPack(&key_pack); return ret; } { krb5_crypto crypto; /* * XXX Verify kp.replyKey is a allowed enctype in the * configuration file */ ret = krb5_crypto_init(context, &key_pack.replyKey, 0, &crypto); if (ret) { free_ReplyKeyPack(&key_pack); return ret; } ret = krb5_verify_checksum(context, crypto, 6, req_buffer->data, req_buffer->length, &key_pack.asChecksum); krb5_crypto_destroy(context, crypto); if (ret) { free_ReplyKeyPack(&key_pack); return ret; } } *key = malloc (sizeof (**key)); if (*key == NULL) { free_ReplyKeyPack(&key_pack); return krb5_enomem(context); } ret = copy_EncryptionKey(&key_pack.replyKey, *key); free_ReplyKeyPack(&key_pack); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT failed copying reply key", "")); free(*key); *key = NULL; } return ret; } static krb5_error_code pk_verify_host(krb5_context context, const char *realm, const krb5_krbhst_info *hi, struct krb5_pk_init_ctx_data *ctx, struct krb5_pk_cert *host) { krb5_error_code ret = 0; if (ctx->require_eku) { ret = hx509_cert_check_eku(context->hx509ctx, host->cert, &asn1_oid_id_pkkdcekuoid, 0); if (ret) { krb5_set_error_message(context, ret, N_("No PK-INIT KDC EKU in kdc certificate", "")); return ret; } } if (ctx->require_krbtgt_otherName) { hx509_octet_string_list list; size_t i; int matched = 0; ret = hx509_cert_find_subjectAltName_otherName(context->hx509ctx, host->cert, &asn1_oid_id_pkinit_san, &list); if (ret) { krb5_set_error_message(context, ret, N_("Failed to find the PK-INIT " "subjectAltName in the KDC " "certificate", "")); return ret; } /* * subjectAltNames are multi-valued, and a single KDC may serve * multiple realms. The SAN validation here must accept * the KDC's cert if *any* of the SANs match the expected KDC. * It is OK for *some* of the SANs to not match, provided at least * one does. */ for (i = 0; matched == 0 && i < list.len; i++) { KRB5PrincipalName r; ret = decode_KRB5PrincipalName(list.val[i].data, list.val[i].length, &r, NULL); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode the PK-INIT " "subjectAltName in the " "KDC certificate", "")); break; } if (r.principalName.name_string.len == 2 && strcmp(r.principalName.name_string.val[0], KRB5_TGS_NAME) == 0 && strcmp(r.principalName.name_string.val[1], realm) == 0 && strcmp(r.realm, realm) == 0) matched = 1; free_KRB5PrincipalName(&r); } hx509_free_octet_string_list(&list); if (matched == 0) { ret = KRB5_KDC_ERR_INVALID_CERTIFICATE; /* XXX: Lost in translation... */ krb5_set_error_message(context, ret, N_("KDC have wrong realm name in " "the certificate", "")); } } if (ret) return ret; if (hi) { ret = hx509_verify_hostname(context->hx509ctx, host->cert, ctx->require_hostname_match, HX509_HN_HOSTNAME, hi->hostname, hi->ai->ai_addr, hi->ai->ai_addrlen); if (ret) krb5_set_error_message(context, ret, N_("Address mismatch in " "the KDC certificate", "")); } return ret; } static krb5_error_code pk_rd_pa_reply_enckey(krb5_context context, int type, const heim_octet_string *indata, const heim_oid *dataType, const char *realm, krb5_pk_init_ctx ctx, krb5_enctype etype, const krb5_krbhst_info *hi, unsigned nonce, const krb5_data *req_buffer, PA_DATA *pa, krb5_keyblock **key) { krb5_error_code ret; struct krb5_pk_cert *host = NULL; krb5_data content; heim_oid contentType = { 0, NULL }; int flags = HX509_CMS_UE_DONT_REQUIRE_KU_ENCIPHERMENT; if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_envelopedData, dataType)) { krb5_set_error_message(context, EINVAL, N_("PKINIT: Invalid content type", "")); return EINVAL; } if (ctx->type == PKINIT_WIN2K) flags |= HX509_CMS_UE_ALLOW_WEAK; ret = hx509_cms_unenvelope(context->hx509ctx, ctx->id->certs, flags, indata->data, indata->length, NULL, 0, &contentType, &content); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to unenvelope CMS data in PK-INIT reply"); return ret; } der_free_oid(&contentType); /* win2k uses ContentInfo */ if (type == PKINIT_WIN2K) { heim_oid type2; heim_octet_string out; ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL); if (ret) { /* windows LH with interesting CMS packets */ size_t ph = 1 + der_length_len(content.length); unsigned char *ptr = malloc(content.length + ph); size_t l; memcpy(ptr + ph, content.data, content.length); ret = der_put_length_and_tag (ptr + ph - 1, ph, content.length, ASN1_C_UNIV, CONS, UT_Sequence, &l); if (ret) { free(ptr); return ret; } free(content.data); content.data = ptr; content.length += ph; ret = hx509_cms_unwrap_ContentInfo(&content, &type2, &out, NULL); if (ret) goto out; } if (der_heim_oid_cmp(&type2, &asn1_oid_id_pkcs7_signedData)) { ret = EINVAL; /* XXX */ krb5_set_error_message(context, ret, N_("PKINIT: Invalid content type", "")); der_free_oid(&type2); der_free_octet_string(&out); goto out; } der_free_oid(&type2); krb5_data_free(&content); ret = krb5_data_copy(&content, out.data, out.length); der_free_octet_string(&out); if (ret) { krb5_set_error_message(context, ret, N_("malloc: out of memory", "")); goto out; } } ret = pk_verify_sign(context, content.data, content.length, ctx->id, &contentType, &content, &host); if (ret) goto out; /* make sure that it is the kdc's certificate */ ret = pk_verify_host(context, realm, hi, ctx, host); if (ret) { goto out; } #if 0 if (type == PKINIT_WIN2K) { if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkcs7_data) != 0) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid"); goto out; } } else { if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkrkeydata) != 0) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, "PKINIT: reply key, wrong oid"); goto out; } } #endif switch(type) { case PKINIT_WIN2K: ret = get_reply_key(context, &content, req_buffer, key); if (ret != 0 && ctx->require_binding == 0) ret = get_reply_key_win(context, &content, nonce, key); break; case PKINIT_27: ret = get_reply_key(context, &content, req_buffer, key); break; } if (ret) goto out; /* XXX compare given etype with key->etype */ out: if (host) _krb5_pk_cert_free(host); der_free_oid(&contentType); krb5_data_free(&content); return ret; } /* * RFC 8062 section 7: * * The client then decrypts the KDC contribution key and verifies that * the ticket session key in the returned ticket is the combined key of * the KDC contribution key and the reply key. */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_kx_confirm(krb5_context context, krb5_pk_init_ctx ctx, krb5_keyblock *reply_key, krb5_keyblock *session_key, PA_DATA *pa_pkinit_kx) { krb5_error_code ret; EncryptedData ed; krb5_keyblock ck, sk_verify; krb5_crypto ck_crypto = NULL; krb5_crypto rk_crypto = NULL; size_t len; krb5_data data; krb5_data p1 = { sizeof("PKINIT") - 1, "PKINIT" }; krb5_data p2 = { sizeof("KEYEXCHANGE") - 1, "KEYEXCHANGE" }; heim_assert(ctx != NULL, "PKINIT context is non-NULL"); heim_assert(reply_key != NULL, "reply key is non-NULL"); heim_assert(session_key != NULL, "session key is non-NULL"); /* PA-PKINIT-KX is optional unless anonymous */ if (pa_pkinit_kx == NULL) return ctx->anonymous ? KRB5_KDCREP_MODIFIED : 0; memset(&ed, 0, sizeof(ed)); krb5_keyblock_zero(&ck); krb5_keyblock_zero(&sk_verify); krb5_data_zero(&data); ret = decode_EncryptedData(pa_pkinit_kx->padata_value.data, pa_pkinit_kx->padata_value.length, &ed, &len); if (ret) goto out; if (len != pa_pkinit_kx->padata_value.length) { ret = KRB5_KDCREP_MODIFIED; goto out; } ret = krb5_crypto_init(context, reply_key, 0, &rk_crypto); if (ret) goto out; ret = krb5_decrypt_EncryptedData(context, rk_crypto, KRB5_KU_PA_PKINIT_KX, &ed, &data); if (ret) goto out; ret = decode_EncryptionKey(data.data, data.length, &ck, &len); if (ret) goto out; ret = krb5_crypto_init(context, &ck, 0, &ck_crypto); if (ret) goto out; ret = krb5_crypto_fx_cf2(context, ck_crypto, rk_crypto, &p1, &p2, session_key->keytype, &sk_verify); if (ret) goto out; if (sk_verify.keytype != session_key->keytype || krb5_data_ct_cmp(&sk_verify.keyvalue, &session_key->keyvalue) != 0) { ret = KRB5_KDCREP_MODIFIED; goto out; } out: free_EncryptedData(&ed); krb5_free_keyblock_contents(context, &ck); krb5_free_keyblock_contents(context, &sk_verify); if (ck_crypto) krb5_crypto_destroy(context, ck_crypto); if (rk_crypto) krb5_crypto_destroy(context, rk_crypto); krb5_data_free(&data); return ret; } static krb5_error_code pk_rd_pa_reply_dh(krb5_context context, const heim_octet_string *indata, const heim_oid *dataType, const char *realm, krb5_pk_init_ctx ctx, krb5_enctype etype, const krb5_krbhst_info *hi, const DHNonce *c_n, const DHNonce *k_n, unsigned nonce, PA_DATA *pa, krb5_keyblock **key) { const unsigned char *p; unsigned char *dh_gen_key = NULL; struct krb5_pk_cert *host = NULL; BIGNUM *kdc_dh_pubkey = NULL; KDCDHKeyInfo kdc_dh_info; heim_oid contentType = { 0, NULL }; krb5_data content; krb5_error_code ret; int dh_gen_keylen = 0; size_t size; krb5_data_zero(&content); memset(&kdc_dh_info, 0, sizeof(kdc_dh_info)); if (der_heim_oid_cmp(&asn1_oid_id_pkcs7_signedData, dataType)) { krb5_set_error_message(context, EINVAL, N_("PKINIT: Invalid content type", "")); return EINVAL; } ret = pk_verify_sign(context, indata->data, indata->length, ctx->id, &contentType, &content, &host); if (ret) goto out; /* make sure that it is the kdc's certificate */ ret = pk_verify_host(context, realm, hi, ctx, host); if (ret) goto out; if (der_heim_oid_cmp(&contentType, &asn1_oid_id_pkdhkeydata)) { ret = KRB5KRB_AP_ERR_MSG_TYPE; krb5_set_error_message(context, ret, N_("pkinit - dh reply contains wrong oid", "")); goto out; } ret = decode_KDCDHKeyInfo(content.data, content.length, &kdc_dh_info, &size); if (ret) { krb5_set_error_message(context, ret, N_("pkinit - failed to decode " "KDC DH Key Info", "")); goto out; } if (kdc_dh_info.nonce != nonce) { ret = KRB5KRB_AP_ERR_MODIFIED; krb5_set_error_message(context, ret, N_("PKINIT: DH nonce is wrong", "")); goto out; } if (kdc_dh_info.dhKeyExpiration) { if (k_n == NULL) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit; got key expiration " "without server nonce", "")); goto out; } if (c_n == NULL) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit; got DH reuse but no " "client nonce", "")); goto out; } } else { if (k_n) { ret = KRB5KRB_ERR_GENERIC; krb5_set_error_message(context, ret, N_("pkinit: got server nonce " "without key expiration", "")); goto out; } c_n = NULL; } p = kdc_dh_info.subjectPublicKey.data; size = (kdc_dh_info.subjectPublicKey.length + 7) / 8; if (ctx->keyex == USE_DH) { DHPublicKey k; ret = decode_DHPublicKey(p, size, &k, NULL); if (ret) { krb5_set_error_message(context, ret, N_("pkinit: can't decode " "without key expiration", "")); goto out; } kdc_dh_pubkey = integer_to_BN(context, "DHPublicKey", &k); free_DHPublicKey(&k); if (kdc_dh_pubkey == NULL) { ret = ENOMEM; goto out; } size = DH_size(ctx->u.dh); dh_gen_key = malloc(size); if (dh_gen_key == NULL) { ret = krb5_enomem(context); goto out; } dh_gen_keylen = DH_compute_key(dh_gen_key, kdc_dh_pubkey, ctx->u.dh); if (dh_gen_keylen == -1) { ret = KRB5KRB_ERR_GENERIC; dh_gen_keylen = 0; krb5_set_error_message(context, ret, N_("PKINIT: Can't compute Diffie-Hellman key", "")); goto out; } if (dh_gen_keylen < (int)size) { size -= dh_gen_keylen; memmove(dh_gen_key + size, dh_gen_key, dh_gen_keylen); memset(dh_gen_key, 0, size); } } else { ret = _krb5_pk_rd_pa_reply_ecdh_compute_key(context, ctx, p, size, &dh_gen_key, &dh_gen_keylen); if (ret) goto out; } if (dh_gen_keylen <= 0) { ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: resulting DH key <= 0", "")); dh_gen_keylen = 0; goto out; } *key = malloc (sizeof (**key)); if (*key == NULL) { ret = krb5_enomem(context); goto out; } ret = _krb5_pk_octetstring2key(context, etype, dh_gen_key, dh_gen_keylen, c_n, k_n, *key); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: can't create key from DH key", "")); free(*key); *key = NULL; goto out; } out: if (kdc_dh_pubkey) BN_free(kdc_dh_pubkey); if (dh_gen_key) { memset(dh_gen_key, 0, dh_gen_keylen); free(dh_gen_key); } if (host) _krb5_pk_cert_free(host); if (content.data) krb5_data_free(&content); der_free_oid(&contentType); free_KDCDHKeyInfo(&kdc_dh_info); return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_rd_pa_reply(krb5_context context, const char *realm, void *c, krb5_enctype etype, const krb5_krbhst_info *hi, unsigned nonce, const krb5_data *req_buffer, PA_DATA *pa, krb5_keyblock **key) { krb5_pk_init_ctx ctx = c; krb5_error_code ret; size_t size; /* Check for IETF PK-INIT first */ if (ctx->type == PKINIT_27) { PA_PK_AS_REP rep; heim_octet_string os, data; heim_oid oid; if (pa->padata_type != KRB5_PADATA_PK_AS_REP) { krb5_set_error_message(context, EINVAL, N_("PKINIT: wrong padata recv", "")); return EINVAL; } ret = decode_PA_PK_AS_REP(pa->padata_value.data, pa->padata_value.length, &rep, &size); if (ret) { krb5_set_error_message(context, ret, N_("Failed to decode pkinit AS rep", "")); return ret; } switch (rep.element) { case choice_PA_PK_AS_REP_dhInfo: _krb5_debug(context, 5, "krb5_get_init_creds: using pkinit dh"); os = rep.u.dhInfo.dhSignedData; break; case choice_PA_PK_AS_REP_encKeyPack: _krb5_debug(context, 5, "krb5_get_init_creds: using kinit enc reply key"); os = rep.u.encKeyPack; break; default: { PA_PK_AS_REP_BTMM btmm; free_PA_PK_AS_REP(&rep); memset(&rep, 0, sizeof(rep)); _krb5_debug(context, 5, "krb5_get_init_creds: using BTMM kinit enc reply key"); ret = decode_PA_PK_AS_REP_BTMM(pa->padata_value.data, pa->padata_value.length, &btmm, &size); if (ret) { krb5_set_error_message(context, EINVAL, N_("PKINIT: -27 reply " "invalid content type", "")); return EINVAL; } if (btmm.dhSignedData || btmm.encKeyPack == NULL) { free_PA_PK_AS_REP_BTMM(&btmm); ret = EINVAL; krb5_set_error_message(context, ret, N_("DH mode not supported for BTMM mode", "")); return ret; } /* * Transform to IETF style PK-INIT reply so that free works below */ rep.element = choice_PA_PK_AS_REP_encKeyPack; rep.u.encKeyPack.data = btmm.encKeyPack->data; rep.u.encKeyPack.length = btmm.encKeyPack->length; btmm.encKeyPack->data = NULL; btmm.encKeyPack->length = 0; free_PA_PK_AS_REP_BTMM(&btmm); os = rep.u.encKeyPack; } } ret = hx509_cms_unwrap_ContentInfo(&os, &oid, &data, NULL); if (ret) { free_PA_PK_AS_REP(&rep); krb5_set_error_message(context, ret, N_("PKINIT: failed to unwrap CI", "")); return ret; } switch (rep.element) { case choice_PA_PK_AS_REP_dhInfo: ret = pk_rd_pa_reply_dh(context, &data, &oid, realm, ctx, etype, hi, ctx->clientDHNonce, rep.u.dhInfo.serverDHNonce, nonce, pa, key); break; case choice_PA_PK_AS_REP_encKeyPack: ret = pk_rd_pa_reply_enckey(context, PKINIT_27, &data, &oid, realm, ctx, etype, hi, nonce, req_buffer, pa, key); break; default: krb5_abortx(context, "pk-init as-rep case not possible to happen"); } der_free_octet_string(&data); der_free_oid(&oid); free_PA_PK_AS_REP(&rep); } else if (ctx->type == PKINIT_WIN2K) { PA_PK_AS_REP_Win2k w2krep; /* Check for Windows encoding of the AS-REP pa data */ #if 0 /* should this be ? */ if (pa->padata_type != KRB5_PADATA_PK_AS_REP) { krb5_set_error_message(context, EINVAL, "PKINIT: wrong padata recv"); return EINVAL; } #endif memset(&w2krep, 0, sizeof(w2krep)); ret = decode_PA_PK_AS_REP_Win2k(pa->padata_value.data, pa->padata_value.length, &w2krep, &size); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: Failed decoding windows " "pkinit reply %d", ""), (int)ret); return ret; } krb5_clear_error_message(context); switch (w2krep.element) { case choice_PA_PK_AS_REP_Win2k_encKeyPack: { heim_octet_string data; heim_oid oid; ret = hx509_cms_unwrap_ContentInfo(&w2krep.u.encKeyPack, &oid, &data, NULL); free_PA_PK_AS_REP_Win2k(&w2krep); if (ret) { krb5_set_error_message(context, ret, N_("PKINIT: failed to unwrap CI", "")); return ret; } ret = pk_rd_pa_reply_enckey(context, PKINIT_WIN2K, &data, &oid, realm, ctx, etype, hi, nonce, req_buffer, pa, key); der_free_octet_string(&data); der_free_oid(&oid); break; } default: free_PA_PK_AS_REP_Win2k(&w2krep); ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: win2k reply invalid " "content type", "")); break; } } else { ret = EINVAL; krb5_set_error_message(context, ret, N_("PKINIT: unknown reply type", "")); } return ret; } struct prompter { krb5_context context; krb5_prompter_fct prompter; void *prompter_data; }; static int hx_pass_prompter(void *data, const hx509_prompt *prompter) { krb5_error_code ret; krb5_prompt prompt; krb5_data password_data; struct prompter *p = data; password_data.data = prompter->reply.data; password_data.length = prompter->reply.length; prompt.prompt = prompter->prompt; prompt.hidden = hx509_prompt_hidden(prompter->type); prompt.reply = &password_data; switch (prompter->type) { case HX509_PROMPT_TYPE_INFO: prompt.type = KRB5_PROMPT_TYPE_INFO; break; case HX509_PROMPT_TYPE_PASSWORD: case HX509_PROMPT_TYPE_QUESTION: default: prompt.type = KRB5_PROMPT_TYPE_PASSWORD; break; } ret = (*p->prompter)(p->context, p->prompter_data, NULL, NULL, 1, &prompt); if (ret) { memset (prompter->reply.data, 0, prompter->reply.length); return 1; } return 0; } static krb5_error_code _krb5_pk_set_user_id(krb5_context context, krb5_principal principal, krb5_pk_init_ctx ctx, struct hx509_certs_data *certs) { hx509_certs c = hx509_certs_ref(certs); hx509_query *q = NULL; int ret; if (ctx->id->certs) hx509_certs_free(&ctx->id->certs); if (ctx->id->cert) { hx509_cert_free(ctx->id->cert); ctx->id->cert = NULL; } ctx->id->certs = c; ctx->anonymous = 0; ret = hx509_query_alloc(context->hx509ctx, &q); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Allocate query to find signing certificate"); return ret; } hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); if (principal && strncmp("LKDC:SHA1.", krb5_principal_get_realm(context, principal), 9) == 0) { ctx->id->flags |= PKINIT_BTMM; } ret = find_cert(context, ctx->id, q, &ctx->id->cert); hx509_query_free(context->hx509ctx, q); if (ret == 0 && _krb5_have_debug(context, 2)) { hx509_name name; char *str, *sn; heim_integer i; ret = hx509_cert_get_subject(ctx->id->cert, &name); if (ret) goto out; ret = hx509_name_to_string(name, &str); hx509_name_free(&name); if (ret) goto out; ret = hx509_cert_get_serialnumber(ctx->id->cert, &i); if (ret) { free(str); goto out; } ret = der_print_hex_heim_integer(&i, &sn); der_free_heim_integer(&i); if (ret) { free(name); goto out; } _krb5_debug(context, 2, "using cert: subject: %s sn: %s", str, sn); free(str); free(sn); } out: return ret; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_pk_load_id(krb5_context context, struct krb5_pk_identity **ret_id, const char *user_id, const char *anchor_id, char * const *chain_list, char * const *revoke_list, krb5_prompter_fct prompter, void *prompter_data, char *password) { struct krb5_pk_identity *id = NULL; struct prompter p; int ret; *ret_id = NULL; if (anchor_id == NULL) { krb5_set_error_message(context, HEIM_PKINIT_NO_VALID_CA, N_("PKINIT: No anchor given", "")); return HEIM_PKINIT_NO_VALID_CA; } /* load cert */ id = calloc(1, sizeof(*id)); if (id == NULL) return krb5_enomem(context); if (user_id) { hx509_lock lock; ret = hx509_lock_init(context->hx509ctx, &lock); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init lock"); goto out; } if (password && password[0]) hx509_lock_add_password(lock, password); if (prompter) { p.context = context; p.prompter = prompter; p.prompter_data = prompter_data; ret = hx509_lock_set_prompter(lock, hx_pass_prompter, &p); if (ret) { hx509_lock_free(lock); goto out; } } ret = hx509_certs_init(context->hx509ctx, user_id, 0, lock, &id->certs); hx509_lock_free(lock); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init cert certs"); goto out; } } else { id->certs = NULL; } ret = hx509_certs_init(context->hx509ctx, anchor_id, 0, NULL, &id->anchors); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init anchors"); goto out; } ret = hx509_certs_init(context->hx509ctx, "MEMORY:pkinit-cert-chain", 0, NULL, &id->certpool); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init chain"); goto out; } while (chain_list && *chain_list) { ret = hx509_certs_append(context->hx509ctx, id->certpool, NULL, *chain_list); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to laod chain %s", *chain_list); goto out; } chain_list++; } if (revoke_list) { ret = hx509_revoke_init(context->hx509ctx, &id->revokectx); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init revoke list"); goto out; } while (*revoke_list) { ret = hx509_revoke_add_crl(context->hx509ctx, id->revokectx, *revoke_list); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed load revoke list"); goto out; } revoke_list++; } } else hx509_context_set_missing_revoke(context->hx509ctx, 1); ret = hx509_verify_init_ctx(context->hx509ctx, &id->verify_ctx); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed init verify context"); goto out; } hx509_verify_attach_anchors(id->verify_ctx, id->anchors); hx509_verify_attach_revoke(id->verify_ctx, id->revokectx); out: if (ret) { hx509_verify_destroy_ctx(id->verify_ctx); hx509_certs_free(&id->certs); hx509_certs_free(&id->anchors); hx509_certs_free(&id->certpool); hx509_revoke_free(&id->revokectx); free(id); } else *ret_id = id; return ret; } /* * */ static void pk_copy_error(krb5_context context, hx509_context hx509ctx, int hxret, const char *fmt, ...) { va_list va; char *s, *f; int ret; va_start(va, fmt); ret = vasprintf(&f, fmt, va); va_end(va); if (ret == -1 || f == NULL) { krb5_clear_error_message(context); return; } s = hx509_get_error_string(hx509ctx, hxret); if (s == NULL) { krb5_clear_error_message(context); free(f); return; } krb5_set_error_message(context, hxret, "%s: %s", f, s); free(s); free(f); } static int parse_integer(krb5_context context, char **p, const char *file, int lineno, const char *name, heim_integer *integer) { int ret; char *p1; p1 = strsep(p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, EINVAL, N_("moduli file %s missing %s on line %d", ""), file, name, lineno); return EINVAL; } ret = der_parse_hex_heim_integer(p1, integer); if (ret) { krb5_set_error_message(context, ret, N_("moduli file %s failed parsing %s " "on line %d", ""), file, name, lineno); return ret; } return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli_line(krb5_context context, const char *file, int lineno, char *p, struct krb5_dh_moduli **m) { struct krb5_dh_moduli *m1; char *p1; int ret; *m = NULL; m1 = calloc(1, sizeof(*m1)); if (m1 == NULL) return krb5_enomem(context); while (isspace((unsigned char)*p)) p++; if (*p == '#') { free(m1); return 0; } ret = EINVAL; p1 = strsep(&p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, ret, N_("moduli file %s missing name on line %d", ""), file, lineno); goto out; } m1->name = strdup(p1); if (m1->name == NULL) { ret = krb5_enomem(context); goto out; } p1 = strsep(&p, " \t"); if (p1 == NULL) { krb5_set_error_message(context, ret, N_("moduli file %s missing bits on line %d", ""), file, lineno); goto out; } m1->bits = atoi(p1); if (m1->bits == 0) { krb5_set_error_message(context, ret, N_("moduli file %s have un-parsable " "bits on line %d", ""), file, lineno); goto out; } ret = parse_integer(context, &p, file, lineno, "p", &m1->p); if (ret) goto out; ret = parse_integer(context, &p, file, lineno, "g", &m1->g); if (ret) goto out; ret = parse_integer(context, &p, file, lineno, "q", &m1->q); if (ret) goto out; *m = m1; return 0; out: free(m1->name); der_free_heim_integer(&m1->p); der_free_heim_integer(&m1->g); der_free_heim_integer(&m1->q); free(m1); return ret; } KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_free_moduli(struct krb5_dh_moduli **moduli) { int i; for (i = 0; moduli[i] != NULL; i++) { free(moduli[i]->name); der_free_heim_integer(&moduli[i]->p); der_free_heim_integer(&moduli[i]->g); der_free_heim_integer(&moduli[i]->q); free(moduli[i]); } free(moduli); } static const char *default_moduli_RFC2412_MODP_group2 = /* name */ "RFC2412-MODP-group2 " /* bits */ "1024 " /* p */ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE65381" "FFFFFFFF" "FFFFFFFF " /* g */ "02 " /* q */ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68" "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E" "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122" "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6" "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F67329C0" "FFFFFFFF" "FFFFFFFF"; static const char *default_moduli_rfc3526_MODP_group14 = /* name */ "rfc3526-MODP-group14 " /* bits */ "1760 " /* p */ "FFFFFFFF" "FFFFFFFF" "C90FDAA2" "2168C234" "C4C6628B" "80DC1CD1" "29024E08" "8A67CC74" "020BBEA6" "3B139B22" "514A0879" "8E3404DD" "EF9519B3" "CD3A431B" "302B0A6D" "F25F1437" "4FE1356D" "6D51C245" "E485B576" "625E7EC6" "F44C42E9" "A637ED6B" "0BFF5CB6" "F406B7ED" "EE386BFB" "5A899FA5" "AE9F2411" "7C4B1FE6" "49286651" "ECE45B3D" "C2007CB8" "A163BF05" "98DA4836" "1C55D39A" "69163FA8" "FD24CF5F" "83655D23" "DCA3AD96" "1C62F356" "208552BB" "9ED52907" "7096966D" "670C354E" "4ABC9804" "F1746C08" "CA18217C" "32905E46" "2E36CE3B" "E39E772C" "180E8603" "9B2783A2" "EC07A28F" "B5C55DF0" "6F4C52C9" "DE2BCBF6" "95581718" "3995497C" "EA956AE5" "15D22618" "98FA0510" "15728E5A" "8AACAA68" "FFFFFFFF" "FFFFFFFF " /* g */ "02 " /* q */ "7FFFFFFF" "FFFFFFFF" "E487ED51" "10B4611A" "62633145" "C06E0E68" "94812704" "4533E63A" "0105DF53" "1D89CD91" "28A5043C" "C71A026E" "F7CA8CD9" "E69D218D" "98158536" "F92F8A1B" "A7F09AB6" "B6A8E122" "F242DABB" "312F3F63" "7A262174" "D31BF6B5" "85FFAE5B" "7A035BF6" "F71C35FD" "AD44CFD2" "D74F9208" "BE258FF3" "24943328" "F6722D9E" "E1003E5C" "50B1DF82" "CC6D241B" "0E2AE9CD" "348B1FD4" "7E9267AF" "C1B2AE91" "EE51D6CB" "0E3179AB" "1042A95D" "CF6A9483" "B84B4B36" "B3861AA7" "255E4C02" "78BA3604" "650C10BE" "19482F23" "171B671D" "F1CF3B96" "0C074301" "CD93C1D1" "7603D147" "DAE2AEF8" "37A62964" "EF15E5FB" "4AAC0B8C" "1CCAA4BE" "754AB572" "8AE9130C" "4C7D0288" "0AB9472D" "45565534" "7FFFFFFF" "FFFFFFFF"; KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_parse_moduli(krb5_context context, const char *file, struct krb5_dh_moduli ***moduli) { /* name bits P G Q */ krb5_error_code ret; struct krb5_dh_moduli **m = NULL, **m2; char buf[4096]; FILE *f; int lineno = 0, n = 0; *moduli = NULL; m = calloc(1, sizeof(m[0]) * 3); if (m == NULL) return krb5_enomem(context); strlcpy(buf, default_moduli_rfc3526_MODP_group14, sizeof(buf)); ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[0]); if (ret) { _krb5_free_moduli(m); return ret; } n++; strlcpy(buf, default_moduli_RFC2412_MODP_group2, sizeof(buf)); ret = _krb5_parse_moduli_line(context, "builtin", 1, buf, &m[1]); if (ret) { _krb5_free_moduli(m); return ret; } n++; if (file == NULL) file = MODULI_FILE; #ifdef KRB5_USE_PATH_TOKENS { char * exp_file; if (_krb5_expand_path_tokens(context, file, 1, &exp_file) == 0) { f = fopen(exp_file, "r"); krb5_xfree(exp_file); } else { f = NULL; } } #else f = fopen(file, "r"); #endif if (f == NULL) { *moduli = m; return 0; } rk_cloexec_file(f); while(fgets(buf, sizeof(buf), f) != NULL) { struct krb5_dh_moduli *element; buf[strcspn(buf, "\n")] = '\0'; lineno++; m2 = realloc(m, (n + 2) * sizeof(m[0])); if (m2 == NULL) { _krb5_free_moduli(m); return krb5_enomem(context); } m = m2; m[n] = NULL; ret = _krb5_parse_moduli_line(context, file, lineno, buf, &element); if (ret) { _krb5_free_moduli(m); return ret; } if (element == NULL) continue; m[n] = element; m[n + 1] = NULL; n++; } *moduli = m; return 0; } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL _krb5_dh_group_ok(krb5_context context, unsigned long bits, heim_integer *p, heim_integer *g, heim_integer *q, struct krb5_dh_moduli **moduli, char **name) { int i; if (name) *name = NULL; for (i = 0; moduli[i] != NULL; i++) { if (der_heim_integer_cmp(&moduli[i]->g, g) == 0 && der_heim_integer_cmp(&moduli[i]->p, p) == 0 && (q == NULL || der_heim_integer_cmp(&moduli[i]->q, q) == 0)) { if (bits && bits > moduli[i]->bits) { krb5_set_error_message(context, KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED, N_("PKINIT: DH group parameter %s " "no accepted, not enough bits " "generated", ""), moduli[i]->name); return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; } if (name) *name = strdup(moduli[i]->name); return 0; } } krb5_set_error_message(context, KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED, N_("PKINIT: DH group parameter no ok", "")); return KRB5_KDC_ERR_DH_KEY_PARAMETERS_NOT_ACCEPTED; } #endif /* PKINIT */ KRB5_LIB_FUNCTION void KRB5_LIB_CALL _krb5_get_init_creds_opt_free_pkinit(krb5_get_init_creds_opt *opt) { #ifdef PKINIT krb5_pk_init_ctx ctx; if (opt->opt_private == NULL || opt->opt_private->pk_init_ctx == NULL) return; ctx = opt->opt_private->pk_init_ctx; switch (ctx->keyex) { case USE_DH: if (ctx->u.dh) DH_free(ctx->u.dh); break; case USE_RSA: break; case USE_ECDH: if (ctx->u.eckey) _krb5_pk_eckey_free(ctx->u.eckey); break; } if (ctx->id) { hx509_verify_destroy_ctx(ctx->id->verify_ctx); hx509_certs_free(&ctx->id->certs); hx509_cert_free(ctx->id->cert); hx509_certs_free(&ctx->id->anchors); hx509_certs_free(&ctx->id->certpool); if (ctx->clientDHNonce) { krb5_free_data(NULL, ctx->clientDHNonce); ctx->clientDHNonce = NULL; } if (ctx->m) _krb5_free_moduli(ctx->m); free(ctx->id); ctx->id = NULL; } free(opt->opt_private->pk_init_ctx); opt->opt_private->pk_init_ctx = NULL; #endif } KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_get_init_creds_opt_set_pkinit(krb5_context context, krb5_get_init_creds_opt *opt, krb5_principal principal, const char *user_id, const char *x509_anchors, char * const * pool, char * const * pki_revoke, int flags, krb5_prompter_fct prompter, void *prompter_data, char *password) { #ifdef PKINIT krb5_error_code ret; char *anchors = NULL; if (opt->opt_private == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on non extendable opt", "")); return EINVAL; } opt->opt_private->pk_init_ctx = calloc(1, sizeof(*opt->opt_private->pk_init_ctx)); if (opt->opt_private->pk_init_ctx == NULL) return krb5_enomem(context); opt->opt_private->pk_init_ctx->require_binding = 0; opt->opt_private->pk_init_ctx->require_eku = 1; opt->opt_private->pk_init_ctx->require_krbtgt_otherName = 1; opt->opt_private->pk_init_ctx->peer = NULL; /* XXX implement krb5_appdefault_strings */ if (pool == NULL) pool = krb5_config_get_strings(context, NULL, "appdefaults", "pkinit_pool", NULL); if (pki_revoke == NULL) pki_revoke = krb5_config_get_strings(context, NULL, "appdefaults", "pkinit_revoke", NULL); if (x509_anchors == NULL) { krb5_appdefault_string(context, "kinit", krb5_principal_get_realm(context, principal), "pkinit_anchors", NULL, &anchors); x509_anchors = anchors; } if (flags & KRB5_GIC_OPT_PKINIT_ANONYMOUS) opt->opt_private->pk_init_ctx->anonymous = 1; ret = _krb5_pk_load_id(context, &opt->opt_private->pk_init_ctx->id, user_id, x509_anchors, pool, pki_revoke, prompter, prompter_data, password); if (ret) { free(opt->opt_private->pk_init_ctx); opt->opt_private->pk_init_ctx = NULL; return ret; } if (opt->opt_private->pk_init_ctx->id->certs) { _krb5_pk_set_user_id(context, principal, opt->opt_private->pk_init_ctx, opt->opt_private->pk_init_ctx->id->certs); } else opt->opt_private->pk_init_ctx->id->cert = NULL; if ((flags & KRB5_GIC_OPT_PKINIT_USE_ENCKEY) == 0) { hx509_context hx509ctx = context->hx509ctx; hx509_cert cert = opt->opt_private->pk_init_ctx->id->cert; opt->opt_private->pk_init_ctx->keyex = USE_DH; /* * If its a ECDSA certs, lets select ECDSA as the keyex algorithm. */ if (cert) { AlgorithmIdentifier alg; ret = hx509_cert_get_SPKI_AlgorithmIdentifier(hx509ctx, cert, &alg); if (ret == 0) { if (der_heim_oid_cmp(&alg.algorithm, &asn1_oid_id_ecPublicKey) == 0) opt->opt_private->pk_init_ctx->keyex = USE_ECDH; free_AlgorithmIdentifier(&alg); } } } else { opt->opt_private->pk_init_ctx->keyex = USE_RSA; if (opt->opt_private->pk_init_ctx->id->certs == NULL) { krb5_set_error_message(context, EINVAL, N_("No anonymous pkinit support in RSA mode", "")); return EINVAL; } } return 0; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } krb5_error_code KRB5_LIB_FUNCTION krb5_get_init_creds_opt_set_pkinit_user_certs(krb5_context context, krb5_get_init_creds_opt *opt, struct hx509_certs_data *certs) { #ifdef PKINIT if (opt->opt_private == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on non extendable opt", "")); return EINVAL; } if (opt->opt_private->pk_init_ctx == NULL) { krb5_set_error_message(context, EINVAL, N_("PKINIT: on pkinit context", "")); return EINVAL; } _krb5_pk_set_user_id(context, NULL, opt->opt_private->pk_init_ctx, certs); return 0; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif } #ifdef PKINIT static int get_ms_san(hx509_context context, hx509_cert cert, char **upn) { hx509_octet_string_list list; int ret; *upn = NULL; ret = hx509_cert_find_subjectAltName_otherName(context, cert, &asn1_oid_id_pkinit_ms_san, &list); if (ret) return 0; if (list.len > 0 && list.val[0].length > 0) ret = decode_MS_UPN_SAN(list.val[0].data, list.val[0].length, upn, NULL); else ret = 1; hx509_free_octet_string_list(&list); return ret; } static int find_ms_san(hx509_context context, hx509_cert cert, void *ctx) { char *upn; int ret; ret = get_ms_san(context, cert, &upn); if (ret == 0) free(upn); return ret; } #endif /* * Private since it need to be redesigned using krb5_get_init_creds() */ KRB5_LIB_FUNCTION krb5_error_code KRB5_LIB_CALL krb5_pk_enterprise_cert(krb5_context context, const char *user_id, krb5_const_realm realm, krb5_principal *principal, struct hx509_certs_data **res) { #ifdef PKINIT krb5_error_code ret; hx509_certs certs, result; hx509_cert cert = NULL; hx509_query *q; char *name; *principal = NULL; if (res) *res = NULL; if (user_id == NULL) { krb5_set_error_message(context, ENOENT, "no user id"); return ENOENT; } ret = hx509_certs_init(context->hx509ctx, user_id, 0, NULL, &certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to init cert certs"); goto out; } ret = hx509_query_alloc(context->hx509ctx, &q); if (ret) { krb5_set_error_message(context, ret, "out of memory"); hx509_certs_free(&certs); goto out; } hx509_query_match_option(q, HX509_QUERY_OPTION_PRIVATE_KEY); hx509_query_match_option(q, HX509_QUERY_OPTION_KU_DIGITALSIGNATURE); hx509_query_match_eku(q, &asn1_oid_id_pkinit_ms_eku); hx509_query_match_cmp_func(q, find_ms_san, NULL); ret = hx509_certs_filter(context->hx509ctx, certs, q, &result); hx509_query_free(context->hx509ctx, q); hx509_certs_free(&certs); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to find PKINIT certificate"); return ret; } ret = hx509_get_one_cert(context->hx509ctx, result, &cert); hx509_certs_free(&result); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get one cert"); goto out; } ret = get_ms_san(context->hx509ctx, cert, &name); if (ret) { pk_copy_error(context, context->hx509ctx, ret, "Failed to get MS SAN"); goto out; } ret = krb5_make_principal(context, principal, realm, name, NULL); free(name); if (ret) goto out; krb5_principal_set_type(context, *principal, KRB5_NT_ENTERPRISE_PRINCIPAL); if (res) { ret = hx509_certs_init(context->hx509ctx, "MEMORY:", 0, NULL, res); if (ret) goto out; ret = hx509_certs_add(context->hx509ctx, *res, cert); if (ret) { hx509_certs_free(res); goto out; } } out: hx509_cert_free(cert); return ret; #else krb5_set_error_message(context, EINVAL, N_("no support for PKINIT compiled in", "")); return EINVAL; #endif }
./CrossVul/dataset_final_sorted/CWE-320/c/good_857_2
crossvul-cpp_data_bad_4237_0
/* $OpenBSD: ca.c,v 1.64 2020/07/15 14:45:15 tobhe Exp $ */ /* * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/queue.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/uio.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <dirent.h> #include <string.h> #include <signal.h> #include <syslog.h> #include <errno.h> #include <err.h> #include <pwd.h> #include <event.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/engine.h> #include <openssl/ssl.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/sha.h> #include <openssl/rsa.h> #include "iked.h" #include "ikev2.h" void ca_run(struct privsep *, struct privsep_proc *, void *); void ca_shutdown(struct privsep_proc *); void ca_reset(struct privsep *); int ca_reload(struct iked *); int ca_getreq(struct iked *, struct imsg *); int ca_getcert(struct iked *, struct imsg *); int ca_getauth(struct iked *, struct imsg *); X509 *ca_by_subjectpubkey(X509_STORE *, uint8_t *, size_t); X509 *ca_by_issuer(X509_STORE *, X509_NAME *, struct iked_static_id *); X509 *ca_by_subjectaltname(X509_STORE *, struct iked_static_id *); void ca_store_certs_info(const char *, X509_STORE *); int ca_subjectpubkey_digest(X509 *, uint8_t *, unsigned int *); int ca_x509_subject_cmp(X509 *, struct iked_static_id *); int ca_validate_pubkey(struct iked *, struct iked_static_id *, void *, size_t, struct iked_id *); int ca_validate_cert(struct iked *, struct iked_static_id *, void *, size_t); int ca_privkey_to_method(struct iked_id *); struct ibuf * ca_x509_serialize(X509 *); int ca_x509_subjectaltname_do(X509 *, int, const char *, struct iked_static_id *, struct iked_id *); int ca_x509_subjectaltname_cmp(X509 *, struct iked_static_id *); int ca_x509_subjectaltname_log(X509 *, const char *); int ca_x509_subjectaltname_get(X509 *cert, struct iked_id *); int ca_dispatch_parent(int, struct privsep_proc *, struct imsg *); int ca_dispatch_ikev2(int, struct privsep_proc *, struct imsg *); static struct privsep_proc procs[] = { { "parent", PROC_PARENT, ca_dispatch_parent }, { "ikev2", PROC_IKEV2, ca_dispatch_ikev2 } }; struct ca_store { X509_STORE *ca_cas; X509_LOOKUP *ca_calookup; X509_STORE *ca_certs; X509_LOOKUP *ca_certlookup; struct iked_id ca_privkey; struct iked_id ca_pubkey; uint8_t ca_privkey_method; }; pid_t caproc(struct privsep *ps, struct privsep_proc *p) { return (proc_run(ps, p, procs, nitems(procs), ca_run, NULL)); } void ca_run(struct privsep *ps, struct privsep_proc *p, void *arg) { struct iked *env = ps->ps_env; struct ca_store *store; /* * pledge in the ca process: * stdio - for malloc and basic I/O including events. * rpath - for certificate files. * recvfd - for ocsp sockets. */ if (pledge("stdio rpath recvfd", NULL) == -1) fatal("pledge"); if ((store = calloc(1, sizeof(*store))) == NULL) fatal("%s: failed to allocate cert store", __func__); env->sc_priv = store; p->p_shutdown = ca_shutdown; } void ca_shutdown(struct privsep_proc *p) { struct iked *env = p->p_env; struct ca_store *store; if (env == NULL) return; ibuf_release(env->sc_certreq); if ((store = env->sc_priv) == NULL) return; ibuf_release(store->ca_pubkey.id_buf); ibuf_release(store->ca_privkey.id_buf); free(store); } void ca_getkey(struct privsep *ps, struct iked_id *key, enum imsg_type type) { struct iked *env = ps->ps_env; struct ca_store *store = env->sc_priv; struct iked_id *id; const char *name; if (store == NULL) fatalx("%s: invalid store", __func__); if (type == IMSG_PRIVKEY) { name = "private"; id = &store->ca_privkey; store->ca_privkey_method = ca_privkey_to_method(key); if (store->ca_privkey_method == IKEV2_AUTH_NONE) fatalx("ca: failed to get auth method for privkey"); } else if (type == IMSG_PUBKEY) { name = "public"; id = &store->ca_pubkey; } else fatalx("%s: invalid type %d", __func__, type); log_debug("%s: received %s key type %s length %zd", __func__, name, print_map(key->id_type, ikev2_cert_map), ibuf_length(key->id_buf)); /* clear old key and copy new one */ ibuf_release(id->id_buf); memcpy(id, key, sizeof(*id)); } void ca_reset(struct privsep *ps) { struct iked *env = ps->ps_env; struct ca_store *store = env->sc_priv; if (store->ca_privkey.id_type == IKEV2_ID_NONE || store->ca_pubkey.id_type == IKEV2_ID_NONE) fatalx("ca_reset: keys not loaded"); if (store->ca_cas != NULL) X509_STORE_free(store->ca_cas); if (store->ca_certs != NULL) X509_STORE_free(store->ca_certs); if ((store->ca_cas = X509_STORE_new()) == NULL) fatalx("ca_reset: failed to get ca store"); if ((store->ca_calookup = X509_STORE_add_lookup(store->ca_cas, X509_LOOKUP_file())) == NULL) fatalx("ca_reset: failed to add ca lookup"); if ((store->ca_certs = X509_STORE_new()) == NULL) fatalx("ca_reset: failed to get cert store"); if ((store->ca_certlookup = X509_STORE_add_lookup(store->ca_certs, X509_LOOKUP_file())) == NULL) fatalx("ca_reset: failed to add cert lookup"); if (ca_reload(env) != 0) fatal("ca_reset: reload"); } int ca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg) { struct iked *env = p->p_env; unsigned int mode; switch (imsg->hdr.type) { case IMSG_CTL_RESET: IMSG_SIZE_CHECK(imsg, &mode); memcpy(&mode, imsg->data, sizeof(mode)); if (mode == RESET_ALL || mode == RESET_CA) { log_debug("%s: config reset", __func__); ca_reset(&env->sc_ps); } break; case IMSG_OCSP_FD: ocsp_receive_fd(env, imsg); break; case IMSG_OCSP_URL: config_getocsp(env, imsg); break; case IMSG_PRIVKEY: case IMSG_PUBKEY: config_getkey(env, imsg); break; default: return (-1); } return (0); } int ca_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg) { struct iked *env = p->p_env; switch (imsg->hdr.type) { case IMSG_CERTREQ: ca_getreq(env, imsg); break; case IMSG_CERT: ca_getcert(env, imsg); break; case IMSG_AUTH: ca_getauth(env, imsg); break; default: return (-1); } return (0); } int ca_setcert(struct iked *env, struct iked_sahdr *sh, struct iked_id *id, uint8_t type, uint8_t *data, size_t len, enum privsep_procid procid) { struct iovec iov[4]; int iovcnt = 0; struct iked_static_id idb; /* Must send the cert and a valid Id to the ca process */ if (procid == PROC_CERT) { if (id == NULL || id->id_type == IKEV2_ID_NONE || ibuf_length(id->id_buf) > IKED_ID_SIZE) return (-1); bzero(&idb, sizeof(idb)); /* Convert to a static Id */ idb.id_type = id->id_type; idb.id_offset = id->id_offset; idb.id_length = ibuf_length(id->id_buf); memcpy(&idb.id_data, ibuf_data(id->id_buf), ibuf_length(id->id_buf)); iov[iovcnt].iov_base = &idb; iov[iovcnt].iov_len = sizeof(idb); iovcnt++; } iov[iovcnt].iov_base = sh; iov[iovcnt].iov_len = sizeof(*sh); iovcnt++; iov[iovcnt].iov_base = &type; iov[iovcnt].iov_len = sizeof(type); iovcnt++; if (data != NULL) { iov[iovcnt].iov_base = data; iov[iovcnt].iov_len = len; iovcnt++; } if (proc_composev(&env->sc_ps, procid, IMSG_CERT, iov, iovcnt) == -1) return (-1); return (0); } int ca_setreq(struct iked *env, struct iked_sa *sa, struct iked_static_id *localid, uint8_t type, uint8_t more, uint8_t *data, size_t len, enum privsep_procid procid) { struct iovec iov[5]; int iovcnt = 0; struct iked_static_id idb; struct iked_id id; int ret = -1; /* Convert to a static Id */ bzero(&id, sizeof(id)); if (ikev2_policy2id(localid, &id, 1) != 0) return (-1); bzero(&idb, sizeof(idb)); idb.id_type = id.id_type; idb.id_offset = id.id_offset; idb.id_length = ibuf_length(id.id_buf); memcpy(&idb.id_data, ibuf_data(id.id_buf), ibuf_length(id.id_buf)); iov[iovcnt].iov_base = &idb; iov[iovcnt].iov_len = sizeof(idb); iovcnt++; iov[iovcnt].iov_base = &sa->sa_hdr; iov[iovcnt].iov_len = sizeof(sa->sa_hdr); iovcnt++; iov[iovcnt].iov_base = &type; iov[iovcnt].iov_len = sizeof(type); iovcnt++; iov[iovcnt].iov_base = &more; iov[iovcnt].iov_len = sizeof(more); iovcnt++; if (data != NULL) { iov[iovcnt].iov_base = data; iov[iovcnt].iov_len = len; iovcnt++; } if (proc_composev(&env->sc_ps, procid, IMSG_CERTREQ, iov, iovcnt) == -1) goto done; sa_stateflags(sa, IKED_REQ_CERTREQ); ret = 0; done: ibuf_release(id.id_buf); return (ret); } static int auth_sig_compatible(uint8_t type) { switch (type) { case IKEV2_AUTH_RSA_SIG: case IKEV2_AUTH_ECDSA_256: case IKEV2_AUTH_ECDSA_384: case IKEV2_AUTH_ECDSA_521: case IKEV2_AUTH_SIG_ANY: return (1); } return (0); } int ca_setauth(struct iked *env, struct iked_sa *sa, struct ibuf *authmsg, enum privsep_procid id) { struct iovec iov[3]; int iovcnt = 3; struct iked_policy *policy = sa->sa_policy; uint8_t type = policy->pol_auth.auth_method; if (id == PROC_CERT) { /* switch encoding to IKEV2_AUTH_SIG if SHA2 is supported */ if (sa->sa_sigsha2 && auth_sig_compatible(type)) { log_debug("%s: switching %s to SIG", __func__, print_map(type, ikev2_auth_map)); type = IKEV2_AUTH_SIG; } else if (!sa->sa_sigsha2 && type == IKEV2_AUTH_SIG_ANY) { log_debug("%s: switching SIG to RSA_SIG(*)", __func__); /* XXX ca might auto-switch to ECDSA */ type = IKEV2_AUTH_RSA_SIG; } else if (type == IKEV2_AUTH_SIG) { log_debug("%s: using SIG (RFC7427)", __func__); } } if (type == IKEV2_AUTH_SHARED_KEY_MIC) { sa->sa_stateflags |= IKED_REQ_AUTH; return (ikev2_msg_authsign(env, sa, &policy->pol_auth, authmsg)); } iov[0].iov_base = &sa->sa_hdr; iov[0].iov_len = sizeof(sa->sa_hdr); iov[1].iov_base = &type; iov[1].iov_len = sizeof(type); if (type == IKEV2_AUTH_NONE) iovcnt--; else { iov[2].iov_base = ibuf_data(authmsg); iov[2].iov_len = ibuf_size(authmsg); log_debug("%s: auth length %zu", __func__, ibuf_size(authmsg)); } if (proc_composev(&env->sc_ps, id, IMSG_AUTH, iov, iovcnt) == -1) return (-1); return (0); } int ca_getcert(struct iked *env, struct imsg *imsg) { struct iked_sahdr sh; uint8_t type; uint8_t *ptr; size_t len; struct iked_static_id id; unsigned int i; struct iovec iov[3]; int iovcnt = 3, cmd, ret = 0; struct iked_id key; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(id) + sizeof(sh) + sizeof(type); if (len < i) return (-1); memcpy(&id, ptr, sizeof(id)); if (id.id_type == IKEV2_ID_NONE) return (-1); memcpy(&sh, ptr + sizeof(id), sizeof(sh)); memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(uint8_t)); ptr += i; len -= i; bzero(&key, sizeof(key)); switch (type) { case IKEV2_CERT_X509_CERT: ret = ca_validate_cert(env, &id, ptr, len); if (ret == 0 && env->sc_ocsp_url) { ret = ocsp_validate_cert(env, &id, ptr, len, sh, type); if (ret == 0) return (0); } break; case IKEV2_CERT_RSA_KEY: case IKEV2_CERT_ECDSA: ret = ca_validate_pubkey(env, &id, ptr, len, NULL); break; case IKEV2_CERT_NONE: /* Fallback to public key */ ret = ca_validate_pubkey(env, &id, NULL, 0, &key); if (ret == 0) { ptr = ibuf_data(key.id_buf); len = ibuf_length(key.id_buf); type = key.id_type; } break; default: log_debug("%s: unsupported cert type %d", __func__, type); ret = -1; break; } if (ret == 0) cmd = IMSG_CERTVALID; else cmd = IMSG_CERTINVALID; iov[0].iov_base = &sh; iov[0].iov_len = sizeof(sh); iov[1].iov_base = &type; iov[1].iov_len = sizeof(type); iov[2].iov_base = ptr; iov[2].iov_len = len; if (proc_composev(&env->sc_ps, PROC_IKEV2, cmd, iov, iovcnt) == -1) return (-1); return (0); } int ca_getreq(struct iked *env, struct imsg *imsg) { struct ca_store *store = env->sc_priv; struct iked_sahdr sh; uint8_t type, more; uint8_t *ptr; size_t len; unsigned int i; X509 *ca = NULL, *cert = NULL; struct ibuf *buf; struct iked_static_id id; char idstr[IKED_ID_SIZE]; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(id) + sizeof(type) + sizeof(sh) + sizeof(more); if (len < i) return (-1); memcpy(&id, ptr, sizeof(id)); if (id.id_type == IKEV2_ID_NONE) return (-1); memcpy(&sh, ptr + sizeof(id), sizeof(sh)); memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(type)); memcpy(&more, ptr + sizeof(id) + sizeof(sh) + sizeof(type), sizeof(more)); ptr += i; len -= i; switch (type) { case IKEV2_CERT_RSA_KEY: case IKEV2_CERT_ECDSA: /* * Find a local raw public key that matches the type * received in the CERTREQ payoad */ if (store->ca_pubkey.id_type != type || store->ca_pubkey.id_buf == NULL) goto fallback; buf = ibuf_dup(store->ca_pubkey.id_buf); log_debug("%s: using local public key of type %s", __func__, print_map(type, ikev2_cert_map)); break; case IKEV2_CERT_X509_CERT: if (len == 0 || len % SHA_DIGEST_LENGTH) { log_info("%s: invalid CERTREQ data.", SPI_SH(&sh, __func__)); return (-1); } /* * Find a local certificate signed by any of the CAs * received in the CERTREQ payload */ for (i = 0; i < len; i += SHA_DIGEST_LENGTH) { if ((ca = ca_by_subjectpubkey(store->ca_cas, ptr + i, SHA_DIGEST_LENGTH)) == NULL) continue; log_debug("%s: found CA %s", __func__, ca->name); if ((cert = ca_by_issuer(store->ca_certs, X509_get_subject_name(ca), &id)) != NULL) { /* XXX * should we re-validate our own cert here? */ break; } } /* Fallthrough */ case IKEV2_CERT_NONE: fallback: /* * If no certificate or key matching any of the trust-anchors * was found and this was the last CERTREQ, try to find one with * subjectAltName matching the ID */ if (more) return (0); if (cert == NULL) cert = ca_by_subjectaltname(store->ca_certs, &id); /* If there is no matching certificate use local raw pubkey */ if (cert == NULL) { if (ikev2_print_static_id(&id, idstr, sizeof(idstr)) == -1) return (-1); log_info("%s: no valid local certificate found for %s", SPI_SH(&sh, __func__), idstr); ca_store_certs_info(SPI_SH(&sh, __func__), store->ca_certs); if (store->ca_pubkey.id_buf == NULL) return (-1); buf = ibuf_dup(store->ca_pubkey.id_buf); type = store->ca_pubkey.id_type; log_info("%s: using local public key of type %s", SPI_SH(&sh, __func__), print_map(type, ikev2_cert_map)); break; } log_debug("%s: found local certificate %s", __func__, cert->name); if ((buf = ca_x509_serialize(cert)) == NULL) return (-1); break; default: log_warnx("%s: unknown cert type requested", SPI_SH(&sh, __func__)); return (-1); } ca_setcert(env, &sh, NULL, type, ibuf_data(buf), ibuf_size(buf), PROC_IKEV2); ibuf_release(buf); return (0); } int ca_getauth(struct iked *env, struct imsg *imsg) { struct ca_store *store = env->sc_priv; struct iked_sahdr sh; uint8_t method; uint8_t *ptr; size_t len; unsigned int i; int ret = -1; struct iked_sa sa; struct iked_policy policy; struct iked_id *id; struct ibuf *authmsg; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(method) + sizeof(sh); if (len <= i) return (-1); memcpy(&sh, ptr, sizeof(sh)); memcpy(&method, ptr + sizeof(sh), sizeof(uint8_t)); if (method == IKEV2_AUTH_SHARED_KEY_MIC) return (-1); ptr += i; len -= i; if ((authmsg = ibuf_new(ptr, len)) == NULL) return (-1); /* * Create fake SA and policy */ bzero(&sa, sizeof(sa)); bzero(&policy, sizeof(policy)); memcpy(&sa.sa_hdr, &sh, sizeof(sh)); sa.sa_policy = &policy; if (sh.sh_initiator) id = &sa.sa_icert; else id = &sa.sa_rcert; memcpy(id, &store->ca_privkey, sizeof(*id)); policy.pol_auth.auth_method = method == IKEV2_AUTH_SIG ? method : store->ca_privkey_method; if (ikev2_msg_authsign(env, &sa, &policy.pol_auth, authmsg) != 0) { log_debug("%s: AUTH sign failed", __func__); policy.pol_auth.auth_method = IKEV2_AUTH_NONE; } ret = ca_setauth(env, &sa, sa.sa_localauth.id_buf, PROC_IKEV2); ibuf_release(sa.sa_localauth.id_buf); sa.sa_localauth.id_buf = NULL; ibuf_release(authmsg); return (ret); } int ca_reload(struct iked *env) { struct ca_store *store = env->sc_priv; uint8_t md[EVP_MAX_MD_SIZE]; char file[PATH_MAX]; struct iovec iov[2]; struct dirent *entry; STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *x509; DIR *dir; int i, len, iovcnt = 0; /* * Load CAs */ if ((dir = opendir(IKED_CA_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CA_DIR, entry->d_name) < 0) continue; if (!X509_load_cert_file(store->ca_calookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load ca file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } log_debug("%s: loaded ca file %s", __func__, entry->d_name); } closedir(dir); /* * Load CRLs for the CAs */ if ((dir = opendir(IKED_CRL_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CRL_DIR, entry->d_name) < 0) continue; if (!X509_load_crl_file(store->ca_calookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load crl file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } /* Only enable CRL checks if we actually loaded a CRL */ X509_STORE_set_flags(store->ca_cas, X509_V_FLAG_CRL_CHECK); log_debug("%s: loaded crl file %s", __func__, entry->d_name); } closedir(dir); /* * Save CAs signatures for the IKEv2 CERTREQ */ ibuf_release(env->sc_certreq); if ((env->sc_certreq = ibuf_new(NULL, 0)) == NULL) return (-1); h = store->ca_cas->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; x509 = xo->data.x509; len = sizeof(md); ca_subjectpubkey_digest(x509, md, &len); log_debug("%s: %s", __func__, x509->name); if (ibuf_add(env->sc_certreq, md, len) != 0) { ibuf_release(env->sc_certreq); env->sc_certreq = NULL; return (-1); } } if (ibuf_length(env->sc_certreq)) { env->sc_certreqtype = IKEV2_CERT_X509_CERT; iov[0].iov_base = &env->sc_certreqtype; iov[0].iov_len = sizeof(env->sc_certreqtype); iovcnt++; iov[1].iov_base = ibuf_data(env->sc_certreq); iov[1].iov_len = ibuf_length(env->sc_certreq); iovcnt++; log_debug("%s: loaded %zu ca certificate%s", __func__, ibuf_length(env->sc_certreq) / SHA_DIGEST_LENGTH, ibuf_length(env->sc_certreq) == SHA_DIGEST_LENGTH ? "" : "s"); (void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt); } /* * Load certificates */ if ((dir = opendir(IKED_CERT_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CERT_DIR, entry->d_name) < 0) continue; if (!X509_load_cert_file(store->ca_certlookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load cert file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } log_debug("%s: loaded cert file %s", __func__, entry->d_name); } closedir(dir); h = store->ca_certs->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; x509 = xo->data.x509; (void)ca_validate_cert(env, NULL, x509, 0); } if (!env->sc_certreqtype) env->sc_certreqtype = store->ca_pubkey.id_type; log_debug("%s: local cert type %s", __func__, print_map(env->sc_certreqtype, ikev2_cert_map)); iov[0].iov_base = &env->sc_certreqtype; iov[0].iov_len = sizeof(env->sc_certreqtype); if (iovcnt == 0) iovcnt++; (void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt); return (0); } X509 * ca_by_subjectpubkey(X509_STORE *ctx, uint8_t *sig, size_t siglen) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *ca; int i; unsigned int len; uint8_t md[EVP_MAX_MD_SIZE]; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; ca = xo->data.x509; len = sizeof(md); ca_subjectpubkey_digest(ca, md, &len); if (len == siglen && memcmp(md, sig, len) == 0) return (ca); } return (NULL); } X509 * ca_by_issuer(X509_STORE *ctx, X509_NAME *subject, struct iked_static_id *id) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; X509_NAME *issuer; if (subject == NULL) return (NULL); h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; if ((issuer = X509_get_issuer_name(cert)) == NULL) continue; else if (X509_NAME_cmp(subject, issuer) == 0) { switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) == 0) return (cert); break; default: if (ca_x509_subjectaltname_cmp(cert, id) == 0) return (cert); break; } } } return (NULL); } X509 * ca_by_subjectaltname(X509_STORE *ctx, struct iked_static_id *id) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) == 0) return (cert); break; default: if (ca_x509_subjectaltname_cmp(cert, id) == 0) return (cert); break; } } return (NULL); } void ca_store_certs_info(const char *msg, X509_STORE *ctx) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; ca_cert_info(msg, cert); } } void ca_cert_info(const char *msg, X509 *cert) { ASN1_INTEGER *asn1_serial; BUF_MEM *memptr; BIO *rawserial = NULL; char buf[BUFSIZ]; if ((asn1_serial = X509_get_serialNumber(cert)) == NULL || (rawserial = BIO_new(BIO_s_mem())) == NULL || i2a_ASN1_INTEGER(rawserial, asn1_serial) <= 0) goto out; if (X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf))) log_info("%s: issuer: %s", msg, buf); BIO_get_mem_ptr(rawserial, &memptr); if (memptr->data != NULL && memptr->length < INT32_MAX) log_info("%s: serial: %.*s", msg, (int)memptr->length, memptr->data); if (X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf))) log_info("%s: subject: %s", msg, buf); ca_x509_subjectaltname_log(cert, msg); out: if (rawserial) BIO_free(rawserial); } int ca_subjectpubkey_digest(X509 *x509, uint8_t *md, unsigned int *size) { EVP_PKEY *pkey; uint8_t *buf = NULL; int buflen; if (*size < SHA_DIGEST_LENGTH) return (-1); /* * Generate a SHA-1 digest of the Subject Public Key Info * element in the X.509 certificate, an ASN.1 sequence * that includes the public key type (eg. RSA) and the * public key value (see 3.7 of RFC7296). */ if ((pkey = X509_get_pubkey(x509)) == NULL) return (-1); buflen = i2d_PUBKEY(pkey, &buf); EVP_PKEY_free(pkey); if (buflen == 0) return (-1); if (!EVP_Digest(buf, buflen, md, size, EVP_sha1(), NULL)) { free(buf); return (-1); } free(buf); return (0); } struct ibuf * ca_x509_serialize(X509 *x509) { long len; struct ibuf *buf; uint8_t *d = NULL; BIO *out; if ((out = BIO_new(BIO_s_mem())) == NULL) return (NULL); if (!i2d_X509_bio(out, x509)) { BIO_free(out); return (NULL); } len = BIO_get_mem_data(out, &d); buf = ibuf_new(d, len); BIO_free(out); return (buf); } int ca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id) { RSA *rsa = NULL; EC_KEY *ec = NULL; uint8_t *d; int len = 0; int ret = -1; switch (key->type) { case EVP_PKEY_RSA: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((rsa = EVP_PKEY_get1_RSA(key)) == NULL) goto done; if ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_RSAPublicKey(rsa, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_RSA_KEY; break; case EVP_PKEY_EC: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL) goto done; if ((len = i2d_EC_PUBKEY(ec, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_EC_PUBKEY(ec, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_ECDSA; break; default: log_debug("%s: unsupported key type %d", __func__, key->type); return (-1); } log_debug("%s: type %s length %d", __func__, print_map(id->id_type, ikev2_cert_map), len); ret = 0; done: if (rsa != NULL) RSA_free(rsa); if (ec != NULL) EC_KEY_free(ec); return (ret); } int ca_privkey_serialize(EVP_PKEY *key, struct iked_id *id) { RSA *rsa = NULL; EC_KEY *ec = NULL; uint8_t *d; int len = 0; int ret = -1; switch (key->type) { case EVP_PKEY_RSA: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((rsa = EVP_PKEY_get1_RSA(key)) == NULL) goto done; if ((len = i2d_RSAPrivateKey(rsa, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_RSAPrivateKey(rsa, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_RSA_KEY; break; case EVP_PKEY_EC: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL) goto done; if ((len = i2d_ECPrivateKey(ec, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_ECPrivateKey(ec, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_ECDSA; break; default: log_debug("%s: unsupported key type %d", __func__, key->type); return (-1); } log_debug("%s: type %s length %d", __func__, print_map(id->id_type, ikev2_cert_map), len); ret = 0; done: if (rsa != NULL) RSA_free(rsa); if (ec != NULL) EC_KEY_free(ec); return (ret); } int ca_privkey_to_method(struct iked_id *privkey) { BIO *rawcert = NULL; EC_KEY *ec = NULL; const EC_GROUP *group = NULL; uint8_t method = IKEV2_AUTH_NONE; switch (privkey->id_type) { case IKEV2_CERT_RSA_KEY: method = IKEV2_AUTH_RSA_SIG; break; case IKEV2_CERT_ECDSA: if ((rawcert = BIO_new_mem_buf(ibuf_data(privkey->id_buf), ibuf_length(privkey->id_buf))) == NULL) goto out; if ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL) goto out; if ((group = EC_KEY_get0_group(ec)) == NULL) goto out; switch (EC_GROUP_get_degree(group)) { case 256: method = IKEV2_AUTH_ECDSA_256; break; case 384: method = IKEV2_AUTH_ECDSA_384; break; case 521: method = IKEV2_AUTH_ECDSA_521; break; } } log_debug("%s: type %s method %s", __func__, print_map(privkey->id_type, ikev2_cert_map), print_map(method, ikev2_auth_map)); out: if (ec != NULL) EC_KEY_free(ec); if (rawcert != NULL) BIO_free(rawcert); return (method); } char * ca_asn1_name(uint8_t *asn1, size_t len) { X509_NAME *name = NULL; char *str = NULL; const uint8_t *p; p = asn1; if ((name = d2i_X509_NAME(NULL, &p, len)) == NULL) return (NULL); str = X509_NAME_oneline(name, NULL, 0); X509_NAME_free(name); return (str); } /* * Copy 'src' to 'dst' until 'marker' is found while unescaping '\' * characters. The return value tells the caller where to continue * parsing (might be the end of the string) or NULL on error. */ static char * ca_x509_name_unescape(char *src, char *dst, char marker) { while (*src) { if (*src == marker) { src++; break; } if (*src == '\\') { src++; if (!*src) { log_warnx("%s: '\\' at end of string", __func__); *dst = '\0'; return (NULL); } } *dst++ = *src++; } *dst = '\0'; return (src); } /* * Parse an X509 subject name where 'subject' is in the format * /type0=value0/type1=value1/type2=... * where characters may be escaped by '\'. * See lib/libssl/src/apps/apps.c:parse_name() */ void * ca_x509_name_parse(char *subject) { char *cp, *value = NULL, *type = NULL; size_t maxlen; X509_NAME *name = NULL; if (*subject != '/') { log_warnx("%s: leading '/' missing in '%s'", __func__, subject); goto err; } /* length of subject is upper bound for unescaped type/value */ maxlen = strlen(subject) + 1; if ((type = calloc(1, maxlen)) == NULL || (value = calloc(1, maxlen)) == NULL || (name = X509_NAME_new()) == NULL) goto err; cp = subject + 1; while (*cp) { /* unescape type, terminated by '=' */ cp = ca_x509_name_unescape(cp, type, '='); if (cp == NULL) { log_warnx("%s: could not parse type", __func__); goto err; } if (!*cp) { log_warnx("%s: missing value", __func__); goto err; } /* unescape value, terminated by '/' */ cp = ca_x509_name_unescape(cp, value, '/'); if (cp == NULL) { log_warnx("%s: could not parse value", __func__); goto err; } if (!*type || !*value) { log_warnx("%s: empty type or value", __func__); goto err; } log_debug("%s: setting '%s' to '%s'", __func__, type, value); if (!X509_NAME_add_entry_by_txt(name, type, MBSTRING_ASC, value, -1, -1, 0)) { log_warnx("%s: setting '%s' to '%s' failed", __func__, type, value); ca_sslerror(__func__); goto err; } } free(type); free(value); return (name); err: X509_NAME_free(name); free(type); free(value); return (NULL); } int ca_validate_pubkey(struct iked *env, struct iked_static_id *id, void *data, size_t len, struct iked_id *out) { BIO *rawcert = NULL; RSA *peerrsa = NULL, *localrsa = NULL; EC_KEY *peerec = NULL; EVP_PKEY *peerkey = NULL, *localkey = NULL; int ret = -1; FILE *fp = NULL; char idstr[IKED_ID_SIZE]; char file[PATH_MAX]; struct iked_id idp; switch (id->id_type) { case IKEV2_ID_IPV4: case IKEV2_ID_FQDN: case IKEV2_ID_UFQDN: case IKEV2_ID_IPV6: break; default: /* Some types like ASN1_DN will not be mapped to file names */ log_debug("%s: unsupported public key type %s", __func__, print_map(id->id_type, ikev2_id_map)); return (-1); } bzero(&idp, sizeof(idp)); if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL) goto done; idp.id_type = id->id_type; idp.id_offset = id->id_offset; if (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1) goto done; if (len == 0 && data) { /* Data is already an public key */ peerkey = (EVP_PKEY *)data; } if (len > 0) { if ((rawcert = BIO_new_mem_buf(data, len)) == NULL) goto done; if ((peerkey = EVP_PKEY_new()) == NULL) goto sslerr; if ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL))) { if (!EVP_PKEY_set1_RSA(peerkey, peerrsa)) { goto sslerr; } } else if (BIO_reset(rawcert) == 1 && (peerec = d2i_EC_PUBKEY_bio(rawcert, NULL))) { if (!EVP_PKEY_set1_EC_KEY(peerkey, peerec)) { goto sslerr; } } else { log_debug("%s: unknown key type received", __func__); goto sslerr; } } lc_idtype(idstr); if (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) || strlcat(file, idstr, sizeof(file)) >= sizeof(file)) { log_debug("%s: public key id too long %s", __func__, idstr); goto done; } if ((fp = fopen(file, "r")) == NULL) { /* Log to debug when called from ca_validate_cert */ logit(len == 0 ? LOG_DEBUG : LOG_INFO, "%s: could not open public key %s", __func__, file); goto done; } localkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (localkey == NULL) { /* reading PKCS #8 failed, try PEM RSA */ rewind(fp); localrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL); fclose(fp); if (localrsa == NULL) goto sslerr; if ((localkey = EVP_PKEY_new()) == NULL) goto sslerr; if (!EVP_PKEY_set1_RSA(localkey, localrsa)) goto sslerr; } else { fclose(fp); } if (localkey == NULL) goto sslerr; if (peerkey && !EVP_PKEY_cmp(peerkey, localkey)) { log_debug("%s: public key does not match %s", __func__, file); goto done; } log_debug("%s: valid public key in file %s", __func__, file); if (out && ca_pubkey_serialize(localkey, out)) goto done; ret = 0; sslerr: if (ret != 0) ca_sslerror(__func__); done: ibuf_release(idp.id_buf); if (localkey != NULL) EVP_PKEY_free(localkey); if (peerrsa != NULL) RSA_free(peerrsa); if (peerec != NULL) EC_KEY_free(peerec); if (localrsa != NULL) RSA_free(localrsa); if (rawcert != NULL) { BIO_free(rawcert); if (peerkey != NULL) EVP_PKEY_free(peerkey); } return (ret); } int ca_validate_cert(struct iked *env, struct iked_static_id *id, void *data, size_t len) { struct ca_store *store = env->sc_priv; X509_STORE_CTX csc; BIO *rawcert = NULL; X509 *cert = NULL; EVP_PKEY *pkey; int ret = -1, result, error; X509_NAME *subject; const char *errstr = "failed"; if (len == 0) { /* Data is already an X509 certificate */ cert = (X509 *)data; } else { /* Convert data to X509 certificate */ if ((rawcert = BIO_new_mem_buf(data, len)) == NULL) goto done; if ((cert = d2i_X509_bio(rawcert, NULL)) == NULL) goto done; } /* Certificate needs a valid subjectName */ if ((subject = X509_get_subject_name(cert)) == NULL) { errstr = "invalid subject"; goto done; } if (id != NULL) { if ((pkey = X509_get_pubkey(cert)) == NULL) { errstr = "no public key in cert"; goto done; } ret = ca_validate_pubkey(env, id, pkey, 0, NULL); EVP_PKEY_free(pkey); if (ret == 0) { errstr = "in public key file, ok"; goto done; } switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) < 0) { errstr = "ASN1_DN identifier mismatch"; goto done; } break; default: if (ca_x509_subjectaltname_cmp(cert, id) != 0) { errstr = "invalid subjectAltName extension"; goto done; } break; } } bzero(&csc, sizeof(csc)); X509_STORE_CTX_init(&csc, store->ca_cas, cert, NULL); if (store->ca_cas->param->flags & X509_V_FLAG_CRL_CHECK) { X509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK_ALL); } result = X509_verify_cert(&csc); error = csc.error; X509_STORE_CTX_cleanup(&csc); if (error != 0) { errstr = X509_verify_cert_error_string(error); goto done; } if (!result) { /* XXX should we accept self-signed certificates? */ errstr = "rejecting self-signed certificate"; goto done; } /* Success */ ret = 0; errstr = "ok"; done: if (cert != NULL) log_debug("%s: %s %.100s", __func__, cert->name, errstr); if (rawcert != NULL) { BIO_free(rawcert); if (cert != NULL) X509_free(cert); } return (ret); } /* check if subject from cert matches the id */ int ca_x509_subject_cmp(X509 *cert, struct iked_static_id *id) { X509_NAME *subject, *idname = NULL; const uint8_t *idptr; size_t idlen; int ret = -1; if (id->id_type != IKEV2_ID_ASN1_DN) return (-1); if ((subject = X509_get_subject_name(cert)) == NULL) return (-1); if (id->id_length <= id->id_offset) return (-1); idlen = id->id_length - id->id_offset; idptr = id->id_data + id->id_offset; if ((idname = d2i_X509_NAME(NULL, &idptr, idlen)) == NULL) return (-1); if (X509_NAME_cmp(subject, idname) == 0) ret = 0; X509_NAME_free(idname); return (ret); } #define MODE_ALT_LOG 1 #define MODE_ALT_GET 2 #define MODE_ALT_CMP 3 int ca_x509_subjectaltname_do(X509 *cert, int mode, const char *logmsg, struct iked_static_id *id, struct iked_id *retid) { STACK_OF(GENERAL_NAME) *stack = NULL; GENERAL_NAME *entry; ASN1_STRING *cstr; char idstr[IKED_ID_SIZE]; int idx, ret, i, type, len; uint8_t *data; ret = -1; idx = -1; while ((stack = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, &idx)) != NULL) { for (i = 0; i < sk_GENERAL_NAME_num(stack); i++) { entry = sk_GENERAL_NAME_value(stack, i); switch (entry->type) { case GEN_DNS: cstr = entry->d.dNSName; if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING) continue; type = IKEV2_ID_FQDN; break; case GEN_EMAIL: cstr = entry->d.rfc822Name; if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING) continue; type = IKEV2_ID_UFQDN; break; case GEN_IPADD: cstr = entry->d.iPAddress; switch (ASN1_STRING_length(cstr)) { case 4: type = IKEV2_ID_IPV4; break; case 16: type = IKEV2_ID_IPV6; break; default: log_debug("%s: invalid subjectAltName" " IP address", __func__); continue; } break; default: continue; } len = ASN1_STRING_length(cstr); data = ASN1_STRING_data(cstr); if (mode == MODE_ALT_LOG) { struct iked_id sanid; bzero(&sanid, sizeof(sanid)); sanid.id_offset = 0; sanid.id_type = type; if ((sanid.id_buf = ibuf_new(data, len)) == NULL) { log_debug("%s: failed to get id buffer", __func__); continue; } ikev2_print_id(&sanid, idstr, sizeof(idstr)); log_info("%s: altname: %s", logmsg, idstr); ibuf_release(sanid.id_buf); sanid.id_buf = NULL; } /* Compare length and data */ if (mode == MODE_ALT_CMP) { if (type == id->id_type && (len == (id->id_length - id->id_offset)) && (memcmp(id->id_data + id->id_offset, data, len)) == 0) { ret = 0; break; } } /* Get first ID */ if (mode == MODE_ALT_GET) { ibuf_release(retid->id_buf); if ((retid->id_buf = ibuf_new(data, len)) == NULL) { log_debug("%s: failed to get id buffer", __func__); ret = -2; break; } retid->id_offset = 0; ikev2_print_id(retid, idstr, sizeof(idstr)); log_debug("%s: %s", __func__, idstr); ret = 0; break; } } sk_GENERAL_NAME_pop_free(stack, GENERAL_NAME_free); if (ret != -1) break; } if (idx == -1) log_debug("%s: did not find subjectAltName in certificate", __func__); return ret; } int ca_x509_subjectaltname_log(X509 *cert, const char *logmsg) { return ca_x509_subjectaltname_do(cert, MODE_ALT_LOG, logmsg, NULL, NULL); } int ca_x509_subjectaltname_cmp(X509 *cert, struct iked_static_id *id) { return ca_x509_subjectaltname_do(cert, MODE_ALT_CMP, NULL, id, NULL); } int ca_x509_subjectaltname_get(X509 *cert, struct iked_id *retid) { return ca_x509_subjectaltname_do(cert, MODE_ALT_GET, NULL, NULL, retid); } void ca_sslinit(void) { OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); /* Init hardware crypto engines. */ ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); } void ca_sslerror(const char *caller) { unsigned long error; while ((error = ERR_get_error()) != 0) log_warnx("%s: %s: %.100s", __func__, caller, ERR_error_string(error, NULL)); }
./CrossVul/dataset_final_sorted/CWE-639/c/bad_4237_0
crossvul-cpp_data_good_4237_0
/* $OpenBSD: ca.c,v 1.65 2020/07/27 14:22:53 tobhe Exp $ */ /* * Copyright (c) 2010-2013 Reyk Floeter <reyk@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/queue.h> #include <sys/socket.h> #include <sys/wait.h> #include <sys/uio.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <dirent.h> #include <string.h> #include <signal.h> #include <syslog.h> #include <errno.h> #include <err.h> #include <pwd.h> #include <event.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/engine.h> #include <openssl/ssl.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <openssl/sha.h> #include <openssl/rsa.h> #include "iked.h" #include "ikev2.h" void ca_run(struct privsep *, struct privsep_proc *, void *); void ca_shutdown(struct privsep_proc *); void ca_reset(struct privsep *); int ca_reload(struct iked *); int ca_getreq(struct iked *, struct imsg *); int ca_getcert(struct iked *, struct imsg *); int ca_getauth(struct iked *, struct imsg *); X509 *ca_by_subjectpubkey(X509_STORE *, uint8_t *, size_t); X509 *ca_by_issuer(X509_STORE *, X509_NAME *, struct iked_static_id *); X509 *ca_by_subjectaltname(X509_STORE *, struct iked_static_id *); void ca_store_certs_info(const char *, X509_STORE *); int ca_subjectpubkey_digest(X509 *, uint8_t *, unsigned int *); int ca_x509_subject_cmp(X509 *, struct iked_static_id *); int ca_validate_pubkey(struct iked *, struct iked_static_id *, void *, size_t, struct iked_id *); int ca_validate_cert(struct iked *, struct iked_static_id *, void *, size_t); int ca_privkey_to_method(struct iked_id *); struct ibuf * ca_x509_serialize(X509 *); int ca_x509_subjectaltname_do(X509 *, int, const char *, struct iked_static_id *, struct iked_id *); int ca_x509_subjectaltname_cmp(X509 *, struct iked_static_id *); int ca_x509_subjectaltname_log(X509 *, const char *); int ca_x509_subjectaltname_get(X509 *cert, struct iked_id *); int ca_dispatch_parent(int, struct privsep_proc *, struct imsg *); int ca_dispatch_ikev2(int, struct privsep_proc *, struct imsg *); static struct privsep_proc procs[] = { { "parent", PROC_PARENT, ca_dispatch_parent }, { "ikev2", PROC_IKEV2, ca_dispatch_ikev2 } }; struct ca_store { X509_STORE *ca_cas; X509_LOOKUP *ca_calookup; X509_STORE *ca_certs; X509_LOOKUP *ca_certlookup; struct iked_id ca_privkey; struct iked_id ca_pubkey; uint8_t ca_privkey_method; }; pid_t caproc(struct privsep *ps, struct privsep_proc *p) { return (proc_run(ps, p, procs, nitems(procs), ca_run, NULL)); } void ca_run(struct privsep *ps, struct privsep_proc *p, void *arg) { struct iked *env = ps->ps_env; struct ca_store *store; /* * pledge in the ca process: * stdio - for malloc and basic I/O including events. * rpath - for certificate files. * recvfd - for ocsp sockets. */ if (pledge("stdio rpath recvfd", NULL) == -1) fatal("pledge"); if ((store = calloc(1, sizeof(*store))) == NULL) fatal("%s: failed to allocate cert store", __func__); env->sc_priv = store; p->p_shutdown = ca_shutdown; } void ca_shutdown(struct privsep_proc *p) { struct iked *env = p->p_env; struct ca_store *store; if (env == NULL) return; ibuf_release(env->sc_certreq); if ((store = env->sc_priv) == NULL) return; ibuf_release(store->ca_pubkey.id_buf); ibuf_release(store->ca_privkey.id_buf); free(store); } void ca_getkey(struct privsep *ps, struct iked_id *key, enum imsg_type type) { struct iked *env = ps->ps_env; struct ca_store *store = env->sc_priv; struct iked_id *id; const char *name; if (store == NULL) fatalx("%s: invalid store", __func__); if (type == IMSG_PRIVKEY) { name = "private"; id = &store->ca_privkey; store->ca_privkey_method = ca_privkey_to_method(key); if (store->ca_privkey_method == IKEV2_AUTH_NONE) fatalx("ca: failed to get auth method for privkey"); } else if (type == IMSG_PUBKEY) { name = "public"; id = &store->ca_pubkey; } else fatalx("%s: invalid type %d", __func__, type); log_debug("%s: received %s key type %s length %zd", __func__, name, print_map(key->id_type, ikev2_cert_map), ibuf_length(key->id_buf)); /* clear old key and copy new one */ ibuf_release(id->id_buf); memcpy(id, key, sizeof(*id)); } void ca_reset(struct privsep *ps) { struct iked *env = ps->ps_env; struct ca_store *store = env->sc_priv; if (store->ca_privkey.id_type == IKEV2_ID_NONE || store->ca_pubkey.id_type == IKEV2_ID_NONE) fatalx("ca_reset: keys not loaded"); if (store->ca_cas != NULL) X509_STORE_free(store->ca_cas); if (store->ca_certs != NULL) X509_STORE_free(store->ca_certs); if ((store->ca_cas = X509_STORE_new()) == NULL) fatalx("ca_reset: failed to get ca store"); if ((store->ca_calookup = X509_STORE_add_lookup(store->ca_cas, X509_LOOKUP_file())) == NULL) fatalx("ca_reset: failed to add ca lookup"); if ((store->ca_certs = X509_STORE_new()) == NULL) fatalx("ca_reset: failed to get cert store"); if ((store->ca_certlookup = X509_STORE_add_lookup(store->ca_certs, X509_LOOKUP_file())) == NULL) fatalx("ca_reset: failed to add cert lookup"); if (ca_reload(env) != 0) fatal("ca_reset: reload"); } int ca_dispatch_parent(int fd, struct privsep_proc *p, struct imsg *imsg) { struct iked *env = p->p_env; unsigned int mode; switch (imsg->hdr.type) { case IMSG_CTL_RESET: IMSG_SIZE_CHECK(imsg, &mode); memcpy(&mode, imsg->data, sizeof(mode)); if (mode == RESET_ALL || mode == RESET_CA) { log_debug("%s: config reset", __func__); ca_reset(&env->sc_ps); } break; case IMSG_OCSP_FD: ocsp_receive_fd(env, imsg); break; case IMSG_OCSP_URL: config_getocsp(env, imsg); break; case IMSG_PRIVKEY: case IMSG_PUBKEY: config_getkey(env, imsg); break; default: return (-1); } return (0); } int ca_dispatch_ikev2(int fd, struct privsep_proc *p, struct imsg *imsg) { struct iked *env = p->p_env; switch (imsg->hdr.type) { case IMSG_CERTREQ: ca_getreq(env, imsg); break; case IMSG_CERT: ca_getcert(env, imsg); break; case IMSG_AUTH: ca_getauth(env, imsg); break; default: return (-1); } return (0); } int ca_setcert(struct iked *env, struct iked_sahdr *sh, struct iked_id *id, uint8_t type, uint8_t *data, size_t len, enum privsep_procid procid) { struct iovec iov[4]; int iovcnt = 0; struct iked_static_id idb; /* Must send the cert and a valid Id to the ca process */ if (procid == PROC_CERT) { if (id == NULL || id->id_type == IKEV2_ID_NONE || ibuf_length(id->id_buf) > IKED_ID_SIZE) return (-1); bzero(&idb, sizeof(idb)); /* Convert to a static Id */ idb.id_type = id->id_type; idb.id_offset = id->id_offset; idb.id_length = ibuf_length(id->id_buf); memcpy(&idb.id_data, ibuf_data(id->id_buf), ibuf_length(id->id_buf)); iov[iovcnt].iov_base = &idb; iov[iovcnt].iov_len = sizeof(idb); iovcnt++; } iov[iovcnt].iov_base = sh; iov[iovcnt].iov_len = sizeof(*sh); iovcnt++; iov[iovcnt].iov_base = &type; iov[iovcnt].iov_len = sizeof(type); iovcnt++; if (data != NULL) { iov[iovcnt].iov_base = data; iov[iovcnt].iov_len = len; iovcnt++; } if (proc_composev(&env->sc_ps, procid, IMSG_CERT, iov, iovcnt) == -1) return (-1); return (0); } int ca_setreq(struct iked *env, struct iked_sa *sa, struct iked_static_id *localid, uint8_t type, uint8_t more, uint8_t *data, size_t len, enum privsep_procid procid) { struct iovec iov[5]; int iovcnt = 0; struct iked_static_id idb; struct iked_id id; int ret = -1; /* Convert to a static Id */ bzero(&id, sizeof(id)); if (ikev2_policy2id(localid, &id, 1) != 0) return (-1); bzero(&idb, sizeof(idb)); idb.id_type = id.id_type; idb.id_offset = id.id_offset; idb.id_length = ibuf_length(id.id_buf); memcpy(&idb.id_data, ibuf_data(id.id_buf), ibuf_length(id.id_buf)); iov[iovcnt].iov_base = &idb; iov[iovcnt].iov_len = sizeof(idb); iovcnt++; iov[iovcnt].iov_base = &sa->sa_hdr; iov[iovcnt].iov_len = sizeof(sa->sa_hdr); iovcnt++; iov[iovcnt].iov_base = &type; iov[iovcnt].iov_len = sizeof(type); iovcnt++; iov[iovcnt].iov_base = &more; iov[iovcnt].iov_len = sizeof(more); iovcnt++; if (data != NULL) { iov[iovcnt].iov_base = data; iov[iovcnt].iov_len = len; iovcnt++; } if (proc_composev(&env->sc_ps, procid, IMSG_CERTREQ, iov, iovcnt) == -1) goto done; sa_stateflags(sa, IKED_REQ_CERTREQ); ret = 0; done: ibuf_release(id.id_buf); return (ret); } static int auth_sig_compatible(uint8_t type) { switch (type) { case IKEV2_AUTH_RSA_SIG: case IKEV2_AUTH_ECDSA_256: case IKEV2_AUTH_ECDSA_384: case IKEV2_AUTH_ECDSA_521: case IKEV2_AUTH_SIG_ANY: return (1); } return (0); } int ca_setauth(struct iked *env, struct iked_sa *sa, struct ibuf *authmsg, enum privsep_procid id) { struct iovec iov[3]; int iovcnt = 3; struct iked_policy *policy = sa->sa_policy; uint8_t type = policy->pol_auth.auth_method; if (id == PROC_CERT) { /* switch encoding to IKEV2_AUTH_SIG if SHA2 is supported */ if (sa->sa_sigsha2 && auth_sig_compatible(type)) { log_debug("%s: switching %s to SIG", __func__, print_map(type, ikev2_auth_map)); type = IKEV2_AUTH_SIG; } else if (!sa->sa_sigsha2 && type == IKEV2_AUTH_SIG_ANY) { log_debug("%s: switching SIG to RSA_SIG(*)", __func__); /* XXX ca might auto-switch to ECDSA */ type = IKEV2_AUTH_RSA_SIG; } else if (type == IKEV2_AUTH_SIG) { log_debug("%s: using SIG (RFC7427)", __func__); } } if (type == IKEV2_AUTH_SHARED_KEY_MIC) { sa->sa_stateflags |= IKED_REQ_AUTH; return (ikev2_msg_authsign(env, sa, &policy->pol_auth, authmsg)); } iov[0].iov_base = &sa->sa_hdr; iov[0].iov_len = sizeof(sa->sa_hdr); iov[1].iov_base = &type; iov[1].iov_len = sizeof(type); if (type == IKEV2_AUTH_NONE) iovcnt--; else { iov[2].iov_base = ibuf_data(authmsg); iov[2].iov_len = ibuf_size(authmsg); log_debug("%s: auth length %zu", __func__, ibuf_size(authmsg)); } if (proc_composev(&env->sc_ps, id, IMSG_AUTH, iov, iovcnt) == -1) return (-1); return (0); } int ca_getcert(struct iked *env, struct imsg *imsg) { struct iked_sahdr sh; uint8_t type; uint8_t *ptr; size_t len; struct iked_static_id id; unsigned int i; struct iovec iov[3]; int iovcnt = 3, cmd, ret = 0; struct iked_id key; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(id) + sizeof(sh) + sizeof(type); if (len < i) return (-1); memcpy(&id, ptr, sizeof(id)); if (id.id_type == IKEV2_ID_NONE) return (-1); memcpy(&sh, ptr + sizeof(id), sizeof(sh)); memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(uint8_t)); ptr += i; len -= i; bzero(&key, sizeof(key)); switch (type) { case IKEV2_CERT_X509_CERT: ret = ca_validate_cert(env, &id, ptr, len); if (ret == 0 && env->sc_ocsp_url) { ret = ocsp_validate_cert(env, &id, ptr, len, sh, type); if (ret == 0) return (0); } break; case IKEV2_CERT_RSA_KEY: case IKEV2_CERT_ECDSA: ret = ca_validate_pubkey(env, &id, ptr, len, NULL); break; case IKEV2_CERT_NONE: /* Fallback to public key */ ret = ca_validate_pubkey(env, &id, NULL, 0, &key); if (ret == 0) { ptr = ibuf_data(key.id_buf); len = ibuf_length(key.id_buf); type = key.id_type; } break; default: log_debug("%s: unsupported cert type %d", __func__, type); ret = -1; break; } if (ret == 0) cmd = IMSG_CERTVALID; else cmd = IMSG_CERTINVALID; iov[0].iov_base = &sh; iov[0].iov_len = sizeof(sh); iov[1].iov_base = &type; iov[1].iov_len = sizeof(type); iov[2].iov_base = ptr; iov[2].iov_len = len; if (proc_composev(&env->sc_ps, PROC_IKEV2, cmd, iov, iovcnt) == -1) return (-1); return (0); } int ca_getreq(struct iked *env, struct imsg *imsg) { struct ca_store *store = env->sc_priv; struct iked_sahdr sh; uint8_t type, more; uint8_t *ptr; size_t len; unsigned int i; X509 *ca = NULL, *cert = NULL; struct ibuf *buf; struct iked_static_id id; char idstr[IKED_ID_SIZE]; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(id) + sizeof(type) + sizeof(sh) + sizeof(more); if (len < i) return (-1); memcpy(&id, ptr, sizeof(id)); if (id.id_type == IKEV2_ID_NONE) return (-1); memcpy(&sh, ptr + sizeof(id), sizeof(sh)); memcpy(&type, ptr + sizeof(id) + sizeof(sh), sizeof(type)); memcpy(&more, ptr + sizeof(id) + sizeof(sh) + sizeof(type), sizeof(more)); ptr += i; len -= i; switch (type) { case IKEV2_CERT_RSA_KEY: case IKEV2_CERT_ECDSA: /* * Find a local raw public key that matches the type * received in the CERTREQ payoad */ if (store->ca_pubkey.id_type != type || store->ca_pubkey.id_buf == NULL) goto fallback; buf = ibuf_dup(store->ca_pubkey.id_buf); log_debug("%s: using local public key of type %s", __func__, print_map(type, ikev2_cert_map)); break; case IKEV2_CERT_X509_CERT: if (len == 0 || len % SHA_DIGEST_LENGTH) { log_info("%s: invalid CERTREQ data.", SPI_SH(&sh, __func__)); return (-1); } /* * Find a local certificate signed by any of the CAs * received in the CERTREQ payload */ for (i = 0; i < len; i += SHA_DIGEST_LENGTH) { if ((ca = ca_by_subjectpubkey(store->ca_cas, ptr + i, SHA_DIGEST_LENGTH)) == NULL) continue; log_debug("%s: found CA %s", __func__, ca->name); if ((cert = ca_by_issuer(store->ca_certs, X509_get_subject_name(ca), &id)) != NULL) { /* XXX * should we re-validate our own cert here? */ break; } } /* Fallthrough */ case IKEV2_CERT_NONE: fallback: /* * If no certificate or key matching any of the trust-anchors * was found and this was the last CERTREQ, try to find one with * subjectAltName matching the ID */ if (more) return (0); if (cert == NULL) cert = ca_by_subjectaltname(store->ca_certs, &id); /* If there is no matching certificate use local raw pubkey */ if (cert == NULL) { if (ikev2_print_static_id(&id, idstr, sizeof(idstr)) == -1) return (-1); log_info("%s: no valid local certificate found for %s", SPI_SH(&sh, __func__), idstr); ca_store_certs_info(SPI_SH(&sh, __func__), store->ca_certs); if (store->ca_pubkey.id_buf == NULL) return (-1); buf = ibuf_dup(store->ca_pubkey.id_buf); type = store->ca_pubkey.id_type; log_info("%s: using local public key of type %s", SPI_SH(&sh, __func__), print_map(type, ikev2_cert_map)); break; } log_debug("%s: found local certificate %s", __func__, cert->name); if ((buf = ca_x509_serialize(cert)) == NULL) return (-1); break; default: log_warnx("%s: unknown cert type requested", SPI_SH(&sh, __func__)); return (-1); } ca_setcert(env, &sh, NULL, type, ibuf_data(buf), ibuf_size(buf), PROC_IKEV2); ibuf_release(buf); return (0); } int ca_getauth(struct iked *env, struct imsg *imsg) { struct ca_store *store = env->sc_priv; struct iked_sahdr sh; uint8_t method; uint8_t *ptr; size_t len; unsigned int i; int ret = -1; struct iked_sa sa; struct iked_policy policy; struct iked_id *id; struct ibuf *authmsg; ptr = (uint8_t *)imsg->data; len = IMSG_DATA_SIZE(imsg); i = sizeof(method) + sizeof(sh); if (len <= i) return (-1); memcpy(&sh, ptr, sizeof(sh)); memcpy(&method, ptr + sizeof(sh), sizeof(uint8_t)); if (method == IKEV2_AUTH_SHARED_KEY_MIC) return (-1); ptr += i; len -= i; if ((authmsg = ibuf_new(ptr, len)) == NULL) return (-1); /* * Create fake SA and policy */ bzero(&sa, sizeof(sa)); bzero(&policy, sizeof(policy)); memcpy(&sa.sa_hdr, &sh, sizeof(sh)); sa.sa_policy = &policy; if (sh.sh_initiator) id = &sa.sa_icert; else id = &sa.sa_rcert; memcpy(id, &store->ca_privkey, sizeof(*id)); policy.pol_auth.auth_method = method == IKEV2_AUTH_SIG ? method : store->ca_privkey_method; if (ikev2_msg_authsign(env, &sa, &policy.pol_auth, authmsg) != 0) { log_debug("%s: AUTH sign failed", __func__); policy.pol_auth.auth_method = IKEV2_AUTH_NONE; } ret = ca_setauth(env, &sa, sa.sa_localauth.id_buf, PROC_IKEV2); ibuf_release(sa.sa_localauth.id_buf); sa.sa_localauth.id_buf = NULL; ibuf_release(authmsg); return (ret); } int ca_reload(struct iked *env) { struct ca_store *store = env->sc_priv; uint8_t md[EVP_MAX_MD_SIZE]; char file[PATH_MAX]; struct iovec iov[2]; struct dirent *entry; STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *x509; DIR *dir; int i, len, iovcnt = 0; /* * Load CAs */ if ((dir = opendir(IKED_CA_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CA_DIR, entry->d_name) < 0) continue; if (!X509_load_cert_file(store->ca_calookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load ca file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } log_debug("%s: loaded ca file %s", __func__, entry->d_name); } closedir(dir); /* * Load CRLs for the CAs */ if ((dir = opendir(IKED_CRL_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CRL_DIR, entry->d_name) < 0) continue; if (!X509_load_crl_file(store->ca_calookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load crl file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } /* Only enable CRL checks if we actually loaded a CRL */ X509_STORE_set_flags(store->ca_cas, X509_V_FLAG_CRL_CHECK); log_debug("%s: loaded crl file %s", __func__, entry->d_name); } closedir(dir); /* * Save CAs signatures for the IKEv2 CERTREQ */ ibuf_release(env->sc_certreq); if ((env->sc_certreq = ibuf_new(NULL, 0)) == NULL) return (-1); h = store->ca_cas->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; x509 = xo->data.x509; len = sizeof(md); ca_subjectpubkey_digest(x509, md, &len); log_debug("%s: %s", __func__, x509->name); if (ibuf_add(env->sc_certreq, md, len) != 0) { ibuf_release(env->sc_certreq); env->sc_certreq = NULL; return (-1); } } if (ibuf_length(env->sc_certreq)) { env->sc_certreqtype = IKEV2_CERT_X509_CERT; iov[0].iov_base = &env->sc_certreqtype; iov[0].iov_len = sizeof(env->sc_certreqtype); iovcnt++; iov[1].iov_base = ibuf_data(env->sc_certreq); iov[1].iov_len = ibuf_length(env->sc_certreq); iovcnt++; log_debug("%s: loaded %zu ca certificate%s", __func__, ibuf_length(env->sc_certreq) / SHA_DIGEST_LENGTH, ibuf_length(env->sc_certreq) == SHA_DIGEST_LENGTH ? "" : "s"); (void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt); } /* * Load certificates */ if ((dir = opendir(IKED_CERT_DIR)) == NULL) return (-1); while ((entry = readdir(dir)) != NULL) { if ((entry->d_type != DT_REG) && (entry->d_type != DT_LNK)) continue; if (snprintf(file, sizeof(file), "%s%s", IKED_CERT_DIR, entry->d_name) < 0) continue; if (!X509_load_cert_file(store->ca_certlookup, file, X509_FILETYPE_PEM)) { log_warn("%s: failed to load cert file %s", __func__, entry->d_name); ca_sslerror(__func__); continue; } log_debug("%s: loaded cert file %s", __func__, entry->d_name); } closedir(dir); h = store->ca_certs->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; x509 = xo->data.x509; (void)ca_validate_cert(env, NULL, x509, 0); } if (!env->sc_certreqtype) env->sc_certreqtype = store->ca_pubkey.id_type; log_debug("%s: local cert type %s", __func__, print_map(env->sc_certreqtype, ikev2_cert_map)); iov[0].iov_base = &env->sc_certreqtype; iov[0].iov_len = sizeof(env->sc_certreqtype); if (iovcnt == 0) iovcnt++; (void)proc_composev(&env->sc_ps, PROC_IKEV2, IMSG_CERTREQ, iov, iovcnt); return (0); } X509 * ca_by_subjectpubkey(X509_STORE *ctx, uint8_t *sig, size_t siglen) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *ca; int i; unsigned int len; uint8_t md[EVP_MAX_MD_SIZE]; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; ca = xo->data.x509; len = sizeof(md); ca_subjectpubkey_digest(ca, md, &len); if (len == siglen && memcmp(md, sig, len) == 0) return (ca); } return (NULL); } X509 * ca_by_issuer(X509_STORE *ctx, X509_NAME *subject, struct iked_static_id *id) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; X509_NAME *issuer; if (subject == NULL) return (NULL); h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; if ((issuer = X509_get_issuer_name(cert)) == NULL) continue; else if (X509_NAME_cmp(subject, issuer) == 0) { switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) == 0) return (cert); break; default: if (ca_x509_subjectaltname_cmp(cert, id) == 0) return (cert); break; } } } return (NULL); } X509 * ca_by_subjectaltname(X509_STORE *ctx, struct iked_static_id *id) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) == 0) return (cert); break; default: if (ca_x509_subjectaltname_cmp(cert, id) == 0) return (cert); break; } } return (NULL); } void ca_store_certs_info(const char *msg, X509_STORE *ctx) { STACK_OF(X509_OBJECT) *h; X509_OBJECT *xo; X509 *cert; int i; h = ctx->objs; for (i = 0; i < sk_X509_OBJECT_num(h); i++) { xo = sk_X509_OBJECT_value(h, i); if (xo->type != X509_LU_X509) continue; cert = xo->data.x509; ca_cert_info(msg, cert); } } void ca_cert_info(const char *msg, X509 *cert) { ASN1_INTEGER *asn1_serial; BUF_MEM *memptr; BIO *rawserial = NULL; char buf[BUFSIZ]; if ((asn1_serial = X509_get_serialNumber(cert)) == NULL || (rawserial = BIO_new(BIO_s_mem())) == NULL || i2a_ASN1_INTEGER(rawserial, asn1_serial) <= 0) goto out; if (X509_NAME_oneline(X509_get_issuer_name(cert), buf, sizeof(buf))) log_info("%s: issuer: %s", msg, buf); BIO_get_mem_ptr(rawserial, &memptr); if (memptr->data != NULL && memptr->length < INT32_MAX) log_info("%s: serial: %.*s", msg, (int)memptr->length, memptr->data); if (X509_NAME_oneline(X509_get_subject_name(cert), buf, sizeof(buf))) log_info("%s: subject: %s", msg, buf); ca_x509_subjectaltname_log(cert, msg); out: if (rawserial) BIO_free(rawserial); } int ca_subjectpubkey_digest(X509 *x509, uint8_t *md, unsigned int *size) { EVP_PKEY *pkey; uint8_t *buf = NULL; int buflen; if (*size < SHA_DIGEST_LENGTH) return (-1); /* * Generate a SHA-1 digest of the Subject Public Key Info * element in the X.509 certificate, an ASN.1 sequence * that includes the public key type (eg. RSA) and the * public key value (see 3.7 of RFC7296). */ if ((pkey = X509_get_pubkey(x509)) == NULL) return (-1); buflen = i2d_PUBKEY(pkey, &buf); EVP_PKEY_free(pkey); if (buflen == 0) return (-1); if (!EVP_Digest(buf, buflen, md, size, EVP_sha1(), NULL)) { free(buf); return (-1); } free(buf); return (0); } struct ibuf * ca_x509_serialize(X509 *x509) { long len; struct ibuf *buf; uint8_t *d = NULL; BIO *out; if ((out = BIO_new(BIO_s_mem())) == NULL) return (NULL); if (!i2d_X509_bio(out, x509)) { BIO_free(out); return (NULL); } len = BIO_get_mem_data(out, &d); buf = ibuf_new(d, len); BIO_free(out); return (buf); } int ca_pubkey_serialize(EVP_PKEY *key, struct iked_id *id) { RSA *rsa = NULL; EC_KEY *ec = NULL; uint8_t *d; int len = 0; int ret = -1; switch (key->type) { case EVP_PKEY_RSA: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((rsa = EVP_PKEY_get1_RSA(key)) == NULL) goto done; if ((len = i2d_RSAPublicKey(rsa, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_RSAPublicKey(rsa, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_RSA_KEY; break; case EVP_PKEY_EC: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL) goto done; if ((len = i2d_EC_PUBKEY(ec, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_EC_PUBKEY(ec, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_ECDSA; break; default: log_debug("%s: unsupported key type %d", __func__, key->type); return (-1); } log_debug("%s: type %s length %d", __func__, print_map(id->id_type, ikev2_cert_map), len); ret = 0; done: if (rsa != NULL) RSA_free(rsa); if (ec != NULL) EC_KEY_free(ec); return (ret); } int ca_privkey_serialize(EVP_PKEY *key, struct iked_id *id) { RSA *rsa = NULL; EC_KEY *ec = NULL; uint8_t *d; int len = 0; int ret = -1; switch (key->type) { case EVP_PKEY_RSA: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((rsa = EVP_PKEY_get1_RSA(key)) == NULL) goto done; if ((len = i2d_RSAPrivateKey(rsa, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_RSAPrivateKey(rsa, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_RSA_KEY; break; case EVP_PKEY_EC: id->id_type = 0; id->id_offset = 0; ibuf_release(id->id_buf); id->id_buf = NULL; if ((ec = EVP_PKEY_get1_EC_KEY(key)) == NULL) goto done; if ((len = i2d_ECPrivateKey(ec, NULL)) <= 0) goto done; if ((id->id_buf = ibuf_new(NULL, len)) == NULL) goto done; d = ibuf_data(id->id_buf); if (i2d_ECPrivateKey(ec, &d) != len) { ibuf_release(id->id_buf); id->id_buf = NULL; goto done; } id->id_type = IKEV2_CERT_ECDSA; break; default: log_debug("%s: unsupported key type %d", __func__, key->type); return (-1); } log_debug("%s: type %s length %d", __func__, print_map(id->id_type, ikev2_cert_map), len); ret = 0; done: if (rsa != NULL) RSA_free(rsa); if (ec != NULL) EC_KEY_free(ec); return (ret); } int ca_privkey_to_method(struct iked_id *privkey) { BIO *rawcert = NULL; EC_KEY *ec = NULL; const EC_GROUP *group = NULL; uint8_t method = IKEV2_AUTH_NONE; switch (privkey->id_type) { case IKEV2_CERT_RSA_KEY: method = IKEV2_AUTH_RSA_SIG; break; case IKEV2_CERT_ECDSA: if ((rawcert = BIO_new_mem_buf(ibuf_data(privkey->id_buf), ibuf_length(privkey->id_buf))) == NULL) goto out; if ((ec = d2i_ECPrivateKey_bio(rawcert, NULL)) == NULL) goto out; if ((group = EC_KEY_get0_group(ec)) == NULL) goto out; switch (EC_GROUP_get_degree(group)) { case 256: method = IKEV2_AUTH_ECDSA_256; break; case 384: method = IKEV2_AUTH_ECDSA_384; break; case 521: method = IKEV2_AUTH_ECDSA_521; break; } } log_debug("%s: type %s method %s", __func__, print_map(privkey->id_type, ikev2_cert_map), print_map(method, ikev2_auth_map)); out: if (ec != NULL) EC_KEY_free(ec); if (rawcert != NULL) BIO_free(rawcert); return (method); } char * ca_asn1_name(uint8_t *asn1, size_t len) { X509_NAME *name = NULL; char *str = NULL; const uint8_t *p; p = asn1; if ((name = d2i_X509_NAME(NULL, &p, len)) == NULL) return (NULL); str = X509_NAME_oneline(name, NULL, 0); X509_NAME_free(name); return (str); } /* * Copy 'src' to 'dst' until 'marker' is found while unescaping '\' * characters. The return value tells the caller where to continue * parsing (might be the end of the string) or NULL on error. */ static char * ca_x509_name_unescape(char *src, char *dst, char marker) { while (*src) { if (*src == marker) { src++; break; } if (*src == '\\') { src++; if (!*src) { log_warnx("%s: '\\' at end of string", __func__); *dst = '\0'; return (NULL); } } *dst++ = *src++; } *dst = '\0'; return (src); } /* * Parse an X509 subject name where 'subject' is in the format * /type0=value0/type1=value1/type2=... * where characters may be escaped by '\'. * See lib/libssl/src/apps/apps.c:parse_name() */ void * ca_x509_name_parse(char *subject) { char *cp, *value = NULL, *type = NULL; size_t maxlen; X509_NAME *name = NULL; if (*subject != '/') { log_warnx("%s: leading '/' missing in '%s'", __func__, subject); goto err; } /* length of subject is upper bound for unescaped type/value */ maxlen = strlen(subject) + 1; if ((type = calloc(1, maxlen)) == NULL || (value = calloc(1, maxlen)) == NULL || (name = X509_NAME_new()) == NULL) goto err; cp = subject + 1; while (*cp) { /* unescape type, terminated by '=' */ cp = ca_x509_name_unescape(cp, type, '='); if (cp == NULL) { log_warnx("%s: could not parse type", __func__); goto err; } if (!*cp) { log_warnx("%s: missing value", __func__); goto err; } /* unescape value, terminated by '/' */ cp = ca_x509_name_unescape(cp, value, '/'); if (cp == NULL) { log_warnx("%s: could not parse value", __func__); goto err; } if (!*type || !*value) { log_warnx("%s: empty type or value", __func__); goto err; } log_debug("%s: setting '%s' to '%s'", __func__, type, value); if (!X509_NAME_add_entry_by_txt(name, type, MBSTRING_ASC, value, -1, -1, 0)) { log_warnx("%s: setting '%s' to '%s' failed", __func__, type, value); ca_sslerror(__func__); goto err; } } free(type); free(value); return (name); err: X509_NAME_free(name); free(type); free(value); return (NULL); } int ca_validate_pubkey(struct iked *env, struct iked_static_id *id, void *data, size_t len, struct iked_id *out) { BIO *rawcert = NULL; RSA *peerrsa = NULL, *localrsa = NULL; EC_KEY *peerec = NULL; EVP_PKEY *peerkey = NULL, *localkey = NULL; int ret = -1; FILE *fp = NULL; char idstr[IKED_ID_SIZE]; char file[PATH_MAX]; struct iked_id idp; switch (id->id_type) { case IKEV2_ID_IPV4: case IKEV2_ID_FQDN: case IKEV2_ID_UFQDN: case IKEV2_ID_IPV6: break; default: /* Some types like ASN1_DN will not be mapped to file names */ log_debug("%s: unsupported public key type %s", __func__, print_map(id->id_type, ikev2_id_map)); return (-1); } bzero(&idp, sizeof(idp)); if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL) goto done; idp.id_type = id->id_type; idp.id_offset = id->id_offset; if (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1) goto done; if (len == 0 && data) { /* Data is already an public key */ peerkey = (EVP_PKEY *)data; } if (len > 0) { if ((rawcert = BIO_new_mem_buf(data, len)) == NULL) goto done; if ((peerkey = EVP_PKEY_new()) == NULL) goto sslerr; if ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL))) { if (!EVP_PKEY_set1_RSA(peerkey, peerrsa)) { goto sslerr; } } else if (BIO_reset(rawcert) == 1 && (peerec = d2i_EC_PUBKEY_bio(rawcert, NULL))) { if (!EVP_PKEY_set1_EC_KEY(peerkey, peerec)) { goto sslerr; } } else { log_debug("%s: unknown key type received", __func__); goto sslerr; } } lc_idtype(idstr); if (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) || strlcat(file, idstr, sizeof(file)) >= sizeof(file)) { log_debug("%s: public key id too long %s", __func__, idstr); goto done; } if ((fp = fopen(file, "r")) == NULL) { /* Log to debug when called from ca_validate_cert */ logit(len == 0 ? LOG_DEBUG : LOG_INFO, "%s: could not open public key %s", __func__, file); goto done; } localkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (localkey == NULL) { /* reading PKCS #8 failed, try PEM RSA */ rewind(fp); localrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL); fclose(fp); if (localrsa == NULL) goto sslerr; if ((localkey = EVP_PKEY_new()) == NULL) goto sslerr; if (!EVP_PKEY_set1_RSA(localkey, localrsa)) goto sslerr; } else { fclose(fp); } if (localkey == NULL) goto sslerr; if (peerkey && EVP_PKEY_cmp(peerkey, localkey) != 1) { log_debug("%s: public key does not match %s", __func__, file); goto done; } log_debug("%s: valid public key in file %s", __func__, file); if (out && ca_pubkey_serialize(localkey, out)) goto done; ret = 0; sslerr: if (ret != 0) ca_sslerror(__func__); done: ibuf_release(idp.id_buf); if (localkey != NULL) EVP_PKEY_free(localkey); if (peerrsa != NULL) RSA_free(peerrsa); if (peerec != NULL) EC_KEY_free(peerec); if (localrsa != NULL) RSA_free(localrsa); if (rawcert != NULL) { BIO_free(rawcert); if (peerkey != NULL) EVP_PKEY_free(peerkey); } return (ret); } int ca_validate_cert(struct iked *env, struct iked_static_id *id, void *data, size_t len) { struct ca_store *store = env->sc_priv; X509_STORE_CTX csc; BIO *rawcert = NULL; X509 *cert = NULL; EVP_PKEY *pkey; int ret = -1, result, error; X509_NAME *subject; const char *errstr = "failed"; if (len == 0) { /* Data is already an X509 certificate */ cert = (X509 *)data; } else { /* Convert data to X509 certificate */ if ((rawcert = BIO_new_mem_buf(data, len)) == NULL) goto done; if ((cert = d2i_X509_bio(rawcert, NULL)) == NULL) goto done; } /* Certificate needs a valid subjectName */ if ((subject = X509_get_subject_name(cert)) == NULL) { errstr = "invalid subject"; goto done; } if (id != NULL) { if ((pkey = X509_get_pubkey(cert)) == NULL) { errstr = "no public key in cert"; goto done; } ret = ca_validate_pubkey(env, id, pkey, 0, NULL); EVP_PKEY_free(pkey); if (ret == 0) { errstr = "in public key file, ok"; goto done; } switch (id->id_type) { case IKEV2_ID_ASN1_DN: if (ca_x509_subject_cmp(cert, id) < 0) { errstr = "ASN1_DN identifier mismatch"; goto done; } break; default: if (ca_x509_subjectaltname_cmp(cert, id) != 0) { errstr = "invalid subjectAltName extension"; goto done; } break; } } bzero(&csc, sizeof(csc)); X509_STORE_CTX_init(&csc, store->ca_cas, cert, NULL); if (store->ca_cas->param->flags & X509_V_FLAG_CRL_CHECK) { X509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_flags(&csc, X509_V_FLAG_CRL_CHECK_ALL); } result = X509_verify_cert(&csc); error = csc.error; X509_STORE_CTX_cleanup(&csc); if (error != 0) { errstr = X509_verify_cert_error_string(error); goto done; } if (!result) { /* XXX should we accept self-signed certificates? */ errstr = "rejecting self-signed certificate"; goto done; } /* Success */ ret = 0; errstr = "ok"; done: if (cert != NULL) log_debug("%s: %s %.100s", __func__, cert->name, errstr); if (rawcert != NULL) { BIO_free(rawcert); if (cert != NULL) X509_free(cert); } return (ret); } /* check if subject from cert matches the id */ int ca_x509_subject_cmp(X509 *cert, struct iked_static_id *id) { X509_NAME *subject, *idname = NULL; const uint8_t *idptr; size_t idlen; int ret = -1; if (id->id_type != IKEV2_ID_ASN1_DN) return (-1); if ((subject = X509_get_subject_name(cert)) == NULL) return (-1); if (id->id_length <= id->id_offset) return (-1); idlen = id->id_length - id->id_offset; idptr = id->id_data + id->id_offset; if ((idname = d2i_X509_NAME(NULL, &idptr, idlen)) == NULL) return (-1); if (X509_NAME_cmp(subject, idname) == 0) ret = 0; X509_NAME_free(idname); return (ret); } #define MODE_ALT_LOG 1 #define MODE_ALT_GET 2 #define MODE_ALT_CMP 3 int ca_x509_subjectaltname_do(X509 *cert, int mode, const char *logmsg, struct iked_static_id *id, struct iked_id *retid) { STACK_OF(GENERAL_NAME) *stack = NULL; GENERAL_NAME *entry; ASN1_STRING *cstr; char idstr[IKED_ID_SIZE]; int idx, ret, i, type, len; uint8_t *data; ret = -1; idx = -1; while ((stack = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, &idx)) != NULL) { for (i = 0; i < sk_GENERAL_NAME_num(stack); i++) { entry = sk_GENERAL_NAME_value(stack, i); switch (entry->type) { case GEN_DNS: cstr = entry->d.dNSName; if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING) continue; type = IKEV2_ID_FQDN; break; case GEN_EMAIL: cstr = entry->d.rfc822Name; if (ASN1_STRING_type(cstr) != V_ASN1_IA5STRING) continue; type = IKEV2_ID_UFQDN; break; case GEN_IPADD: cstr = entry->d.iPAddress; switch (ASN1_STRING_length(cstr)) { case 4: type = IKEV2_ID_IPV4; break; case 16: type = IKEV2_ID_IPV6; break; default: log_debug("%s: invalid subjectAltName" " IP address", __func__); continue; } break; default: continue; } len = ASN1_STRING_length(cstr); data = ASN1_STRING_data(cstr); if (mode == MODE_ALT_LOG) { struct iked_id sanid; bzero(&sanid, sizeof(sanid)); sanid.id_offset = 0; sanid.id_type = type; if ((sanid.id_buf = ibuf_new(data, len)) == NULL) { log_debug("%s: failed to get id buffer", __func__); continue; } ikev2_print_id(&sanid, idstr, sizeof(idstr)); log_info("%s: altname: %s", logmsg, idstr); ibuf_release(sanid.id_buf); sanid.id_buf = NULL; } /* Compare length and data */ if (mode == MODE_ALT_CMP) { if (type == id->id_type && (len == (id->id_length - id->id_offset)) && (memcmp(id->id_data + id->id_offset, data, len)) == 0) { ret = 0; break; } } /* Get first ID */ if (mode == MODE_ALT_GET) { ibuf_release(retid->id_buf); if ((retid->id_buf = ibuf_new(data, len)) == NULL) { log_debug("%s: failed to get id buffer", __func__); ret = -2; break; } retid->id_offset = 0; ikev2_print_id(retid, idstr, sizeof(idstr)); log_debug("%s: %s", __func__, idstr); ret = 0; break; } } sk_GENERAL_NAME_pop_free(stack, GENERAL_NAME_free); if (ret != -1) break; } if (idx == -1) log_debug("%s: did not find subjectAltName in certificate", __func__); return ret; } int ca_x509_subjectaltname_log(X509 *cert, const char *logmsg) { return ca_x509_subjectaltname_do(cert, MODE_ALT_LOG, logmsg, NULL, NULL); } int ca_x509_subjectaltname_cmp(X509 *cert, struct iked_static_id *id) { return ca_x509_subjectaltname_do(cert, MODE_ALT_CMP, NULL, id, NULL); } int ca_x509_subjectaltname_get(X509 *cert, struct iked_id *retid) { return ca_x509_subjectaltname_do(cert, MODE_ALT_GET, NULL, NULL, retid); } void ca_sslinit(void) { OpenSSL_add_all_algorithms(); ERR_load_crypto_strings(); /* Init hardware crypto engines. */ ENGINE_load_builtin_engines(); ENGINE_register_all_complete(); } void ca_sslerror(const char *caller) { unsigned long error; while ((error = ERR_get_error()) != 0) log_warnx("%s: %s: %.100s", __func__, caller, ERR_error_string(error, NULL)); }
./CrossVul/dataset_final_sorted/CWE-639/c/good_4237_0
crossvul-cpp_data_bad_5229_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/ext/bcmath/bcmath.h" #include "hphp/runtime/base/ini-setting.h" #include <folly/ScopeGuard.h> namespace HPHP { /////////////////////////////////////////////////////////////////////////////// struct bcmath_data { bcmath_data() { // we can't really call bc_init_numbers() that calls into this constructor data._zero_ = _bc_new_num_ex (1,0,1); data._one_ = _bc_new_num_ex (1,0,1); data._one_->n_value[0] = 1; data._two_ = _bc_new_num_ex (1,0,1); data._two_->n_value[0] = 2; data.bc_precision = 0; } BCMathGlobals data; }; static IMPLEMENT_THREAD_LOCAL(bcmath_data, s_globals); /////////////////////////////////////////////////////////////////////////////// static void php_str2num(bc_num *num, const char *str) { const char *p; if (!(p = strchr(str, '.'))) { bc_str2num(num, (char*)str, 0); } else { bc_str2num(num, (char*)str, strlen(p + 1)); } } static bool HHVM_FUNCTION(bcscale, int64_t scale) { BCG(bc_precision) = scale < 0 ? 0 : scale; return true; } static String HHVM_FUNCTION(bcadd, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_add(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static String HHVM_FUNCTION(bcsub, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_sub(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static int64_t HHVM_FUNCTION(bccomp, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second; bc_init_num(&first); bc_init_num(&second); bc_str2num(&first, (char*)left.data(), scale); bc_str2num(&second, (char*)right.data(), scale); int64_t ret = bc_compare(first, second); bc_free_num(&first); bc_free_num(&second); return ret; } static String HHVM_FUNCTION(bcmul, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_multiply(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static Variant HHVM_FUNCTION(bcdiv, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); if (bc_divide(first, second, &result, scale) == -1) { raise_warning("Division by zero"); return init_null(); } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcmod, const String& left, const String& right) { bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); if (bc_modulo(first, second, &result, 0) == -1) { raise_warning("Division by zero"); return init_null(); } String ret(bc_num2str(result), AttachString); return ret; } static String HHVM_FUNCTION(bcpow, const String& left, const String& right, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_raise(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcpowmod, const String& left, const String& right, const String& modulus, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num first, second, mod, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&mod); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&mod); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); php_str2num(&mod, (char*)modulus.data()); if (bc_raisemod(first, second, mod, &result, scale) == -1) { return false; } if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcsqrt, const String& operand, int64_t scale /* = -1 */) { if (scale < 0) scale = BCG(bc_precision); bc_num result; bc_init_num(&result); SCOPE_EXIT { bc_free_num(&result); }; php_str2num(&result, (char*)operand.data()); Variant ret; if (bc_sqrt(&result, scale) != 0) { if (result->n_scale > scale) { result->n_scale = scale; } ret = String(bc_num2str(result), AttachString); } else { raise_warning("Square root of negative number"); } return ret; } /////////////////////////////////////////////////////////////////////////////// struct bcmathExtension final : Extension { bcmathExtension() : Extension("bcmath", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(bcscale); HHVM_FE(bcadd); HHVM_FE(bcsub); HHVM_FE(bccomp); HHVM_FE(bcmul); HHVM_FE(bcdiv); HHVM_FE(bcmod); HHVM_FE(bcpow); HHVM_FE(bcpowmod); HHVM_FE(bcsqrt); loadSystemlib(); } void threadInit() override { IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "bcmath.scale", "0", &BCG(bc_precision)); } } s_bcmath_extension; /////////////////////////////////////////////////////////////////////////////// extern "C" { struct BCMathGlobals *get_bcmath_globals() { return &HPHP::s_globals.get()->data; } } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_5229_0
crossvul-cpp_data_bad_5230_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/string-util.h" #include <algorithm> #include <vector> #include "hphp/zend/zend-html.h" #include "hphp/runtime/base/array-init.h" #include "hphp/util/bstring.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/container-functions.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // manipulations String StringUtil::Pad(const String& input, int final_length, const String& pad_string /* = " " */, PadType type /* = PadType::Right */) { int len = input.size(); return string_pad(input.data(), len, final_length, pad_string.data(), pad_string.size(), static_cast<int>(type)); } String StringUtil::StripHTMLTags(const String& input, const String& allowable_tags /* = "" */) { if (input.empty()) return input; return string_strip_tags(input.data(), input.size(), allowable_tags.data(), allowable_tags.size(), false); } /////////////////////////////////////////////////////////////////////////////// // splits/joins Variant StringUtil::Explode(const String& input, const String& delimiter, int limit /* = 0x7FFFFFFF */) { if (delimiter.empty()) { throw_invalid_argument("delimiter: (empty)"); return false; } Array ret(Array::Create()); if (input.empty()) { if (limit >= 0) { ret.append(""); } return ret; } if (limit > 1) { int pos = input.find(delimiter); if (pos < 0) { ret.append(input); } else { int len = delimiter.size(); int pos0 = 0; do { ret.append(input.substr(pos0, pos - pos0)); pos += len; pos0 = pos; } while ((pos = input.find(delimiter, pos)) >= 0 && --limit > 1); if (pos0 <= input.size()) { ret.append(input.substr(pos0)); } } } else if (limit < 0) { int pos = input.find(delimiter); if (pos >= 0) { std::vector<int> positions; int len = delimiter.size(); int pos0 = 0; int found = 0; do { positions.push_back(pos0); positions.push_back(pos - pos0); pos += len; pos0 = pos; found++; } while ((pos = input.find(delimiter, pos)) >= 0); if (pos0 <= input.size()) { positions.push_back(pos0); positions.push_back(input.size() - pos0); found++; } int iMax = (found + limit) << 1; for (int i = 0; i < iMax; i += 2) { ret.append(input.substr(positions[i], positions[i+1])); } } // else we have negative limit and delimiter not found } else { ret.append(input); } return ret; } String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector<String> sitems; sitems.reserve(size); int len = 0; int lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assert(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assert(p - buffer == len); s.setSize(len); return s; } Variant StringUtil::Split(const String& str, int64_t split_length /* = 1 */) { if (split_length <= 0) { throw_invalid_argument( "The length of each segment must be greater than zero" ); return false; } int len = str.size(); PackedArrayInit ret(len / split_length + 1, CheckAllocation{}); if (split_length >= len) { ret.append(str); } else { for (int i = 0; i < len; i += split_length) { ret.append(str.substr(i, split_length)); } } return ret.toArray(); } Variant StringUtil::ChunkSplit(const String& body, int chunklen /* = 76 */, const String& end /* = "\r\n" */) { if (chunklen <= 0) { throw_invalid_argument("chunklen: (non-positive)"); return false; } String ret; int len = body.size(); if (chunklen >= len) { ret = body; ret += end; } else { return string_chunk_split(body.data(), len, end.c_str(), end.size(), chunklen); } return ret; } /////////////////////////////////////////////////////////////////////////////// // encoding/decoding String StringUtil::HtmlEncode(const String& input, QuoteStyle quoteStyle, const char *charset, bool dEncode, bool htmlEnt) { return HtmlEncode(input, static_cast<int64_t>(quoteStyle), charset, dEncode, htmlEnt); } String StringUtil::HtmlEncode(const String& input, const int64_t qsBitmask, const char *charset, bool dEncode, bool htmlEnt) { if (input.empty()) return input; assert(charset); bool utf8 = true; if (strcasecmp(charset, "ISO-8859-1") == 0) { utf8 = false; } else if (strcasecmp(charset, "UTF-8")) { throw_not_implemented(charset); } int len = input.size(); char *ret = string_html_encode(input.data(), len, qsBitmask, utf8, dEncode, htmlEnt); if (!ret) { return empty_string(); } return String(ret, len, AttachString); } #define A1(v, ch) ((v)|((ch) & 64 ? 0 : 1uLL<<((ch)&63))) #define A2(v, ch) ((v)|((ch) & 64 ? 1uLL<<((ch)&63) : 0)) static const AsciiMap mapNoQuotes = { { A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@') } }; static const AsciiMap mapDoubleQuotes = { { A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"') } }; static const AsciiMap mapBothQuotes = { { A1(A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\''), A2(A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\'') } }; static const AsciiMap mapNothing = {}; String StringUtil::HtmlEncodeExtra(const String& input, QuoteStyle quoteStyle, const char *charset, bool nbsp, Array extra) { if (input.empty()) return input; assert(charset); int flags = STRING_HTML_ENCODE_UTF8; if (nbsp) { flags |= STRING_HTML_ENCODE_NBSP; } if (RuntimeOption::Utf8izeReplace) { flags |= STRING_HTML_ENCODE_UTF8IZE_REPLACE; } if (!*charset || strcasecmp(charset, "UTF-8") == 0) { } else if (strcasecmp(charset, "ISO-8859-1") == 0) { flags &= ~STRING_HTML_ENCODE_UTF8; } else { throw_not_implemented(charset); } const AsciiMap *am; AsciiMap tmp; switch (quoteStyle) { case QuoteStyle::FBUtf8Only: am = &mapNothing; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::FBUtf8: am = &mapBothQuotes; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::Both: am = &mapBothQuotes; break; case QuoteStyle::Double: am = &mapDoubleQuotes; break; case QuoteStyle::No: am = &mapNoQuotes; break; default: am = &mapNothing; raise_error("Unknown quote style: %d", (int)quoteStyle); } if (quoteStyle != QuoteStyle::FBUtf8Only && extra.toBoolean()) { tmp = *am; am = &tmp; for (ArrayIter iter(extra); iter; ++iter) { String item = iter.second().toString(); char c = item.data()[0]; tmp.map[c & 64 ? 1 : 0] |= 1uLL << (c & 63); } } int len = input.size(); char *ret = string_html_encode_extra(input.data(), len, (StringHtmlEncoding)flags, am); if (!ret) { raise_error("HtmlEncode called on too large input (%d)", len); } return String(ret, len, AttachString); } String StringUtil::HtmlDecode(const String& input, QuoteStyle quoteStyle, const char *charset, bool all) { if (input.empty()) return input; assert(charset); int len = input.size(); char *ret = string_html_decode(input.data(), len, quoteStyle != QuoteStyle::No, quoteStyle == QuoteStyle::Both, charset, all); if (!ret) { // null iff charset was not recognized throw_not_implemented(charset); // (charset is not null, see assertion above) } return String(ret, len, AttachString); } String StringUtil::QuotedPrintableEncode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_encode(input.data(), len); } String StringUtil::QuotedPrintableDecode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_decode(input.data(), len, false); } String StringUtil::UUEncode(const String& input) { if (input.empty()) return input; return string_uuencode(input.data(), input.size()); } String StringUtil::UUDecode(const String& input) { if (!input.empty()) { return string_uudecode(input.data(), input.size()); } return String(); } String StringUtil::Base64Encode(const String& input) { int len = input.size(); return string_base64_encode(input.data(), len); } String StringUtil::Base64Decode(const String& input, bool strict /* = false */) { int len = input.size(); return string_base64_decode(input.data(), len, strict); } String StringUtil::UrlEncode(const String& input, bool encodePlus /* = true */) { return encodePlus ? url_encode(input.data(), input.size()) : url_raw_encode(input.data(), input.size()); } String StringUtil::UrlDecode(const String& input, bool decodePlus /* = true */) { return decodePlus ? url_decode(input.data(), input.size()) : url_raw_decode(input.data(), input.size()); } bool StringUtil::IsFileUrl(const String& input) { return string_strncasecmp( input.data(), input.size(), "file://", sizeof("file://") - 1, sizeof("file://") - 1) == 0; } String StringUtil::DecodeFileUrl(const String& input) { Url url; if (!url_parse(url, input.data(), input.size())) { return null_string; } if (bstrcasecmp(url.scheme.data(), url.scheme.size(), "file", sizeof("file")-1) != 0) { // Not file scheme return null_string; } if (url.host.size() > 0 && bstrcasecmp(url.host.data(), url.host.size(), "localhost", sizeof("localhost")-1) != 0) { // Not localhost or empty host return null_string; } return url_raw_decode(url.path.data(), url.path.size()); } /////////////////////////////////////////////////////////////////////////////// // formatting String StringUtil::MoneyFormat(const char *format, double value) { assert(format); return string_money_format(format, value); } /////////////////////////////////////////////////////////////////////////////// // hashing String StringUtil::Translate(const String& input, const String& from, const String& to) { if (input.empty()) return input; int len = input.size(); String retstr(len, ReserveString); char *ret = retstr.mutableData(); memcpy(ret, input.data(), len); auto trlen = std::min(from.size(), to.size()); string_translate(ret, len, from.data(), to.data(), trlen); retstr.setSize(len); return retstr; } String StringUtil::ROT13(const String& input) { if (input.empty()) return input; return String(string_rot13(input.data(), input.size()), input.size(), AttachString); } int64_t StringUtil::CRC32(const String& input) { return string_crc32(input.data(), input.size()); } String StringUtil::Crypt(const String& input, const char *salt /* = "" */) { if (salt && salt[0] == '\0') { raise_notice("crypt(): No salt parameter was specified." " You must use a randomly generated salt and a strong" " hash function to produce a secure hash."); } return String(string_crypt(input.c_str(), salt), AttachString); } String StringUtil::MD5(const char *data, uint32_t size, bool raw /* = false */) { Md5Digest md5(data, size); auto const rawLen = sizeof(md5.digest); if (raw) return String((char*)md5.digest, rawLen, CopyString); auto const hexLen = rawLen * 2; String hex(hexLen, ReserveString); string_bin2hex((char*)md5.digest, rawLen, hex.mutableData()); hex.setSize(hexLen); return hex; } String StringUtil::MD5(const String& input, bool raw /* = false */) { return MD5(input.data(), input.length(), raw); } String StringUtil::SHA1(const String& input, bool raw /* = false */) { int len; char *ret = string_sha1(input.data(), input.size(), raw, len); return String(ret, len, AttachString); } /////////////////////////////////////////////////////////////////////////////// // integer safety for string allocations size_t safe_address(size_t nmemb, size_t size, size_t offset) { uint64_t result = (uint64_t) nmemb * (uint64_t) size + (uint64_t) offset; if (UNLIKELY(result > StringData::MaxSize)) { throw FatalErrorException(0, "String length exceeded 2^31-2: %" PRIu64, result); } return result; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_5230_0
crossvul-cpp_data_bad_291_0
/********************************************************************** * Log: * 2006-03-12: Parts originally authored by Doug Madory as wifi_parser.c * 2013-03-15: Substantially modified by Simson Garfinkel for inclusion into tcpflow * 2013-11-18: reworked static calls to be entirely calls to a class. Changed TimeVal pointer to an instance variable that includes the full packet header. **********************************************************************/ //*do 11-18 #include "config.h" // pull in HAVE_ defines #define __STDC_FORMAT_MACROS #include <stdint.h> #include <inttypes.h> #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <stdarg.h> #include <errno.h> #ifdef HAVE_NET_ETHERNET_H #include <net/ethernet.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #pragma GCC diagnostic ignored "-Wcast-align" #include "wifipcap.h" #include "cpack.h" #include "extract.h" #include "oui.h" #include "ethertype.h" #include "icmp.h" #include "ipproto.h" /* wifipcap uses a MAC class which is somewhat lame, but works */ MAC MAC::broadcast(0xffffffffffffULL); MAC MAC::null((uint64_t)0); int WifiPacket::debug=0; int MAC::print_fmt(MAC::PRINT_FMT_COLON); std::ostream& operator<<(std::ostream& out, const MAC& mac) { const char *fmt = MAC::print_fmt == MAC::PRINT_FMT_COLON ? "%02x:%02x:%02x:%02x:%02x:%02x" : "%02x%02x%02x%02x%02x%02x"; char buf[24]; sprintf(buf, fmt, (int)((mac.val>>40)&0xff), (int)((mac.val>>32)&0xff), (int)((mac.val>>24)&0xff), (int)((mac.val>>16)&0xff), (int)((mac.val>>8)&0xff), (int)((mac.val)&0xff) ); out << buf; return out; } std::ostream& operator<<(std::ostream& out, const struct in_addr& ip) { out << inet_ntoa(ip); return out; } struct tok { int v; /* value */ const char *s; /* string */ }; #if 0 static const struct tok ethertype_values[] = { { ETHERTYPE_IP, "IPv4" }, { ETHERTYPE_MPLS, "MPLS unicast" }, { ETHERTYPE_MPLS_MULTI, "MPLS multicast" }, { ETHERTYPE_IPV6, "IPv6" }, { ETHERTYPE_8021Q, "802.1Q" }, { ETHERTYPE_VMAN, "VMAN" }, { ETHERTYPE_PUP, "PUP" }, { ETHERTYPE_ARP, "ARP"}, { ETHERTYPE_REVARP, "Reverse ARP"}, { ETHERTYPE_NS, "NS" }, { ETHERTYPE_SPRITE, "Sprite" }, { ETHERTYPE_TRAIL, "Trail" }, { ETHERTYPE_MOPDL, "MOP DL" }, { ETHERTYPE_MOPRC, "MOP RC" }, { ETHERTYPE_DN, "DN" }, { ETHERTYPE_LAT, "LAT" }, { ETHERTYPE_SCA, "SCA" }, { ETHERTYPE_LANBRIDGE, "Lanbridge" }, { ETHERTYPE_DECDNS, "DEC DNS" }, { ETHERTYPE_DECDTS, "DEC DTS" }, { ETHERTYPE_VEXP, "VEXP" }, { ETHERTYPE_VPROD, "VPROD" }, { ETHERTYPE_ATALK, "Appletalk" }, { ETHERTYPE_AARP, "Appletalk ARP" }, { ETHERTYPE_IPX, "IPX" }, { ETHERTYPE_PPP, "PPP" }, { ETHERTYPE_SLOW, "Slow Protocols" }, { ETHERTYPE_PPPOED, "PPPoE D" }, { ETHERTYPE_PPPOES, "PPPoE S" }, { ETHERTYPE_EAPOL, "EAPOL" }, { ETHERTYPE_JUMBO, "Jumbo" }, { ETHERTYPE_LOOPBACK, "Loopback" }, { ETHERTYPE_ISO, "OSI" }, { ETHERTYPE_GRE_ISO, "GRE-OSI" }, { 0, NULL} }; #endif /*max length of an IEEE 802.11 packet*/ #ifndef MAX_LEN_80211 #define MAX_LEN_80211 3000 #endif /* from ethereal packet-prism.c */ #define pletohs(p) ((u_int16_t) \ ((u_int16_t)*((const u_int8_t *)(p)+1)<<8| \ (u_int16_t)*((const u_int8_t *)(p)+0)<<0)) #define pntohl(p) ((u_int32_t)*((const u_int8_t *)(p)+0)<<24| \ (u_int32_t)*((const u_int8_t *)(p)+1)<<16| \ (u_int32_t)*((const u_int8_t *)(p)+2)<<8| \ (u_int32_t)*((const u_int8_t *)(p)+3)<<0) #define COOK_FRAGMENT_NUMBER(x) ((x) & 0x000F) #define COOK_SEQUENCE_NUMBER(x) (((x) & 0xFFF0) >> 4) /* end ethereal code */ /* Sequence number gap */ #define SEQ_GAP(current, last)(0xfff & (current - last)) /* In the following three arrays, even though the QoS subtypes are listed, in the rest of the program * the QoS subtypes are treated as "OTHER_TYPES". The file "ieee802_11.h" currently doesn't account for * the existence of QoS subtypes. The QoS subtypes might need to be accomodated there in the future. */ #if 0 static const char * mgmt_subtype_text[] = { "AssocReq", "AssocResp", "ReAssocReq", "ReAssocResp", "ProbeReq", "ProbeResp", "", "", "Beacon", "ATIM", "Disassoc", "Auth", "DeAuth", "Action", /*QoS mgmt_subtype*/ "", "" }; static const char * ctrl_subtype_text[] = { "", "", "", "", "", "", "", "", "BlockAckReq", /*QoS ctrl_subtype*/ "BlockAck", /*QoS ctrl_subtype*/ "PS-Poll", "RTS", "CTS", "ACK", "CF-End", "CF-End+CF-Ack" }; static const char * data_subtype_text[] = { "Data", "Data+CF-Ack", "Data+CF-Poll", "Data+CF-Ack+CF-Poll", "Null(no_data)", "CF-Ack(no_data)", "CF-Poll(no_data)", "CF-Ack+CF-Poll(no_data)", "QoS_Data", /*QoS data_subtypes from here on*/ "QoS_Data+CF-Ack", "QoS_Data+CF-Poll", "QoS_Data+CF-Ack+CF-Poll", "QoS_Null(no_data)", "", "QoS_CF-Poll(no_data)", "QoS_CF-Ack+CF-Poll(no_data)" }; #endif /////////////////////////////////////////////////////////////////////////////// // crc32 implementation needed for wifi checksum /* crc32.c * CRC-32 routine * * $Id: crc32.cpp,v 1.1 2007/02/14 00:05:50 jpang Exp $ * * Ethereal - Network traffic analyzer * By Gerald Combs <gerald@ethereal.com> * Copyright 1998 Gerald Combs * * Copied from README.developer * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Credits: * * Table from Solomon Peachy * Routine from Chris Waters */ /* * Table for the AUTODIN/HDLC/802.x CRC. * * Polynomial is * * x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^8 + x^7 + * x^5 + x^4 + x^2 + x + 1 */ static const uint32_t crc32_ccitt_table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; #define CRC32_CCITT_SEED 0xFFFFFFFF static uint32_t crc32_ccitt_seed(const uint8_t *buf, size_t len, uint32_t seed); static uint32_t crc32_ccitt(const uint8_t *buf, size_t len) { return ( crc32_ccitt_seed(buf, len, CRC32_CCITT_SEED) ); } static uint32_t crc32_ccitt_seed(const uint8_t *buf, size_t len, uint32_t seed) { uint32_t crc32 = seed; for (unsigned int i = 0; i < len; i++){ crc32 = crc32_ccitt_table[(crc32 ^ buf[i]) & 0xff] ^ (crc32 >> 8); } return ( ~crc32 ); } /* * IEEE 802.x version (Ethernet and 802.11, at least) - byte-swap * the result of "crc32()". * * XXX - does this mean we should fetch the Ethernet and 802.11 * Frame Checksum (FCS) with "tvb_get_letohl()" rather than "tvb_get_ntohl()", * or is fetching it big-endian and byte-swapping the CRC done * to cope with 802.x sending stuff out in reverse bit order? */ static uint32_t crc32_802(const unsigned char *buf, size_t len) { uint32_t c_crc; c_crc = crc32_ccitt(buf, len); /* Byte reverse. */ c_crc = ((unsigned char)(c_crc>>0)<<24) | ((unsigned char)(c_crc>>8)<<16) | ((unsigned char)(c_crc>>16)<<8) | ((unsigned char)(c_crc>>24)<<0); return ( c_crc ); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /* Translate Ethernet address, as seen in struct ether_header, to type MAC. */ /* Extract header length. */ static size_t extract_header_length(u_int16_t fc) { switch (FC_TYPE(fc)) { case T_MGMT: return MGMT_HDRLEN; case T_CTRL: switch (FC_SUBTYPE(fc)) { case CTRL_PS_POLL: return CTRL_PS_POLL_HDRLEN; case CTRL_RTS: return CTRL_RTS_HDRLEN; case CTRL_CTS: return CTRL_CTS_HDRLEN; case CTRL_ACK: return CTRL_ACK_HDRLEN; case CTRL_CF_END: return CTRL_END_HDRLEN; case CTRL_END_ACK: return CTRL_END_ACK_HDRLEN; default: return 0; } case T_DATA: return (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24; default: return 0; } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #pragma GCC diagnostic ignored "-Wcast-align" void WifiPacket::handle_llc(const mac_hdr_t &mac,const u_char *ptr, size_t len,u_int16_t fc) { if (len < 7) { // truncated header! cbs->HandleLLC(*this,NULL, ptr, len); return; } // http://www.wildpackets.com/resources/compendium/wireless_lan/wlan_packets llc_hdr_t hdr; hdr.dsap = EXTRACT_LE_8BITS(ptr); // Destination Service Access point hdr.ssap = EXTRACT_LE_8BITS(ptr + 1); // Source Service Access Point hdr.control= EXTRACT_LE_8BITS(ptr + 2); // ignored by most protocols hdr.oui = EXTRACT_24BITS(ptr + 3); hdr.type = EXTRACT_16BITS(ptr + 6); /* "When both the DSAP and SSAP are set to 0xAA, the type is * interpreted as a protocol not defined by IEEE and the LSAP is * referred to as SubNetwork Access Protocol (SNAP). In SNAP, the * 5 bytes that follow the DSAP, SSAP, and control byte are called * the Protocol Discriminator." */ if(hdr.dsap==0xAA && hdr.ssap==0xAA){ cbs->HandleLLC(*this,&hdr,ptr+8,len-8); return; } if (hdr.oui == OUI_ENCAP_ETHER || hdr.oui == OUI_CISCO_90) { cbs->HandleLLC(*this,&hdr, ptr+8, len-8); return; } cbs->HandleLLCUnknown(*this,ptr, len); } void WifiPacket::handle_wep(const u_char *ptr, size_t len) { // Jeff: XXX handle TKIP/CCMP ? how can we demultiplex different // protection protocols? struct wep_hdr_t hdr; u_int32_t iv; if (len < IEEE802_11_IV_LEN + IEEE802_11_KID_LEN) { // truncated! cbs->HandleWEP(*this,NULL, ptr, len); return; } iv = EXTRACT_LE_32BITS(ptr); hdr.iv = IV_IV(iv); hdr.pad = IV_PAD(iv); hdr.keyid = IV_KEYID(iv); cbs->HandleWEP(*this,&hdr, ptr, len); } /////////////////////////////////////////////////////////////////////////////// static const char *auth_alg_text[]={"Open System","Shared Key","EAP"}; #define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0]) static const char *status_text[] = { "Succesful", /* 0 */ "Unspecified failure", /* 1 */ "Reserved", /* 2 */ "Reserved", /* 3 */ "Reserved", /* 4 */ "Reserved", /* 5 */ "Reserved", /* 6 */ "Reserved", /* 7 */ "Reserved", /* 8 */ "Reserved", /* 9 */ "Cannot Support all requested capabilities in the Capability Information field", /* 10 */ "Reassociation denied due to inability to confirm that association exists", /* 11 */ "Association denied due to reason outside the scope of the standard", /* 12 */ "Responding station does not support the specified authentication algorithm ", /* 13 */ "Received an Authentication frame with authentication transaction " \ "sequence number out of expected sequence", /* 14 */ "Authentication rejected because of challenge failure", /* 15 */ "Authentication rejected due to timeout waiting for next frame in sequence", /* 16 */ "Association denied because AP is unable to handle additional associated stations", /* 17 */ "Association denied due to requesting station not supporting all of the " \ "data rates in BSSBasicRateSet parameter", /* 18 */ }; #define NUM_STATUSES (sizeof status_text / sizeof status_text[0]) static const char *reason_text[] = { "Reserved", /* 0 */ "Unspecified reason", /* 1 */ "Previous authentication no longer valid", /* 2 */ "Deauthenticated because sending station is leaving (or has left) IBSS or ESS", /* 3 */ "Disassociated due to inactivity", /* 4 */ "Disassociated because AP is unable to handle all currently associated stations", /* 5 */ "Class 2 frame received from nonauthenticated station", /* 6 */ "Class 3 frame received from nonassociated station", /* 7 */ "Disassociated because sending station is leaving (or has left) BSS", /* 8 */ "Station requesting (re)association is not authenticated with responding station", /* 9 */ }; #define NUM_REASONS (sizeof reason_text / sizeof reason_text[0]) const char *Wifipcap::WifiUtil::MgmtAuthAlg2Txt(uint v) { return v < NUM_AUTH_ALGS ? auth_alg_text[v] : "Unknown"; } const char *Wifipcap::WifiUtil::MgmtStatusCode2Txt(uint v) { return v < NUM_STATUSES ? status_text[v] : "Reserved"; } const char *Wifipcap::WifiUtil::MgmtReasonCode2Txt(uint v) { return v < NUM_REASONS ? reason_text[v] : "Reserved"; } /////////////////////////////////////////////////////////////////////////////// // Jeff: HACK -- tcpdump uses a global variable to check truncation #define TTEST2(_p, _l) ((const u_char *)&(_p) - p + (_l) <= (ssize_t)len) void WifiPacket::parse_elements(struct mgmt_body_t *pbody, const u_char *p, int offset, size_t len) { /* * We haven't seen any elements yet. */ pbody->challenge_status = NOT_PRESENT; pbody->ssid_status = NOT_PRESENT; pbody->rates_status = NOT_PRESENT; pbody->ds_status = NOT_PRESENT; pbody->cf_status = NOT_PRESENT; pbody->tim_status = NOT_PRESENT; for (;;) { if (!TTEST2(*(p + offset), 1)) return; switch (*(p + offset)) { case E_SSID: /* Present, possibly truncated */ pbody->ssid_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->ssid, p + offset, 2); offset += 2; if (pbody->ssid.length != 0) { if (pbody->ssid.length > sizeof(pbody->ssid.ssid) - 1) return; if (!TTEST2(*(p + offset), pbody->ssid.length)) return; memcpy(&pbody->ssid.ssid, p + offset, pbody->ssid.length); offset += pbody->ssid.length; } pbody->ssid.ssid[pbody->ssid.length] = '\0'; /* Present and not truncated */ pbody->ssid_status = PRESENT; break; case E_CHALLENGE: /* Present, possibly truncated */ pbody->challenge_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->challenge, p + offset, 2); offset += 2; if (pbody->challenge.length != 0) { if (pbody->challenge.length > sizeof(pbody->challenge.text) - 1) return; if (!TTEST2(*(p + offset), pbody->challenge.length)) return; memcpy(&pbody->challenge.text, p + offset, pbody->challenge.length); offset += pbody->challenge.length; } pbody->challenge.text[pbody->challenge.length] = '\0'; /* Present and not truncated */ pbody->challenge_status = PRESENT; break; case E_RATES: /* Present, possibly truncated */ pbody->rates_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&(pbody->rates), p + offset, 2); offset += 2; if (pbody->rates.length != 0) { if (pbody->rates.length > sizeof pbody->rates.rate) return; if (!TTEST2(*(p + offset), pbody->rates.length)) return; memcpy(&pbody->rates.rate, p + offset, pbody->rates.length); offset += pbody->rates.length; } /* Present and not truncated */ pbody->rates_status = PRESENT; break; case E_DS: /* Present, possibly truncated */ pbody->ds_status = TRUNCATED; if (!TTEST2(*(p + offset), 3)) return; memcpy(&pbody->ds, p + offset, 3); offset += 3; /* Present and not truncated */ pbody->ds_status = PRESENT; break; case E_CF: /* Present, possibly truncated */ pbody->cf_status = TRUNCATED; if (!TTEST2(*(p + offset), 8)) return; memcpy(&pbody->cf, p + offset, 8); offset += 8; /* Present and not truncated */ pbody->cf_status = PRESENT; break; case E_TIM: /* Present, possibly truncated */ pbody->tim_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->tim, p + offset, 2); offset += 2; if (!TTEST2(*(p + offset), 3)) return; memcpy(&pbody->tim.count, p + offset, 3); offset += 3; if (pbody->tim.length <= 3) break; if (pbody->rates.length > sizeof pbody->tim.bitmap) return; if (!TTEST2(*(p + offset), pbody->tim.length - 3)) return; memcpy(pbody->tim.bitmap, p + (pbody->tim.length - 3), (pbody->tim.length - 3)); offset += pbody->tim.length - 3; /* Present and not truncated */ pbody->tim_status = PRESENT; break; default: #ifdef DEBUG_WIFI printf("(1) unhandled element_id (%d) ", *(p + offset) ); #endif if (!TTEST2(*(p + offset), 2)) return; if (!TTEST2(*(p + offset + 2), *(p + offset + 1))) return; offset += *(p + offset + 1) + 2; break; } } } /********************************************************************************* * Print Handle functions for the management frame types *********************************************************************************/ int WifiPacket::handle_beacon( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); printf(" %s", CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS"); PRINT_DS_CHANNEL(pbody); */ cbs->Handle80211MgmtBeacon(*this, pmh, &pbody); return 1; } int WifiPacket::handle_assoc_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); */ cbs->Handle80211MgmtAssocRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_assoc_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len, bool reassoc) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.status_code = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_STATUS_LEN; pbody.aid = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_AID_LEN; parse_elements(&pbody, p, offset, len); /* printf(" AID(%x) :%s: %s", ((u_int16_t)(pbody.aid << 2 )) >> 2 , CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "", (pbody.status_code < NUM_STATUSES ? status_text[pbody.status_code] : "n/a")); */ if (!reassoc) cbs->Handle80211MgmtAssocResponse(*this, pmh, &pbody); else cbs->Handle80211MgmtReassocResponse(*this, pmh, &pbody); return 1; } int WifiPacket::handle_reassoc_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN); offset += IEEE802_11_AP_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); printf(" AP : %s", etheraddr_string( pbody.ap )); */ cbs->Handle80211MgmtReassocRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_reassoc_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { /* Same as a Association Reponse */ return handle_assoc_response(pmh, p, len, true); } int WifiPacket::handle_probe_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); */ cbs->Handle80211MgmtProbeRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_probe_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); PRINT_DS_CHANNEL(pbody); */ cbs->Handle80211MgmtProbeResponse(*this, pmh, &pbody); return 1; } int WifiPacket::handle_atim( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { /* the frame body for ATIM is null. */ cbs->Handle80211MgmtATIM(*this, pmh); return 1; } int WifiPacket::handle_disassoc( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); /* printf(": %s", (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved" ); */ cbs->Handle80211MgmtDisassoc(*this, pmh, &pbody); return 1; } int WifiPacket::handle_auth( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, 6)) return 0; pbody.auth_alg = EXTRACT_LE_16BITS(p); offset += 2; pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset); offset += 2; pbody.status_code = EXTRACT_LE_16BITS(p + offset); offset += 2; parse_elements(&pbody, p, offset, len); /* if ((pbody.auth_alg == 1) && ((pbody.auth_trans_seq_num == 2) || (pbody.auth_trans_seq_num == 3))) { printf(" (%s)-%x [Challenge Text] %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, ((pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : "")); return 1; } printf(" (%s)-%x: %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, (pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : ""); */ cbs->Handle80211MgmtAuth(*this, pmh, &pbody); return 1; } int WifiPacket::handle_deauth( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; //const char *reason = NULL; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); offset += IEEE802_11_REASON_LEN; /* reason = (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved"; if (eflag) { printf(": %s", reason); } else { printf(" (%s): %s", etheraddr_string(pmh->sa), reason); } */ cbs->Handle80211MgmtDeauth(*this, pmh, &pbody); return 1; } /********************************************************************************* * Print Body funcs *********************************************************************************/ /** Decode a management request. * @return 0 - failure, non-zero success * * NOTE — this function and all that it calls should be handled as methods in WifipcapCallbacks */ int WifiPacket::decode_mgmt_body(u_int16_t fc, struct mgmt_header_t *pmh, const u_char *p, size_t len) { if(debug) std::cerr << "decode_mgmt_body FC_SUBTYPE(fc)="<<(int)FC_SUBTYPE(fc)<<" "; switch (FC_SUBTYPE(fc)) { case ST_ASSOC_REQUEST: return handle_assoc_request(pmh, p, len); case ST_ASSOC_RESPONSE: return handle_assoc_response(pmh, p, len); case ST_REASSOC_REQUEST: return handle_reassoc_request(pmh, p, len); case ST_REASSOC_RESPONSE: return handle_reassoc_response(pmh, p, len); case ST_PROBE_REQUEST: return handle_probe_request(pmh, p, len); case ST_PROBE_RESPONSE: return handle_probe_response(pmh, p, len); case ST_BEACON: return handle_beacon(pmh, p, len); case ST_ATIM: return handle_atim(pmh, p, len); case ST_DISASSOC: return handle_disassoc(pmh, p, len); case ST_AUTH: if (len < 3) { return 0; } if ((p[0] == 0 ) && (p[1] == 0) && (p[2] == 0)) { //printf("Authentication (Shared-Key)-3 "); cbs->Handle80211MgmtAuthSharedKey(*this, pmh, p, len); return 0; } return handle_auth(pmh, p, len); case ST_DEAUTH: return handle_deauth(pmh, p, len); break; default: return 0; } } int WifiPacket::decode_mgmt_frame(const u_char * ptr, size_t len, u_int16_t fc, u_int8_t hdrlen) { mgmt_header_t hdr; u_int16_t seq_ctl; hdr.da = MAC::ether2MAC(ptr + 4); hdr.sa = MAC::ether2MAC(ptr + 10); hdr.bssid = MAC::ether2MAC(ptr + 16); hdr.duration = EXTRACT_LE_16BITS(ptr+2); seq_ctl = pletohs(ptr + 22); hdr.seq = COOK_SEQUENCE_NUMBER(seq_ctl); hdr.frag = COOK_FRAGMENT_NUMBER(seq_ctl); cbs->Handle80211(*this, fc, hdr.sa, hdr.da, MAC::null, MAC::null, ptr, len); int ret = decode_mgmt_body(fc, &hdr, ptr+MGMT_HDRLEN, len-MGMT_HDRLEN); if (ret==0) { cbs->Handle80211Unknown(*this, fc, ptr, len); return 0; } return 0; } int WifiPacket::decode_data_frame(const u_char * ptr, size_t len, u_int16_t fc) { mac_hdr_t hdr; hdr.fc = fc; hdr.duration = EXTRACT_LE_16BITS(ptr+2); hdr.seq_ctl = pletohs(ptr + 22); hdr.seq = COOK_SEQUENCE_NUMBER(hdr.seq_ctl); hdr.frag = COOK_FRAGMENT_NUMBER(hdr.seq_ctl); if(FC_TYPE(fc)==2 && FC_SUBTYPE(fc)==8){ // quality of service? hdr.qos = 1; } size_t hdrlen=0; const MAC address1 = MAC::ether2MAC(ptr+4); const MAC address2 = MAC::ether2MAC(ptr+10); const MAC address3 = MAC::ether2MAC(ptr+16); /* call the 80211 callback data callback */ if (FC_TO_DS(fc)==0 && FC_FROM_DS(fc)==0) { /* ad hoc IBSS */ hdr.da = address1; hdr.sa = address2; hdr.bssid = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataIBSS( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc)==0 && FC_FROM_DS(fc)) { /* from AP to STA */ hdr.da = address1; hdr.bssid = address2; hdr.sa = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataFromAP( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)==0) { /* frame from STA to AP */ hdr.bssid = address1; hdr.sa = address2; hdr.da = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataToAP( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) { /* WDS */ const MAC address4 = MAC::ether2MAC(ptr+18); hdr.ra = address1; hdr.ta = address2; hdr.da = address3; hdr.sa = address4; hdrlen = DATA_WDS_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataWDS( *this, hdr, ptr+hdrlen, len-hdrlen); } /* Handle either the WEP or the link layer. This handles the data itself */ if (FC_WEP(fc)) { handle_wep(ptr+hdrlen, len-hdrlen-4 ); } else { handle_llc(hdr, ptr+hdrlen, len-hdrlen-4, fc); } return 0; } int WifiPacket::decode_ctrl_frame(const u_char * ptr, size_t len, u_int16_t fc) { u_int16_t du = EXTRACT_LE_16BITS(ptr+2); //duration switch (FC_SUBTYPE(fc)) { case CTRL_PS_POLL: { ctrl_ps_poll_t hdr; hdr.fc = fc; hdr.aid = du; hdr.bssid = MAC::ether2MAC(ptr+4); hdr.ta = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, hdr.ta, ptr, len); cbs->Handle80211CtrlPSPoll( *this, &hdr); break; } case CTRL_RTS: { ctrl_rts_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.ta = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211CtrlRTS( *this, &hdr); break; } case CTRL_CTS: { ctrl_cts_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlCTS( *this, &hdr); break; } case CTRL_ACK: { ctrl_ack_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlAck( *this, &hdr); break; } case CTRL_CF_END: { ctrl_end_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.bssid = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlCFEnd( *this, &hdr); break; } case CTRL_END_ACK: { ctrl_end_ack_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.bssid = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlEndAck( *this, &hdr); break; } default: { cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, MAC::null, ptr, len); cbs->Handle80211Unknown( *this, fc, ptr, len); return -1; //add the case statements for QoS control frames once ieee802_11.h is updated } } return 0; } #ifndef roundup2 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #endif void WifiPacket::handle_80211(const u_char * pkt, size_t len /* , int pad */) { if (debug) std::cerr << "handle_80211(len= " << len << " "; if (len < 2) { cbs->Handle80211( *this, 0, MAC::null, MAC::null, MAC::null, MAC::null, pkt, len); cbs->Handle80211Unknown( *this, -1, pkt, len); return; } u_int16_t fc = EXTRACT_LE_16BITS(pkt); //frame control size_t hdrlen = extract_header_length(fc); /* if (pad) { hdrlen = roundup2(hdrlen, 4); } */ if (debug) std::cerr << "FC_TYPE(fc)= " << FC_TYPE(fc) << " "; if (len < IEEE802_11_FC_LEN || len < hdrlen) { cbs->Handle80211Unknown( *this, fc, pkt, len); return; } /* Always calculate the frame checksum, but only process the packets if the FCS or if we are ignoring it */ if (len >= hdrlen + 4) { // assume fcs is last 4 bytes (?) u_int32_t fcs_sent = EXTRACT_32BITS(pkt+len-4); u_int32_t fcs = crc32_802(pkt, len-4); /* if (fcs != fcs_sent) { cerr << "bad fcs: "; fprintf (stderr, "%08x != %08x\n", fcs_sent, fcs); } */ fcs_ok = (fcs == fcs_sent); } if (cbs->Check80211FCS(*this) && fcs_ok==false){ cbs->Handle80211Unknown(*this,fc,pkt,len); return; } // fill in current_frame: type, sn switch (FC_TYPE(fc)) { case T_MGMT: if(decode_mgmt_frame(pkt, len, fc, hdrlen)<0) return; break; case T_DATA: if(decode_data_frame(pkt, len, fc)<0) return; break; case T_CTRL: if(decode_ctrl_frame(pkt, len, fc)<0) return; break; default: cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, MAC::null, pkt, len); cbs->Handle80211Unknown( *this, fc, pkt, len); return; } } int WifiPacket::print_radiotap_field(struct cpack_state *s, u_int32_t bit, int *pad, radiotap_hdr *hdr) { union { int8_t i8; u_int8_t u8; int16_t i16; u_int16_t u16; u_int32_t u32; u_int64_t u64; } u, u2, u3; int rc; switch (bit) { case IEEE80211_RADIOTAP_FLAGS: rc = cpack_uint8(s, &u.u8); if (u.u8 & IEEE80211_RADIOTAP_F_DATAPAD) *pad = 1; break; case IEEE80211_RADIOTAP_RATE: case IEEE80211_RADIOTAP_DB_ANTSIGNAL: case IEEE80211_RADIOTAP_DB_ANTNOISE: case IEEE80211_RADIOTAP_ANTENNA: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: case IEEE80211_RADIOTAP_DBM_ANTNOISE: rc = cpack_int8(s, &u.i8); break; case IEEE80211_RADIOTAP_CHANNEL: rc = cpack_uint16(s, &u.u16); if (rc != 0) break; rc = cpack_uint16(s, &u2.u16); break; case IEEE80211_RADIOTAP_FHSS: case IEEE80211_RADIOTAP_LOCK_QUALITY: case IEEE80211_RADIOTAP_TX_ATTENUATION: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DBM_TX_POWER: rc = cpack_int8(s, &u.i8); break; case IEEE80211_RADIOTAP_TSFT: rc = cpack_uint64(s, &u.u64); break; case IEEE80211_RADIOTAP_RX_FLAGS: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_TX_FLAGS: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_RTS_RETRIES: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DATA_RETRIES: rc = cpack_uint8(s, &u.u8); break; // simson add follows: case IEEE80211_RADIOTAP_XCHANNEL: rc = cpack_uint8(s, &u.u8); // simson guess break; case IEEE80211_RADIOTAP_MCS: rc = cpack_uint8(s, &u.u8) || cpack_uint8(s, &u2.u8) || cpack_uint8(s, &u3.u8); // simson guess break; // simson end default: /* this bit indicates a field whose * size we do not know, so we cannot * proceed. */ //printf("[0x%08x] ", bit); fprintf(stderr, "wifipcap: unknown radiotap bit: %d (%d)\n", bit,IEEE80211_RADIOTAP_XCHANNEL); return -1 ; } if (rc != 0) { //printf("[|802.11]"); fprintf(stderr, "wifipcap: truncated radiotap header for bit: %d\n", bit); return rc ; } switch (bit) { case IEEE80211_RADIOTAP_CHANNEL: //printf("%u MHz ", u.u16); if (u2.u16 != 0) //printf("(0x%04x) ", u2.u16); hdr->has_channel = true; hdr->channel = u2.u16; break; case IEEE80211_RADIOTAP_FHSS: //printf("fhset %d fhpat %d ", u.u16 & 0xff, (u.u16 >> 8) & 0xff); hdr->has_fhss = true; hdr->fhss_fhset = u.u16 & 0xff; hdr->fhss_fhpat = (u.u16 >> 8) & 0xff; break; case IEEE80211_RADIOTAP_RATE: //PRINT_RATE("", u.u8, " Mb/s "); hdr->has_rate = true; hdr->rate = u.u8; break; case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: //printf("%ddB signal ", u.i8); hdr->has_signal_dbm = true; hdr->signal_dbm = u.i8; break; case IEEE80211_RADIOTAP_DBM_ANTNOISE: //printf("%ddB noise ", u.i8); hdr->has_noise_dbm = true; hdr->noise_dbm = u.i8; break; case IEEE80211_RADIOTAP_DB_ANTSIGNAL: //printf("%ddB signal ", u.u8); hdr->has_signal_db = true; hdr->signal_db = u.u8; break; case IEEE80211_RADIOTAP_DB_ANTNOISE: //printf("%ddB noise ", u.u8); hdr->has_noise_db = true; hdr->noise_db = u.u8; break; case IEEE80211_RADIOTAP_LOCK_QUALITY: //printf("%u sq ", u.u16); hdr->has_quality = true; hdr->quality = u.u16; break; case IEEE80211_RADIOTAP_TX_ATTENUATION: //printf("%d tx power ", -(int)u.u16); hdr->has_txattenuation = true; hdr->txattenuation = -(int)u.u16; break; case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: //printf("%ddB tx power ", -(int)u.u8); hdr->has_txattenuation_db = true; hdr->txattenuation_db = -(int)u.u8; break; case IEEE80211_RADIOTAP_DBM_TX_POWER: //printf("%ddBm tx power ", u.i8); hdr->has_txpower_dbm = true; hdr->txpower_dbm = u.i8; break; case IEEE80211_RADIOTAP_FLAGS: hdr->has_flags = true; if (u.u8 & IEEE80211_RADIOTAP_F_CFP) //printf("cfp "); hdr->flags_cfp = true; if (u.u8 & IEEE80211_RADIOTAP_F_SHORTPRE) //printf("short preamble "); hdr->flags_short_preamble = true; if (u.u8 & IEEE80211_RADIOTAP_F_WEP) //printf("wep "); hdr->flags_wep = true; if (u.u8 & IEEE80211_RADIOTAP_F_FRAG) //printf("fragmented "); hdr->flags_fragmented = true; if (u.u8 & IEEE80211_RADIOTAP_F_BADFCS) //printf("bad-fcs "); hdr->flags_badfcs = true; break; case IEEE80211_RADIOTAP_ANTENNA: //printf("antenna %d ", u.u8); hdr->has_antenna = true; hdr->antenna = u.u8; break; case IEEE80211_RADIOTAP_TSFT: //printf("%" PRIu64 "us tsft ", u.u64); hdr->has_tsft = true; hdr->tsft = u.u64; break; case IEEE80211_RADIOTAP_RX_FLAGS: hdr->has_rxflags = true; hdr->rxflags = u.u16; break; case IEEE80211_RADIOTAP_TX_FLAGS: hdr->has_txflags = true; hdr->txflags = u.u16; break; case IEEE80211_RADIOTAP_RTS_RETRIES: hdr->has_rts_retries = true; hdr->rts_retries = u.u8; break; case IEEE80211_RADIOTAP_DATA_RETRIES: hdr->has_data_retries = true; hdr->data_retries = u.u8; break; } return 0 ; } void WifiPacket::handle_radiotap(const u_char *p,size_t caplen) { #define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x))) #define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x))) #define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x))) #define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x))) #define BITNO_2(x) (((x) & 2) ? 1 : 0) #define BIT(n) (1 << n) #define IS_EXTENDED(__p) (EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0 // If caplen is too small, just give it a try and carry on. if (caplen < sizeof(struct ieee80211_radiotap_header)) { cbs->HandleRadiotap( *this, NULL, p, caplen); return; } struct ieee80211_radiotap_header *hdr = (struct ieee80211_radiotap_header *)p; size_t len = EXTRACT_LE_16BITS(&hdr->it_len); // length of radiotap header if (caplen < len) { //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } uint32_t *last_presentp=0; for (last_presentp = &hdr->it_present; IS_EXTENDED(last_presentp) && (u_char*)(last_presentp + 1) <= p + len; last_presentp++){ } /* are there more bitmap extensions than bytes in header? */ if (IS_EXTENDED(last_presentp)) { //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } const u_char *iter = (u_char*)(last_presentp + 1); struct cpack_state cpacker; if (cpack_init(&cpacker, (u_int8_t*)iter, len - (iter - p)) != 0) { /* XXX */ //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } radiotap_hdr ohdr; memset(&ohdr, 0, sizeof(ohdr)); /* Assume no Atheros padding between 802.11 header and body */ int pad = 0; uint32_t *presentp; int bit0=0; for (bit0 = 0, presentp = &hdr->it_present; presentp <= last_presentp; presentp++, bit0 += 32) { u_int32_t present, next_present; for (present = EXTRACT_LE_32BITS(presentp); present; present = next_present) { /* clear the least significant bit that is set */ next_present = present & (present - 1); /* extract the least significant bit that is set */ enum ieee80211_radiotap_type bit = (enum ieee80211_radiotap_type) (bit0 + BITNO_32(present ^ next_present)); /* print the next radiotap field */ int r = print_radiotap_field(&cpacker, bit, &pad, &ohdr); /* If we got an error, break both loops */ if(r!=0) goto done; } } done:; cbs->HandleRadiotap( *this, &ohdr, p, caplen); //return len + ieee802_11_print(p + len, length - len, caplen - len, pad); #undef BITNO_32 #undef BITNO_16 #undef BITNO_8 #undef BITNO_4 #undef BITNO_2 #undef BIT handle_80211(p+len, caplen-len); } void WifiPacket::handle_prism(const u_char *pc, size_t len) { prism2_pkthdr hdr; /* get the fields */ hdr.host_time = EXTRACT_LE_32BITS(pc+32); hdr.mac_time = EXTRACT_LE_32BITS(pc+44); hdr.channel = EXTRACT_LE_32BITS(pc+56); hdr.rssi = EXTRACT_LE_32BITS(pc+68); hdr.sq = EXTRACT_LE_32BITS(pc+80); hdr.signal = EXTRACT_LE_32BITS(pc+92); hdr.noise = EXTRACT_LE_32BITS(pc+104); hdr.rate = EXTRACT_LE_32BITS(pc+116)/2; hdr.istx = EXTRACT_LE_32BITS(pc+128); cbs->HandlePrism( *this, &hdr, pc + 144, len - 144); handle_80211(pc+144,len-144); } /////////////////////////////////////////////////////////////////////////////// /// /// handle_*: /// handle each of the packet types /// void WifiPacket::handle_ether(const u_char *ptr, size_t len) { #if 0 ether_hdr_t hdr; hdr.da = MAC::ether2MAC(ptr); hdr.sa = MAC::ether2MAC(ptr+6); hdr.type = EXTRACT_16BITS(ptr + 12); ptr += 14; len -= 14; cbs->HandleEthernet(*this, &hdr, ptr, len); switch (hdr.type) { case ETHERTYPE_IP: handle_ip(ptr, len); return; case ETHERTYPE_IPV6: handle_ip6(ptr, len); return; case ETHERTYPE_ARP: handle_arp( ptr, len); return; default: cbs->HandleL2Unknown(*this, hdr.type, ptr, len); return; } #endif } /////////////////////////////////////////////////////////////////////////////// /* These are all static functions */ #if 0 void Wifipcap::dl_prism(const PcapUserData &data, const struct pcap_pkthdr *header, const u_char * packet) { WifipcapCallbacks *cbs = data.cbs; if(header->caplen < 144) return; // prism header cbs->PacketBegin( packet, header->caplen, header->len); handle_prism(cbs,packet+144,header->caplen-144); cbs->PacketEnd(); } void Wifipcap::dl_prism(u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { PcapUserData *data = reinterpret_cast<PcapUserData *>(user); Wifipcap::dl_prism(*data,header,packet); } #endif #if 0 void Wifipcap::dl_ieee802_11_radio(const PcapUserData &data, const struct pcap_pkthdr *header, const u_char * packet) { data.cbs->PacketBegin( packet, header->caplen, header->len); handle_radiotap(packet, header->caplen); data.cbs->PacketEnd(); } #endif void Wifipcap::dl_ieee802_11_radio(const u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { const PcapUserData *data = reinterpret_cast<const PcapUserData *>(user); WifiPacket pkt(data->cbs,data->header_type,header,packet); data->cbs->PacketBegin(pkt,packet,header->caplen,header->len); pkt.handle_radiotap(packet,header->caplen); data->cbs->PacketEnd(pkt); //Wifipcap::dl_ieee802_11_radio(*data,header,packet); } /////////////////////////////////////////////////////////////////////////////// /* None of these are used in tcpflow */ bool Wifipcap::InitNext() { if (morefiles.size() < 1){ return false; } if (descr) { pcap_close(descr); } Init(morefiles.front(), false); morefiles.pop_front(); return true; } void Wifipcap::Init(const char *name, bool live) { if (verbose){ std::cerr << "wifipcap: initializing '" << name << "'" << std::endl; } if (!live) { #ifdef _WIN32 std::cerr << "Trace replay is unsupported in windows." << std::endl; exit(1); #else // mini hack: handle gziped files since all our traces are in // this format int slen = strlen(name); bool gzip = !strcmp(name+slen-3, ".gz"); bool bzip = !strcmp(name+slen-4, ".bz2"); char cmd[256]; char errbuf[256]; if (gzip) sprintf(cmd, "zcat %s", name); else if (bzip) sprintf(cmd, "bzcat %s", name); else // using cat here instead of pcap_open or fopen is intentional // neither of these may be able to handle large files (>2GB files) // but cat uses the linux routines to allow it to sprintf(cmd, "cat %s", name); FILE *pipe = popen(cmd, "r"); if (pipe == NULL) { printf("popen(): %s\n", strerror(errno)); exit(1); } descr = pcap_fopen_offline(pipe, errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n", errbuf); exit(1); } #endif } else { char errbuf[256]; descr = pcap_open_live(name,BUFSIZ,1,-1,errbuf); if(descr == NULL) { printf("pcap_open_live(): %s\n", errbuf); exit(1); } } datalink = pcap_datalink(descr); if (datalink != DLT_PRISM_HEADER && datalink != DLT_IEEE802_11_RADIO && datalink != DLT_IEEE802_11) { if (datalink == DLT_EN10MB) { printf("warning: ethernet datalink type: %s\n", pcap_datalink_val_to_name(datalink)); } else { printf("warning: unrecognized datalink type: %s\n", pcap_datalink_val_to_name(datalink)); } } } /* object-oriented version of pcap callback. Called with the callbacks object, * the DLT type, the header and the packet. * This is the main packet processor. * It records some stats and then dispatches to the appropriate callback. */ void Wifipcap::handle_packet(WifipcapCallbacks *cbs,int header_type, const struct pcap_pkthdr *header, const u_char * packet) { /* Record start time if we don't have it */ if (startTime == TIME_NONE) { startTime = header->ts; lastPrintTime = header->ts; } /* Print stats if necessary */ if (header->ts.tv_sec > lastPrintTime.tv_sec + Wifipcap::PRINT_TIME_INTERVAL) { if (verbose) { int hours = (header->ts.tv_sec - startTime.tv_sec)/3600; int days = hours/24; int left = hours%24; fprintf(stderr, "wifipcap: %2d days %2d hours, %10" PRId64 " pkts\n", days, left, packetsProcessed); } lastPrintTime = header->ts; } packetsProcessed++; /* Create the packet object and call the appropriate callbacks */ WifiPacket pkt(cbs,header_type,header,packet); /* Notify callback */ cbs->PacketBegin(pkt, packet, header->caplen, header->len); //int frameLen = header->caplen; switch(header_type) { case DLT_PRISM_HEADER: pkt.handle_prism(packet,header->caplen); break; case DLT_IEEE802_11_RADIO: pkt.handle_radiotap(packet,header->caplen); break; case DLT_IEEE802_11: pkt.handle_80211(packet,header->caplen); break; case DLT_EN10MB: pkt.handle_ether(packet,header->caplen); break; default: #if 0 // try handling it as default IP assuming framing is ethernet // (this is for testing) pkt.handle_ip(packet,header->caplen); #endif break; } cbs->PacketEnd(pkt); } /* The raw callback from pcap; jump back into the object-oriented domain */ /* note: u_char *user may not be const according to spec */ void Wifipcap::handle_packet_callback(u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { Wifipcap::PcapUserData *data = reinterpret_cast<Wifipcap::PcapUserData *>(user); data->wcap->handle_packet(data->cbs,data->header_type,header,packet); } const char *Wifipcap::SetFilter(const char *filter) { struct bpf_program fp; #ifdef PCAP_NETMASK_UNKNOWN bpf_u_int32 netp=PCAP_NETMASK_UNKNOWN; #else bpf_u_int32 netp=0; #endif if(pcap_compile(descr,&fp,(char *)filter,0,netp) == -1) { return "Error calling pcap_compile"; } if(pcap_setfilter(descr,&fp) == -1) { return "Error setting filter"; } return NULL; } void Wifipcap::Run(WifipcapCallbacks *cbs, int maxpkts) { /* NOTE: This needs to be fixed so that the correct handle_packet is called */ packetsProcessed = 0; do { PcapUserData data(this,cbs,DLT_IEEE802_11_RADIO); pcap_loop(descr, maxpkts > 0 ? maxpkts - packetsProcessed : 0, Wifipcap::handle_packet_callback, reinterpret_cast<u_char *>(&data)); } while ( InitNext() ); } ///////////////////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_291_0
crossvul-cpp_data_bad_3222_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_3222_0
crossvul-cpp_data_good_5229_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/ext/bcmath/bcmath.h" #include "hphp/runtime/base/ini-setting.h" #include <folly/ScopeGuard.h> namespace HPHP { /////////////////////////////////////////////////////////////////////////////// struct bcmath_data { bcmath_data() { // we can't really call bc_init_numbers() that calls into this constructor data._zero_ = _bc_new_num_ex (1,0,1); data._one_ = _bc_new_num_ex (1,0,1); data._one_->n_value[0] = 1; data._two_ = _bc_new_num_ex (1,0,1); data._two_->n_value[0] = 2; data.bc_precision = 0; } BCMathGlobals data; }; static IMPLEMENT_THREAD_LOCAL(bcmath_data, s_globals); /////////////////////////////////////////////////////////////////////////////// static int64_t adjust_scale(int64_t scale) { if (scale < 0) { scale = BCG(bc_precision); if (scale < 0) scale = 0; } if ((uint64_t)scale > StringData::MaxSize) return StringData::MaxSize; return scale; } static void php_str2num(bc_num *num, const char *str) { const char *p; if (!(p = strchr(str, '.'))) { bc_str2num(num, (char*)str, 0); } else { bc_str2num(num, (char*)str, strlen(p + 1)); } } static bool HHVM_FUNCTION(bcscale, int64_t scale) { BCG(bc_precision) = scale < 0 ? 0 : scale; return true; } static String HHVM_FUNCTION(bcadd, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_add(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static String HHVM_FUNCTION(bcsub, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_sub(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static int64_t HHVM_FUNCTION(bccomp, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second; bc_init_num(&first); bc_init_num(&second); bc_str2num(&first, (char*)left.data(), scale); bc_str2num(&second, (char*)right.data(), scale); int64_t ret = bc_compare(first, second); bc_free_num(&first); bc_free_num(&second); return ret; } static String HHVM_FUNCTION(bcmul, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_multiply(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); return ret; } static Variant HHVM_FUNCTION(bcdiv, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); if (bc_divide(first, second, &result, scale) == -1) { raise_warning("Division by zero"); return init_null(); } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcmod, const String& left, const String& right) { bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); if (bc_modulo(first, second, &result, 0) == -1) { raise_warning("Division by zero"); return init_null(); } String ret(bc_num2str(result), AttachString); return ret; } static String HHVM_FUNCTION(bcpow, const String& left, const String& right, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); bc_raise(first, second, &result, scale); if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcpowmod, const String& left, const String& right, const String& modulus, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num first, second, mod, result; bc_init_num(&first); bc_init_num(&second); bc_init_num(&mod); bc_init_num(&result); SCOPE_EXIT { bc_free_num(&first); bc_free_num(&second); bc_free_num(&mod); bc_free_num(&result); }; php_str2num(&first, (char*)left.data()); php_str2num(&second, (char*)right.data()); php_str2num(&mod, (char*)modulus.data()); if (bc_raisemod(first, second, mod, &result, scale) == -1) { return false; } if (result->n_scale > scale) { result->n_scale = scale; } String ret(bc_num2str(result), AttachString); return ret; } static Variant HHVM_FUNCTION(bcsqrt, const String& operand, int64_t scale /* = -1 */) { scale = adjust_scale(scale); bc_num result; bc_init_num(&result); SCOPE_EXIT { bc_free_num(&result); }; php_str2num(&result, (char*)operand.data()); Variant ret; if (bc_sqrt(&result, scale) != 0) { if (result->n_scale > scale) { result->n_scale = scale; } ret = String(bc_num2str(result), AttachString); } else { raise_warning("Square root of negative number"); } return ret; } /////////////////////////////////////////////////////////////////////////////// struct bcmathExtension final : Extension { bcmathExtension() : Extension("bcmath", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(bcscale); HHVM_FE(bcadd); HHVM_FE(bcsub); HHVM_FE(bccomp); HHVM_FE(bcmul); HHVM_FE(bcdiv); HHVM_FE(bcmod); HHVM_FE(bcpow); HHVM_FE(bcpowmod); HHVM_FE(bcsqrt); loadSystemlib(); } void threadInit() override { IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "bcmath.scale", "0", &BCG(bc_precision)); } } s_bcmath_extension; /////////////////////////////////////////////////////////////////////////////// extern "C" { struct BCMathGlobals *get_bcmath_globals() { return &HPHP::s_globals.get()->data; } } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_5229_0
crossvul-cpp_data_good_434_2
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2016, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ /* Modification History: * Date Name Description * 07/15/99 helena Ported to HPUX 10/11 CC. */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "numfmtst.h" #include "unicode/currpinf.h" #include "unicode/dcfmtsym.h" #include "unicode/decimfmt.h" #include "unicode/localpointer.h" #include "unicode/ucurr.h" #include "unicode/ustring.h" #include "unicode/measfmt.h" #include "unicode/curramt.h" #include "unicode/strenum.h" #include "textfile.h" #include "tokiter.h" #include "charstr.h" #include "cstr.h" #include "putilimp.h" #include "winnmtst.h" #include <cmath> #include <float.h> #include <string.h> #include <stdlib.h> #include "cmemory.h" #include "cstring.h" #include "unicode/numsys.h" #include "fmtableimp.h" #include "numberformattesttuple.h" #include "unicode/msgfmt.h" #include "number_decimalquantity.h" #include "unicode/numberformatter.h" #if (U_PLATFORM == U_PF_AIX) || (U_PLATFORM == U_PF_OS390) // These should not be macros. If they are, // replace them with std::isnan and std::isinf #if defined(isnan) #undef isnan namespace std { bool isnan(double x) { return _isnan(x); } } #endif #if defined(isinf) #undef isinf namespace std { bool isinf(double x) { return _isinf(x); } } #endif #endif using icu::number::impl::DecimalQuantity; using namespace icu::number; //#define NUMFMTST_CACHE_DEBUG 1 #include "stdio.h" /* for sprintf */ // #include "iostream" // for cout //#define NUMFMTST_DEBUG 1 static const UChar EUR[] = {69,85,82,0}; // "EUR" static const UChar ISO_CURRENCY_USD[] = {0x55, 0x53, 0x44, 0}; // "USD" // ***************************************************************************** // class NumberFormatTest // ***************************************************************************** #define CHECK(status,str) if (U_FAILURE(status)) { errcheckln(status, UnicodeString("FAIL: ") + str + " - " + u_errorName(status)); return; } #define CHECK_DATA(status,str) if (U_FAILURE(status)) { dataerrln(UnicodeString("FAIL: ") + str + " - " + u_errorName(status)); return; } void NumberFormatTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ ) { TESTCASE_AUTO_BEGIN; TESTCASE_AUTO(TestCurrencySign); TESTCASE_AUTO(TestCurrency); TESTCASE_AUTO(TestParse); TESTCASE_AUTO(TestRounding487); TESTCASE_AUTO(TestQuotes); TESTCASE_AUTO(TestExponential); TESTCASE_AUTO(TestPatterns); // Upgrade to alphaWorks - liu 5/99 TESTCASE_AUTO(TestExponent); TESTCASE_AUTO(TestScientific); TESTCASE_AUTO(TestPad); TESTCASE_AUTO(TestPatterns2); TESTCASE_AUTO(TestSecondaryGrouping); TESTCASE_AUTO(TestSurrogateSupport); TESTCASE_AUTO(TestAPI); TESTCASE_AUTO(TestCurrencyObject); TESTCASE_AUTO(TestCurrencyPatterns); //TESTCASE_AUTO(TestDigitList); TESTCASE_AUTO(TestWhiteSpaceParsing); TESTCASE_AUTO(TestComplexCurrency); // This test removed because CLDR no longer uses choice formats in currency symbols. TESTCASE_AUTO(TestRegCurrency); TESTCASE_AUTO(TestSymbolsWithBadLocale); TESTCASE_AUTO(TestAdoptDecimalFormatSymbols); TESTCASE_AUTO(TestScientific2); TESTCASE_AUTO(TestScientificGrouping); TESTCASE_AUTO(TestInt64); TESTCASE_AUTO(TestPerMill); TESTCASE_AUTO(TestIllegalPatterns); TESTCASE_AUTO(TestCases); TESTCASE_AUTO(TestCurrencyNames); TESTCASE_AUTO(TestCurrencyAmount); TESTCASE_AUTO(TestCurrencyUnit); TESTCASE_AUTO(TestCoverage); TESTCASE_AUTO(TestLocalizedPatternSymbolCoverage); TESTCASE_AUTO(TestJB3832); TESTCASE_AUTO(TestHost); TESTCASE_AUTO(TestHostClone); TESTCASE_AUTO(TestCurrencyFormat); TESTCASE_AUTO(TestRounding); TESTCASE_AUTO(TestNonpositiveMultiplier); TESTCASE_AUTO(TestNumberingSystems); TESTCASE_AUTO(TestSpaceParsing); TESTCASE_AUTO(TestMultiCurrencySign); TESTCASE_AUTO(TestCurrencyFormatForMixParsing); TESTCASE_AUTO(TestMismatchedCurrencyFormatFail); TESTCASE_AUTO(TestDecimalFormatCurrencyParse); TESTCASE_AUTO(TestCurrencyIsoPluralFormat); TESTCASE_AUTO(TestCurrencyParsing); TESTCASE_AUTO(TestParseCurrencyInUCurr); TESTCASE_AUTO(TestFormatAttributes); TESTCASE_AUTO(TestFieldPositionIterator); TESTCASE_AUTO(TestDecimal); TESTCASE_AUTO(TestCurrencyFractionDigits); TESTCASE_AUTO(TestExponentParse); TESTCASE_AUTO(TestExplicitParents); TESTCASE_AUTO(TestLenientParse); TESTCASE_AUTO(TestAvailableNumberingSystems); TESTCASE_AUTO(TestRoundingPattern); TESTCASE_AUTO(Test9087); TESTCASE_AUTO(TestFormatFastpaths); TESTCASE_AUTO(TestFormattableSize); TESTCASE_AUTO(TestUFormattable); TESTCASE_AUTO(TestSignificantDigits); TESTCASE_AUTO(TestShowZero); TESTCASE_AUTO(TestCompatibleCurrencies); TESTCASE_AUTO(TestBug9936); TESTCASE_AUTO(TestParseNegativeWithFaLocale); TESTCASE_AUTO(TestParseNegativeWithAlternateMinusSign); TESTCASE_AUTO(TestCustomCurrencySignAndSeparator); TESTCASE_AUTO(TestParseSignsAndMarks); TESTCASE_AUTO(Test10419RoundingWith0FractionDigits); TESTCASE_AUTO(Test10468ApplyPattern); TESTCASE_AUTO(TestRoundingScientific10542); TESTCASE_AUTO(TestZeroScientific10547); TESTCASE_AUTO(TestAccountingCurrency); TESTCASE_AUTO(TestEquality); TESTCASE_AUTO(TestCurrencyUsage); TESTCASE_AUTO(TestDoubleLimit11439); TESTCASE_AUTO(TestGetAffixes); TESTCASE_AUTO(TestToPatternScientific11648); TESTCASE_AUTO(TestBenchmark); TESTCASE_AUTO(TestCtorApplyPatternDifference); TESTCASE_AUTO(TestFractionalDigitsForCurrency); TESTCASE_AUTO(TestFormatCurrencyPlural); TESTCASE_AUTO(Test11868); TESTCASE_AUTO(Test11739_ParseLongCurrency); TESTCASE_AUTO(Test13035_MultiCodePointPaddingInPattern); TESTCASE_AUTO(Test13737_ParseScientificStrict); TESTCASE_AUTO(Test10727_RoundingZero); TESTCASE_AUTO(Test11376_getAndSetPositivePrefix); TESTCASE_AUTO(Test11475_signRecognition); TESTCASE_AUTO(Test11640_getAffixes); TESTCASE_AUTO(Test11649_toPatternWithMultiCurrency); TESTCASE_AUTO(Test13327_numberingSystemBufferOverflow); TESTCASE_AUTO(Test13391_chakmaParsing); TESTCASE_AUTO(Test11735_ExceptionIssue); TESTCASE_AUTO(Test11035_FormatCurrencyAmount); TESTCASE_AUTO(Test11318_DoubleConversion); TESTCASE_AUTO(TestParsePercentRegression); TESTCASE_AUTO(TestMultiplierWithScale); TESTCASE_AUTO(TestFastFormatInt32); TESTCASE_AUTO(Test11646_Equality); TESTCASE_AUTO(TestParseNaN); TESTCASE_AUTO(Test11897_LocalizedPatternSeparator); TESTCASE_AUTO(Test13055_PercentageRounding); TESTCASE_AUTO(Test11839); TESTCASE_AUTO(Test10354); TESTCASE_AUTO(Test11645_ApplyPatternEquality); TESTCASE_AUTO(Test12567); TESTCASE_AUTO(Test11626_CustomizeCurrencyPluralInfo); TESTCASE_AUTO(Test20073_StrictPercentParseErrorIndex); TESTCASE_AUTO(Test13056_GroupingSize); TESTCASE_AUTO(Test11025_CurrencyPadding); TESTCASE_AUTO(Test11648_ExpDecFormatMalPattern); TESTCASE_AUTO(Test11649_DecFmtCurrencies); TESTCASE_AUTO(Test13148_ParseGroupingSeparators); TESTCASE_AUTO(Test12753_PatternDecimalPoint); TESTCASE_AUTO(Test11647_PatternCurrencySymbols); TESTCASE_AUTO(Test11913_BigDecimal); TESTCASE_AUTO(Test11020_RoundingInScientificNotation); TESTCASE_AUTO(Test11640_TripleCurrencySymbol); TESTCASE_AUTO(Test13763_FieldPositionIteratorOffset); TESTCASE_AUTO(Test13777_ParseLongNameNonCurrencyMode); TESTCASE_AUTO(Test13804_EmptyStringsWhenParsing); TESTCASE_AUTO(Test20037_ScientificIntegerOverflow); TESTCASE_AUTO(Test13840_ParseLongStringCrash); TESTCASE_AUTO(Test13850_EmptyStringCurrency); TESTCASE_AUTO_END; } // ------------------------------------- // Test API (increase code coverage) void NumberFormatTest::TestAPI(void) { logln("Test API"); UErrorCode status = U_ZERO_ERROR; NumberFormat *test = NumberFormat::createInstance("root", status); if(U_FAILURE(status)) { dataerrln("unable to create format object - %s", u_errorName(status)); } if(test != NULL) { test->setMinimumIntegerDigits(10); test->setMaximumIntegerDigits(1); test->setMinimumFractionDigits(10); test->setMaximumFractionDigits(1); UnicodeString result; FieldPosition pos; Formattable bla("Paja Patak"); // Donald Duck for non Serbian speakers test->format(bla, result, pos, status); if(U_SUCCESS(status)) { errln("Yuck... Formatted a duck... As a number!"); } else { status = U_ZERO_ERROR; } result.remove(); int64_t ll = 12; test->format(ll, result); assertEquals("format int64_t error", u"2.0", result); test->setMinimumIntegerDigits(4); test->setMinimumFractionDigits(4); result.remove(); test->format(ll, result); assertEquals("format int64_t error", u"0,012.0000", result); ParsePosition ppos; LocalPointer<CurrencyAmount> currAmt(test->parseCurrency("",ppos)); // old test for (U_FAILURE(status)) was bogus here, method does not set status! if (ppos.getIndex()) { errln("Parsed empty string as currency"); } delete test; } } class StubNumberFormat :public NumberFormat{ public: StubNumberFormat(){}; virtual UnicodeString& format(double ,UnicodeString& appendTo,FieldPosition& ) const { return appendTo; } virtual UnicodeString& format(int32_t ,UnicodeString& appendTo,FieldPosition& ) const { return appendTo.append((UChar)0x0033); } virtual UnicodeString& format(int64_t number,UnicodeString& appendTo,FieldPosition& pos) const { return NumberFormat::format(number, appendTo, pos); } virtual UnicodeString& format(const Formattable& , UnicodeString& appendTo, FieldPosition& , UErrorCode& ) const { return appendTo; } virtual void parse(const UnicodeString& , Formattable& , ParsePosition& ) const {} virtual void parse( const UnicodeString& , Formattable& , UErrorCode& ) const {} virtual UClassID getDynamicClassID(void) const { static char classID = 0; return (UClassID)&classID; } virtual Format* clone() const {return NULL;} }; void NumberFormatTest::TestCoverage(void){ StubNumberFormat stub; UnicodeString agent("agent"); FieldPosition pos; int64_t num = 4; if (stub.format(num, agent, pos) != UnicodeString("agent3")){ errln("NumberFormat::format(int64, UnicodString&, FieldPosition&) should delegate to (int32, ,)"); }; } void NumberFormatTest::TestLocalizedPatternSymbolCoverage() { IcuTestErrorCode errorCode(*this, "TestLocalizedPatternSymbolCoverage"); // Ticket #12961: DecimalFormat::toLocalizedPattern() is not working as designed. DecimalFormatSymbols dfs(errorCode); dfs.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u'⁖'); dfs.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u'⁘'); dfs.setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, u'⁙'); dfs.setSymbol(DecimalFormatSymbols::kDigitSymbol, u'▰'); dfs.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, u'໐'); dfs.setSymbol(DecimalFormatSymbols::kSignificantDigitSymbol, u'⁕'); dfs.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u'†'); dfs.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u'‡'); dfs.setSymbol(DecimalFormatSymbols::kPercentSymbol, u'⁜'); dfs.setSymbol(DecimalFormatSymbols::kPerMillSymbol, u'‱'); dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"⁑⁑"); // tests multi-char sequence dfs.setSymbol(DecimalFormatSymbols::kPadEscapeSymbol, u'⁂'); { UnicodeString standardPattern(u"#,##0.05+%;#,##0.05-%"); UnicodeString localizedPattern(u"▰⁖▰▰໐⁘໐໕†⁜⁙▰⁖▰▰໐⁘໐໕‡⁜"); DecimalFormat df1("#", new DecimalFormatSymbols(dfs), errorCode); df1.applyPattern(standardPattern, errorCode); DecimalFormat df2("#", new DecimalFormatSymbols(dfs), errorCode); df2.applyLocalizedPattern(localizedPattern, errorCode); assertTrue("DecimalFormat instances should be equal", df1 == df2); UnicodeString p2; assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern(p2)); UnicodeString lp1; assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern(lp1)); } { UnicodeString standardPattern(u"* @@@E0‰"); UnicodeString localizedPattern(u"⁂ ⁕⁕⁕⁑⁑໐‱"); DecimalFormat df1("#", new DecimalFormatSymbols(dfs), errorCode); df1.applyPattern(standardPattern, errorCode); DecimalFormat df2("#", new DecimalFormatSymbols(dfs), errorCode); df2.applyLocalizedPattern(localizedPattern, errorCode); assertTrue("DecimalFormat instances should be equal", df1 == df2); UnicodeString p2; assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern(p2)); UnicodeString lp1; assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern(lp1)); } } // Test various patterns void NumberFormatTest::TestPatterns(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "FAIL: Could not construct DecimalFormatSymbols - %s", u_errorName(status)); return; } const char* pat[] = { "#.#", "#.", ".#", "#" }; int32_t pat_length = UPRV_LENGTHOF(pat); const char* newpat[] = { "0.#", "0.", "#.0", "0" }; const char* num[] = { "0", "0.", ".0", "0" }; for (int32_t i=0; i<pat_length; ++i) { status = U_ZERO_ERROR; DecimalFormat fmt(pat[i], sym, status); if (U_FAILURE(status)) { errln((UnicodeString)"FAIL: DecimalFormat constructor failed for " + pat[i]); continue; } UnicodeString newp; fmt.toPattern(newp); if (!(newp == newpat[i])) errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); UnicodeString s; (*(NumberFormat*)&fmt).format((int32_t)0, s); if (!(s == num[i])) { errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); logln((UnicodeString)"Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } /* icu_2_4::DigitList::operator== 0 0 2 icuuc24d.dll digitlst.cpp Doug icu_2_4::DigitList::append 0 0 4 icuin24d.dll digitlst.h Doug icu_2_4::DigitList::operator!= 0 0 1 icuuc24d.dll digitlst.h Doug */ /* void NumberFormatTest::TestDigitList(void) { // API coverage for DigitList DigitList list1; list1.append('1'); list1.fDecimalAt = 1; DigitList list2; list2.set((int32_t)1); if (list1 != list2) { errln("digitlist append, operator!= or set failed "); } if (!(list1 == list2)) { errln("digitlist append, operator== or set failed "); } } */ // ------------------------------------- // Test exponential pattern void NumberFormatTest::TestExponential(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "FAIL: Bad status returned by DecimalFormatSymbols ct - %s", u_errorName(status)); return; } const char* pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" }; int32_t pat_length = UPRV_LENGTHOF(pat); // The following #if statements allow this test to be built and run on // platforms that do not have standard IEEE numerics. For example, // S/390 doubles have an exponent range of -78 to +75. For the // following #if statements to work, float.h must define // DBL_MAX_10_EXP to be a compile-time constant. // This section may be expanded as needed. #if DBL_MAX_10_EXP > 300 double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 }; int32_t val_length = UPRV_LENGTHOF(val); const char* valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271", // 00.000E00 "12.340E-03", "12.346E07", "12.300E299", "-31.416E-272", // ##0.######E000 "12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" }; double valParse[] = { 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123456800, 1.23E300, -3.141593E-271, 0.01234, 123500000, 1.23E300, -3.142E-271, }; #elif DBL_MAX_10_EXP > 70 double val[] = { 0.01234, 123456789, 1.23e70, -3.141592653e-71 }; int32_t val_length = UPRV_LENGTHOF(val); char* valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E70", "-3.1416E-71", // 00.000E00 "12.340E-03", "12.346E07", "12.300E69", "-31.416E-72", // ##0.######E000 "12.34E-003", "123.4568E006", "12.3E069", "-31.41593E-072", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E70", "[3.142E-71]" }; double valParse[] = { 0.01234, 123460000, 1.23E70, -3.1416E-71, 0.01234, 123460000, 1.23E70, -3.1416E-71, 0.01234, 123456800, 1.23E70, -3.141593E-71, 0.01234, 123500000, 1.23E70, -3.142E-71, }; #else // Don't test double conversion double* val = 0; int32_t val_length = 0; char** valFormat = 0; double* valParse = 0; logln("Warning: Skipping double conversion tests"); #endif int32_t lval[] = { 0, -1, 1, 123456789 }; int32_t lval_length = UPRV_LENGTHOF(lval); const char* lvalFormat[] = { // 0.####E0 "0E0", "-1E0", "1E0", "1.2346E8", // 00.000E00 "00.000E00", "-10.000E-01", "10.000E-01", "12.346E07", // ##0.######E000 "0E000", "-1E000", "1E000", "123.4568E006", // 0.###E0;[0.###E0] "0E0", "[1E0]", "1E0", "1.235E8" }; int32_t lvalParse[] = { 0, -1, 1, 123460000, 0, -1, 1, 123460000, 0, -1, 1, 123456800, 0, -1, 1, 123500000, }; int32_t ival = 0, ilval = 0; for (int32_t p=0; p<pat_length; ++p) { DecimalFormat fmt(pat[p], sym, status); if (U_FAILURE(status)) { errln("FAIL: Bad status returned by DecimalFormat ct"); continue; } UnicodeString pattern; logln((UnicodeString)"Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern(pattern) + "\""); int32_t v; for (v=0; v<val_length; ++v) { UnicodeString s; (*(NumberFormat*)&fmt).format(val[v], s); logln((UnicodeString)" " + val[v] + " -format-> " + s); if (s != valFormat[v+ival]) errln((UnicodeString)"FAIL: Expected " + valFormat[v+ival]); ParsePosition pos(0); Formattable af; fmt.parse(s, af, pos); double a; UBool useEpsilon = FALSE; if (af.getType() == Formattable::kLong) a = af.getLong(); else if (af.getType() == Formattable::kDouble) { a = af.getDouble(); #if U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400 // S/390 will show a failure like this: //| -3.141592652999999e-271 -format-> -3.1416E-271 //| -parse-> -3.1416e-271 //| FAIL: Expected -3.141599999999999e-271 // To compensate, we use an epsilon-based equality // test on S/390 only. We don't want to do this in // general because it's less exacting. useEpsilon = TRUE; #endif } else { errln(UnicodeString("FAIL: Non-numeric Formattable returned: ") + pattern + " " + s); continue; } if (pos.getIndex() == s.length()) { logln((UnicodeString)" -parse-> " + a); // Use epsilon comparison as necessary if ((useEpsilon && (uprv_fabs(a - valParse[v+ival]) / a > (2*DBL_EPSILON))) || (!useEpsilon && a != valParse[v+ival])) { errln((UnicodeString)"FAIL: Expected " + valParse[v+ival] + " but got " + a + " on input " + s); } } else { errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); errln((UnicodeString)" should be (" + s.length() + " chars) -> " + valParse[v+ival]); } } for (v=0; v<lval_length; ++v) { UnicodeString s; (*(NumberFormat*)&fmt).format(lval[v], s); logln((UnicodeString)" " + lval[v] + "L -format-> " + s); if (s != lvalFormat[v+ilval]) errln((UnicodeString)"ERROR: Expected " + lvalFormat[v+ilval] + " Got: " + s); ParsePosition pos(0); Formattable af; fmt.parse(s, af, pos); if (af.getType() == Formattable::kLong || af.getType() == Formattable::kInt64) { UErrorCode status = U_ZERO_ERROR; int32_t a = af.getLong(status); if (pos.getIndex() == s.length()) { logln((UnicodeString)" -parse-> " + a); if (a != lvalParse[v+ilval]) errln((UnicodeString)"FAIL: Expected " + lvalParse[v+ilval] + " but got " + a); } else errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } else errln((UnicodeString)"FAIL: Non-long Formattable returned for " + s + " Double: " + af.getDouble() + ", Long: " + af.getLong()); } ival += val_length; ilval += lval_length; } } void NumberFormatTest::TestScientific2() { // jb 2552 UErrorCode status = U_ZERO_ERROR; DecimalFormat* fmt = (DecimalFormat*)NumberFormat::createCurrencyInstance("en_US", status); if (U_SUCCESS(status)) { double num = 12.34; expect(*fmt, num, "$12.34"); fmt->setScientificNotation(TRUE); expect(*fmt, num, "$1.23E1"); fmt->setScientificNotation(FALSE); expect(*fmt, num, "$12.34"); } delete fmt; } void NumberFormatTest::TestScientificGrouping() { // jb 2552 UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("##0.00E0",status); if (assertSuccess("", status, true, __FILE__, __LINE__)) { expect(fmt, .01234, "12.3E-3"); expect(fmt, .1234, "123E-3"); expect(fmt, 1.234, "1.23E0"); expect(fmt, 12.34, "12.3E0"); expect(fmt, 123.4, "123E0"); expect(fmt, 1234., "1.23E3"); } } /*static void setFromString(DigitList& dl, const char* str) { char c; UBool decimalSet = FALSE; dl.clear(); while ((c = *str++)) { if (c == '-') { dl.fIsPositive = FALSE; } else if (c == '+') { dl.fIsPositive = TRUE; } else if (c == '.') { dl.fDecimalAt = dl.fCount; decimalSet = TRUE; } else { dl.append(c); } } if (!decimalSet) { dl.fDecimalAt = dl.fCount; } }*/ void NumberFormatTest::TestInt64() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("#.#E0",status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } fmt.setMaximumFractionDigits(20); if (U_SUCCESS(status)) { expect(fmt, (Formattable)(int64_t)0, "0E0"); expect(fmt, (Formattable)(int64_t)-1, "-1E0"); expect(fmt, (Formattable)(int64_t)1, "1E0"); expect(fmt, (Formattable)(int64_t)2147483647, "2.147483647E9"); expect(fmt, (Formattable)((int64_t)-2147483647-1), "-2.147483648E9"); expect(fmt, (Formattable)(int64_t)U_INT64_MAX, "9.223372036854775807E18"); expect(fmt, (Formattable)(int64_t)U_INT64_MIN, "-9.223372036854775808E18"); } // also test digitlist /* int64_t int64max = U_INT64_MAX; int64_t int64min = U_INT64_MIN; const char* int64maxstr = "9223372036854775807"; const char* int64minstr = "-9223372036854775808"; UnicodeString fail("fail: "); // test max int64 value DigitList dl; setFromString(dl, int64maxstr); { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + int64maxstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != int64max) { errln(fail + int64maxstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != int64max) { errln(fail + int64maxstr); } } // test negative of max int64 value (1 shy of min int64 value) dl.fIsPositive = FALSE; { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + "-" + int64maxstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != -int64max) { errln(fail + "-" + int64maxstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != -int64max) { errln(fail + "-" + int64maxstr); } } // test min int64 value setFromString(dl, int64minstr); { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + "-" + int64minstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != int64min) { errln(fail + int64minstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != int64min) { errln(fail + int64minstr); } } // test negative of min int 64 value (1 more than max int64 value) dl.fIsPositive = TRUE; // won't fit { if (dl.fitsIntoInt64(FALSE)) { errln(fail + "-(" + int64minstr + ") didn't fit"); } }*/ } // ------------------------------------- // Test the handling of quotes void NumberFormatTest::TestQuotes(void) { UErrorCode status = U_ZERO_ERROR; UnicodeString *pat; DecimalFormatSymbols *sym = new DecimalFormatSymbols(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "Fail to create DecimalFormatSymbols - %s", u_errorName(status)); delete sym; return; } pat = new UnicodeString("a'fo''o'b#"); DecimalFormat *fmt = new DecimalFormat(*pat, *sym, status); UnicodeString s; ((NumberFormat*)fmt)->format((int32_t)123, s); logln((UnicodeString)"Pattern \"" + *pat + "\""); logln((UnicodeString)" Format 123 -> " + escape(s)); if (!(s=="afo'ob123")) errln((UnicodeString)"FAIL: Expected afo'ob123"); s.truncate(0); delete fmt; delete pat; pat = new UnicodeString("a''b#"); fmt = new DecimalFormat(*pat, *sym, status); ((NumberFormat*)fmt)->format((int32_t)123, s); logln((UnicodeString)"Pattern \"" + *pat + "\""); logln((UnicodeString)" Format 123 -> " + escape(s)); if (!(s=="a'b123")) errln((UnicodeString)"FAIL: Expected a'b123"); delete fmt; delete pat; delete sym; } /** * Test the handling of the currency symbol in patterns. */ void NumberFormatTest::TestCurrencySign(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale::getUS(), status); UnicodeString pat; UChar currency = 0x00A4; if (U_FAILURE(status)) { errcheckln(status, "Fail to create DecimalFormatSymbols - %s", u_errorName(status)); delete sym; return; } // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append("#,##0.00;-"). append(currency).append("#,##0.00"); DecimalFormat *fmt = new DecimalFormat(pat, *sym, status); UnicodeString s; ((NumberFormat*)fmt)->format(1234.56, s); pat.truncate(0); logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); if (s != "$1,234.56") dataerrln((UnicodeString)"FAIL: Expected $1,234.56"); s.truncate(0); ((NumberFormat*)fmt)->format(- 1234.56, s); logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); if (s != "-$1,234.56") dataerrln((UnicodeString)"FAIL: Expected -$1,234.56"); delete fmt; pat.truncate(0); // "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00" pat.append(currency).append(currency). append(" #,##0.00;"). append(currency).append(currency). append(" -#,##0.00"); fmt = new DecimalFormat(pat, *sym, status); s.truncate(0); ((NumberFormat*)fmt)->format(1234.56, s); logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); if (s != "USD 1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD 1,234.56"); s.truncate(0); ((NumberFormat*)fmt)->format(-1234.56, s); logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); if (s != "USD -1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD -1,234.56"); delete fmt; delete sym; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + u_errorName(status)); } // ------------------------------------- static UChar toHexString(int32_t i) { return (UChar)(i + (i < 10 ? 0x30 : (0x41 - 10))); } UnicodeString& NumberFormatTest::escape(UnicodeString& s) { UnicodeString buf; for (int32_t i=0; i<s.length(); ++i) { UChar c = s[(int32_t)i]; if (c <= (UChar)0x7F) buf += c; else { buf += (UChar)0x5c; buf += (UChar)0x55; buf += toHexString((c & 0xF000) >> 12); buf += toHexString((c & 0x0F00) >> 8); buf += toHexString((c & 0x00F0) >> 4); buf += toHexString(c & 0x000F); } } return (s = buf); } // ------------------------------------- static const char* testCases[][2]= { /* locale ID */ /* expected */ {"ca_ES_PREEURO", "\\u20A7\\u00A01.150" }, {"de_LU_PREEURO", "1,150\\u00A0F" }, {"el_GR_PREEURO", "1.150,50\\u00A0\\u0394\\u03C1\\u03C7" }, {"en_BE_PREEURO", "1.150,50\\u00A0BEF" }, {"es_ES_PREEURO", "1.150\\u00A0\\u20A7" }, {"eu_ES_PREEURO", "\\u20A7\\u00A01.150" }, {"gl_ES_PREEURO", "1.150\\u00A0\\u20A7" }, {"it_IT_PREEURO", "ITL\\u00A01.150" }, {"pt_PT_PREEURO", "1,150$50\\u00A0\\u200B"}, // per cldrbug 7670 {"en_US@currency=JPY", "\\u00A51,150"}, {"en_US@currency=jpy", "\\u00A51,150"}, {"en-US-u-cu-jpy", "\\u00A51,150"} }; /** * Test localized currency patterns. */ void NumberFormatTest::TestCurrency(void) { UErrorCode status = U_ZERO_ERROR; NumberFormat* currencyFmt = NumberFormat::createCurrencyInstance(Locale::getCanadaFrench(), status); if (U_FAILURE(status)) { dataerrln("Error calling NumberFormat::createCurrencyInstance()"); return; } UnicodeString s; currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre ici a..........." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0$"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>$ but got " + s); delete currencyFmt; s.truncate(0); char loc[256]={0}; int len = uloc_canonicalize("de_DE_PREEURO", loc, 256, &status); (void)len; // Suppress unused variable warning. currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc),status); currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre en Allemagne a.." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0DM"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>DM but got " + s); delete currencyFmt; s.truncate(0); len = uloc_canonicalize("fr_FR_PREEURO", loc, 256, &status); currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc), status); currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre en France a....." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0F"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>F"); delete currencyFmt; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + (int32_t)status); for(int i=0; i < UPRV_LENGTHOF(testCases); i++){ status = U_ZERO_ERROR; const char *localeID = testCases[i][0]; UnicodeString expected(testCases[i][1], -1, US_INV); expected = expected.unescape(); s.truncate(0); char loc[256]={0}; uloc_canonicalize(localeID, loc, 256, &status); currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc), status); if(U_FAILURE(status)){ errln("Could not create currency formatter for locale %s",localeID); continue; } currencyFmt->format(1150.50, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln((UnicodeString)"FAIL: Status " + (int32_t)status); } delete currencyFmt; } } // ------------------------------------- /** * Test the Currency object handling, new as of ICU 2.2. */ void NumberFormatTest::TestCurrencyObject() { UErrorCode ec = U_ZERO_ERROR; NumberFormat* fmt = NumberFormat::createCurrencyInstance(Locale::getUS(), ec); if (U_FAILURE(ec)) { dataerrln("FAIL: getCurrencyInstance(US) - %s", u_errorName(ec)); delete fmt; return; } Locale null("", "", ""); expectCurrency(*fmt, null, 1234.56, "$1,234.56"); expectCurrency(*fmt, Locale::getFrance(), 1234.56, CharsToUnicodeString("\\u20AC1,234.56")); // Euro expectCurrency(*fmt, Locale::getJapan(), 1234.56, CharsToUnicodeString("\\u00A51,235")); // Yen expectCurrency(*fmt, Locale("fr", "CH", ""), 1234.56, "CHF 1,234.56"); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(*fmt, Locale::getUS(), 1234.56, "$1,234.56"); delete fmt; fmt = NumberFormat::createCurrencyInstance(Locale::getFrance(), ec); if (U_FAILURE(ec)) { errln("FAIL: getCurrencyInstance(FRANCE)"); delete fmt; return; } expectCurrency(*fmt, null, 1234.56, CharsToUnicodeString("1\\u202F234,56 \\u20AC")); expectCurrency(*fmt, Locale::getJapan(), 1234.56, CharsToUnicodeString("1\\u202F235 JPY")); // Yen expectCurrency(*fmt, Locale("fr", "CH", ""), 1234.56, CharsToUnicodeString("1\\u202F234,56 CHF")); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(*fmt, Locale::getUS(), 1234.56, CharsToUnicodeString("1\\u202F234,56 $US")); expectCurrency(*fmt, Locale::getFrance(), 1234.56, CharsToUnicodeString("1\\u202F234,56 \\u20AC")); // Euro delete fmt; } // ------------------------------------- /** * Do rudimentary testing of parsing. */ void NumberFormatTest::TestParse(void) { UErrorCode status = U_ZERO_ERROR; UnicodeString arg("0"); DecimalFormat* format = new DecimalFormat("00", status); //try { Formattable n; format->parse(arg, n, status); logln((UnicodeString)"parse(" + arg + ") = " + n.getLong()); if (n.getType() != Formattable::kLong || n.getLong() != 0) errln((UnicodeString)"FAIL: Expected 0"); delete format; if (U_FAILURE(status)) errcheckln(status, (UnicodeString)"FAIL: Status " + u_errorName(status)); //} //catch(Exception e) { // errln((UnicodeString)"Exception caught: " + e); //} } // ------------------------------------- static const char *lenientAffixTestCases[] = { "(1)", "( 1)", "(1 )", "( 1 )" }; static const char *lenientMinusTestCases[] = { "-5", "\\u22125", "\\u27965" }; static const char *lenientCurrencyTestCases[] = { "$1,000", "$ 1,000", "$1000", "$ 1000", "$1 000.00", "$ 1 000.00", "$ 1\\u00A0000.00", "1000.00" }; // changed from () to - per cldrbug 5674 static const char *lenientNegativeCurrencyTestCases[] = { "-$1,000", "-$ 1,000", "-$1000", "-$ 1000", "-$1 000.00", "-$ 1 000.00", "- $ 1,000.00 ", "-$ 1\\u00A0000.00", "-1000.00" }; static const char *lenientPercentTestCases[] = { "25%", " 25%", " 25 %", "25 %", "25\\u00A0%", "25" }; static const char *lenientNegativePercentTestCases[] = { "-25%", " -25%", " - 25%", "- 25 %", " - 25 %", "-25 %", "-25\\u00A0%", "-25", "- 25" }; static const char *strictFailureTestCases[] = { " 1000", "10,00", "1,000,.0" }; /** * Test lenient parsing. */ void NumberFormatTest::TestLenientParse(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormat *format = new DecimalFormat("(#,##0)", status); Formattable n; if (format == NULL || U_FAILURE(status)) { dataerrln("Unable to create DecimalFormat (#,##0) - %s", u_errorName(status)); } else { format->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientAffixTestCases); t += 1) { UnicodeString testCase = ctou(lenientAffixTestCases[t]); format->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != 1) { dataerrln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientAffixTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete format; } Locale en_US("en_US"); Locale sv_SE("sv_SE"); NumberFormat *mFormat = NumberFormat::createInstance(sv_SE, UNUM_DECIMAL, status); if (mFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (sv_SE, UNUM_DECIMAL) - %s", u_errorName(status)); } else { mFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(lenientMinusTestCases); t += 1) { UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete mFormat; } mFormat = NumberFormat::createInstance(en_US, UNUM_DECIMAL, status); if (mFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US, UNUM_DECIMAL) - %s", u_errorName(status)); } else { mFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(lenientMinusTestCases); t += 1) { UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete mFormat; } NumberFormat *cFormat = NumberFormat::createInstance(en_US, UNUM_CURRENCY, status); if (cFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US, UNUM_CURRENCY) - %s", u_errorName(status)); } else { cFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientCurrencyTestCases); t += 1) { UnicodeString testCase = ctou(lenientCurrencyTestCases[t]); cFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientCurrencyTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } for (int32_t t = 0; t < UPRV_LENGTHOF (lenientNegativeCurrencyTestCases); t += 1) { UnicodeString testCase = ctou(lenientNegativeCurrencyTestCases[t]); cFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != -1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativeCurrencyTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete cFormat; } NumberFormat *pFormat = NumberFormat::createPercentInstance(en_US, status); if (pFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat::createPercentInstance (en_US) - %s", u_errorName(status)); } else { pFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientPercentTestCases); t += 1) { UnicodeString testCase = ctou(lenientPercentTestCases[t]); pFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != 0.25) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientPercentTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } } for (int32_t t = 0; t < UPRV_LENGTHOF (lenientNegativePercentTestCases); t += 1) { UnicodeString testCase = ctou(lenientNegativePercentTestCases[t]); pFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != -0.25) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativePercentTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } } delete pFormat; } // Test cases that should fail with a strict parse and pass with a // lenient parse. NumberFormat *nFormat = NumberFormat::createInstance(en_US, status); if (nFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US) - %s", u_errorName(status)); } else { // first, make sure that they fail with a strict parse for (int32_t t = 0; t < UPRV_LENGTHOF(strictFailureTestCases); t += 1) { UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (! U_FAILURE(status)) { errln((UnicodeString)"Strict Parse succeeded for \"" + (UnicodeString) strictFailureTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); } status = U_ZERO_ERROR; } // then, make sure that they pass with a lenient parse nFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(strictFailureTestCases); t += 1) { UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) strictFailureTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete nFormat; } } // ------------------------------------- /** * Test proper rounding by the format method. */ void NumberFormatTest::TestRounding487(void) { UErrorCode status = U_ZERO_ERROR; NumberFormat *nf = NumberFormat::createInstance(status); if (U_FAILURE(status)) { dataerrln("Error calling NumberFormat::createInstance()"); return; } roundingTest(*nf, 0.00159999, 4, "0.0016"); roundingTest(*nf, 0.00995, 4, "0.01"); roundingTest(*nf, 12.3995, 3, "12.4"); roundingTest(*nf, 12.4999, 0, "12"); roundingTest(*nf, - 19.5, 0, "-20"); delete nf; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + (int32_t)status); } /** * Test the functioning of the secondary grouping value. */ void NumberFormatTest::TestSecondaryGrouping(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols ct"); DecimalFormat f("#,##,###", US, status); CHECK(status, "DecimalFormat ct"); expect2(f, (int32_t)123456789L, "12,34,56,789"); expectPat(f, "#,##,##0"); f.applyPattern("#,###", status); CHECK(status, "applyPattern"); f.setSecondaryGroupingSize(4); expect2(f, (int32_t)123456789L, "12,3456,789"); expectPat(f, "#,####,##0"); NumberFormat *g = NumberFormat::createInstance(Locale("hi", "IN"), status); CHECK_DATA(status, "createInstance(hi_IN)"); UnicodeString out; int32_t l = (int32_t)1876543210L; g->format(l, out); delete g; // expect "1,87,65,43,210", but with Hindi digits // 01234567890123 UBool ok = TRUE; if (out.length() != 14) { ok = FALSE; } else { for (int32_t i=0; i<out.length(); ++i) { UBool expectGroup = FALSE; switch (i) { case 1: case 4: case 7: case 10: expectGroup = TRUE; break; } // Later -- fix this to get the actual grouping // character from the resource bundle. UBool isGroup = (out.charAt(i) == 0x002C); if (isGroup != expectGroup) { ok = FALSE; break; } } } if (!ok) { errln((UnicodeString)"FAIL Expected " + l + " x hi_IN -> \"1,87,65,43,210\" (with Hindi digits), got \"" + escape(out) + "\""); } else { logln((UnicodeString)"Ok " + l + " x hi_IN -> \"" + escape(out) + "\""); } } void NumberFormatTest::TestWhiteSpaceParsing(void) { UErrorCode ec = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), ec); DecimalFormat fmt("a b#0c ", US, ec); if (U_FAILURE(ec)) { errcheckln(ec, "FAIL: Constructor - %s", u_errorName(ec)); return; } // From ICU 62, flexible whitespace needs lenient mode fmt.setLenient(TRUE); int32_t n = 1234; expect(fmt, "a b1234c ", n); expect(fmt, "a b1234c ", n); } /** * Test currencies whose display name is a ChoiceFormat. */ void NumberFormatTest::TestComplexCurrency() { // UErrorCode ec = U_ZERO_ERROR; // Locale loc("kn", "IN", ""); // NumberFormat* fmt = NumberFormat::createCurrencyInstance(loc, ec); // if (U_SUCCESS(ec)) { // expect2(*fmt, 1.0, CharsToUnicodeString("Re.\\u00A01.00")); // Use .00392625 because that's 2^-8. Any value less than 0.005 is fine. // expect(*fmt, 1.00390625, CharsToUnicodeString("Re.\\u00A01.00")); // tricky // expect2(*fmt, 12345678.0, CharsToUnicodeString("Rs.\\u00A01,23,45,678.00")); // expect2(*fmt, 0.5, CharsToUnicodeString("Rs.\\u00A00.50")); // expect2(*fmt, -1.0, CharsToUnicodeString("-Re.\\u00A01.00")); // expect2(*fmt, -10.0, CharsToUnicodeString("-Rs.\\u00A010.00")); // } else { // errln("FAIL: getCurrencyInstance(kn_IN)"); // } // delete fmt; } // ------------------------------------- void NumberFormatTest::roundingTest(NumberFormat& nf, double x, int32_t maxFractionDigits, const char* expected) { nf.setMaximumFractionDigits(maxFractionDigits); UnicodeString out; nf.format(x, out); logln((UnicodeString)"" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!(out==expected)) errln((UnicodeString)"FAIL: Expected " + expected); } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestExponent(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat fmt1(UnicodeString("0.###E0"), US, status); CHECK(status, "DecimalFormat(0.###E0)"); DecimalFormat fmt2(UnicodeString("0.###E+0"), US, status); CHECK(status, "DecimalFormat(0.###E+0)"); int32_t n = 1234; expect2(fmt1, n, "1.234E3"); expect2(fmt2, n, "1.234E+3"); expect(fmt1, "1.234E+3", n); // Either format should parse "E+3" } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestScientific(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); // Test pattern round-trip const char* PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; int32_t PAT_length = UPRV_LENGTHOF(PAT); int32_t DIGITS[] = { // min int, max int, min frac, max frac 1, 1, 0, 0, // "#E0" 1, 1, 0, 4, // "0.####E0" 2, 2, 3, 3, // "00.000E00" 1, 3, 0, 4, // "##0.####E000" 1, 1, 0, 3, // "0.###E0;[0.###E0]" }; for (int32_t i=0; i<PAT_length; ++i) { UnicodeString pat(PAT[i]); DecimalFormat df(pat, US, status); CHECK(status, "DecimalFormat constructor"); UnicodeString pat2; df.toPattern(pat2); if (pat == pat2) { logln(UnicodeString("Ok Pattern rt \"") + pat + "\" -> \"" + pat2 + "\""); } else { errln(UnicodeString("FAIL Pattern rt \"") + pat + "\" -> \"" + pat2 + "\""); } // Make sure digit counts match what we expect if (df.getMinimumIntegerDigits() != DIGITS[4*i] || df.getMaximumIntegerDigits() != DIGITS[4*i+1] || df.getMinimumFractionDigits() != DIGITS[4*i+2] || df.getMaximumFractionDigits() != DIGITS[4*i+3]) { errln(UnicodeString("FAIL \"" + pat + "\" min/max int; min/max frac = ") + df.getMinimumIntegerDigits() + "/" + df.getMaximumIntegerDigits() + ";" + df.getMinimumFractionDigits() + "/" + df.getMaximumFractionDigits() + ", expect " + DIGITS[4*i] + "/" + DIGITS[4*i+1] + ";" + DIGITS[4*i+2] + "/" + DIGITS[4*i+3]); } } // Test the constructor for default locale. We have to // manually set the default locale, as there is no // guarantee that the default locale has the same // scientific format. Locale def = Locale::getDefault(); Locale::setDefault(Locale::getUS(), status); expect2(NumberFormat::createScientificInstance(status), 12345.678901, "1.2345678901E4", status); Locale::setDefault(def, status); expect2(new DecimalFormat("#E0", US, status), 12345.0, "1.2345E4", status); expect(new DecimalFormat("0E0", US, status), 12345.0, "1E4", status); expect2(NumberFormat::createScientificInstance(Locale::getUS(), status), 12345.678901, "1.2345678901E4", status); expect(new DecimalFormat("##0.###E0", US, status), 12345.0, "12.34E3", status); expect(new DecimalFormat("##0.###E0", US, status), 12345.00001, "12.35E3", status); expect2(new DecimalFormat("##0.####E0", US, status), (int32_t) 12345, "12.345E3", status); expect2(NumberFormat::createScientificInstance(Locale::getFrance(), status), 12345.678901, "1,2345678901E4", status); expect(new DecimalFormat("##0.####E0", US, status), 789.12345e-9, "789.12E-9", status); expect2(new DecimalFormat("##0.####E0", US, status), 780.e-9, "780E-9", status); expect(new DecimalFormat(".###E0", US, status), 45678.0, ".457E5", status); expect2(new DecimalFormat(".###E0", US, status), (int32_t) 0, ".0E0", status); /* expect(new DecimalFormat[] { new DecimalFormat("#E0", US), new DecimalFormat("##E0", US), new DecimalFormat("####E0", US), new DecimalFormat("0E0", US), new DecimalFormat("00E0", US), new DecimalFormat("000E0", US), }, new Long(45678000), new String[] { "4.5678E7", "45.678E6", "4567.8E4", "5E7", "46E6", "457E5", } ); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("#E0", US, status), (int32_t) 45678000, "4.5678E7", status); expect2(new DecimalFormat("##E0", US, status), (int32_t) 45678000, "45.678E6", status); expect2(new DecimalFormat("####E0", US, status), (int32_t) 45678000, "4567.8E4", status); expect(new DecimalFormat("0E0", US, status), (int32_t) 45678000, "5E7", status); expect(new DecimalFormat("00E0", US, status), (int32_t) 45678000, "46E6", status); expect(new DecimalFormat("000E0", US, status), (int32_t) 45678000, "457E5", status); /* expect(new DecimalFormat("###E0", US, status), new Object[] { new Double(0.0000123), "12.3E-6", new Double(0.000123), "123E-6", new Double(0.00123), "1.23E-3", new Double(0.0123), "12.3E-3", new Double(0.123), "123E-3", new Double(1.23), "1.23E0", new Double(12.3), "12.3E0", new Double(123), "123E0", new Double(1230), "1.23E3", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("###E0", US, status), 0.0000123, "12.3E-6", status); expect2(new DecimalFormat("###E0", US, status), 0.000123, "123E-6", status); expect2(new DecimalFormat("###E0", US, status), 0.00123, "1.23E-3", status); expect2(new DecimalFormat("###E0", US, status), 0.0123, "12.3E-3", status); expect2(new DecimalFormat("###E0", US, status), 0.123, "123E-3", status); expect2(new DecimalFormat("###E0", US, status), 1.23, "1.23E0", status); expect2(new DecimalFormat("###E0", US, status), 12.3, "12.3E0", status); expect2(new DecimalFormat("###E0", US, status), 123.0, "123E0", status); expect2(new DecimalFormat("###E0", US, status), 1230.0, "1.23E3", status); /* expect(new DecimalFormat("0.#E+00", US, status), new Object[] { new Double(0.00012), "1.2E-04", new Long(12000), "1.2E+04", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("0.#E+00", US, status), 0.00012, "1.2E-04", status); expect2(new DecimalFormat("0.#E+00", US, status), (int32_t) 12000, "1.2E+04", status); } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestPad(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); expect2(new DecimalFormat("*^##.##", US, status), int32_t(0), "^^^^0", status); expect2(new DecimalFormat("*^##.##", US, status), -1.3, "^-1.3", status); expect2(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), int32_t(0), "0.0E0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), 1.0/3, "333.333E-3_ g-m/s^2", status); expect2(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), int32_t(0), "0.0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), 1.0/3, "0.33333__ g-m/s^2", status); // Test padding before a sign const char *formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)"; expect2(new DecimalFormat(formatStr, US, status), int32_t(-10), "xxxxxxxxxx(10.0)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(-1000),"xxxxxxx(1,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(-1000000),"xxx(1,000,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), -100.37, "xxxxxxxx(100.37)", status); expect2(new DecimalFormat(formatStr, US, status), -10456.37, "xxxxx(10,456.37)", status); expect2(new DecimalFormat(formatStr, US, status), -1120456.37, "xx(1,120,456.37)", status); expect2(new DecimalFormat(formatStr, US, status), -112045600.37, "(112,045,600.37)", status); expect2(new DecimalFormat(formatStr, US, status), -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(10), "xxxxxxxxxxxx10.0", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(1000),"xxxxxxxxx1,000.0", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(1000000),"xxxxx1,000,000.0", status); expect2(new DecimalFormat(formatStr, US, status), 100.37, "xxxxxxxxxx100.37", status); expect2(new DecimalFormat(formatStr, US, status), 10456.37, "xxxxxxx10,456.37", status); expect2(new DecimalFormat(formatStr, US, status), 1120456.37, "xxxx1,120,456.37", status); expect2(new DecimalFormat(formatStr, US, status), 112045600.37, "xx112,045,600.37", status); expect2(new DecimalFormat(formatStr, US, status), 10252045600.37,"10,252,045,600.37", status); // Test padding between a sign and a number const char *formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)"; expect2(new DecimalFormat(formatStr2, US, status), int32_t(-10), "(10.0xxxxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(-1000),"(1,000.0xxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(-1000000),"(1,000,000.0xxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -100.37, "(100.37xxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -10456.37, "(10,456.37xxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -1120456.37, "(1,120,456.37xx)", status); expect2(new DecimalFormat(formatStr2, US, status), -112045600.37, "(112,045,600.37)", status); expect2(new DecimalFormat(formatStr2, US, status), -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(10), "10.0xxxxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(1000),"1,000.0xxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(1000000),"1,000,000.0xxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 100.37, "100.37xxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 10456.37, "10,456.37xxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 1120456.37, "1,120,456.37xxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 112045600.37, "112,045,600.37xx", status); expect2(new DecimalFormat(formatStr2, US, status), 10252045600.37,"10,252,045,600.37", status); //testing the setPadCharacter(UnicodeString) and getPadCharacterString() DecimalFormat fmt("#", US, status); CHECK(status, "DecimalFormat constructor"); UnicodeString padString("P"); fmt.setPadCharacter(padString); expectPad(fmt, "*P##.##", DecimalFormat::kPadBeforePrefix, 5, padString); fmt.setPadCharacter((UnicodeString)"^"); expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, (UnicodeString)"^"); //commented untill implementation is complete /* fmt.setPadCharacter((UnicodeString)"^^^"); expectPad(fmt, "*^^^#", DecimalFormat::kPadBeforePrefix, 3, (UnicodeString)"^^^"); padString.remove(); padString.append((UChar)0x0061); padString.append((UChar)0x0302); fmt.setPadCharacter(padString); UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000}; UnicodeString pattern(patternChars); expectPad(fmt, pattern , DecimalFormat::kPadBeforePrefix, 4, padString); */ } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestPatterns2(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat fmt("#", US, status); CHECK(status, "DecimalFormat constructor"); UChar hat = 0x005E; /*^*/ expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, hat); expectPad(fmt, "$*^#", DecimalFormat::kPadAfterPrefix, 2, hat); expectPad(fmt, "#*^", DecimalFormat::kPadBeforeSuffix, 1, hat); expectPad(fmt, "#$*^", DecimalFormat::kPadAfterSuffix, 2, hat); expectPad(fmt, "$*^$#", ILLEGAL); expectPad(fmt, "#$*^$", ILLEGAL); expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat::kPadBeforeSuffix, 12, (UChar)0x0078 /*x*/); expectPad(fmt, "''#0*x", DecimalFormat::kPadBeforeSuffix, 3, (UChar)0x0078 /*x*/); expectPad(fmt, "'I''ll'*a###.##", DecimalFormat::kPadAfterPrefix, 10, (UChar)0x0061 /*a*/); fmt.applyPattern("AA#,##0.00ZZ", status); CHECK(status, "applyPattern"); fmt.setPadCharacter(hat); fmt.setFormatWidth(10); fmt.setPadPosition(DecimalFormat::kPadBeforePrefix); expectPat(fmt, "*^AA#,##0.00ZZ"); fmt.setPadPosition(DecimalFormat::kPadBeforeSuffix); expectPat(fmt, "AA#,##0.00*^ZZ"); fmt.setPadPosition(DecimalFormat::kPadAfterSuffix); expectPat(fmt, "AA#,##0.00ZZ*^"); // 12 3456789012 UnicodeString exp("AA*^#,##0.00ZZ", ""); fmt.setFormatWidth(12); fmt.setPadPosition(DecimalFormat::kPadAfterPrefix); expectPat(fmt, exp); fmt.setFormatWidth(13); // 12 34567890123 expectPat(fmt, "AA*^##,##0.00ZZ"); fmt.setFormatWidth(14); // 12 345678901234 expectPat(fmt, "AA*^###,##0.00ZZ"); fmt.setFormatWidth(15); // 12 3456789012345 expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case fmt.setFormatWidth(16); // 12 34567890123456 expectPat(fmt, "AA*^#####,##0.00ZZ"); } void NumberFormatTest::TestSurrogateSupport(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols custom(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); custom.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, "decimal"); custom.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, "plus"); custom.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, " minus "); custom.setSymbol(DecimalFormatSymbols::kExponentialSymbol, "exponent"); UnicodeString patternStr("*\\U00010000##.##", ""); patternStr = patternStr.unescape(); UnicodeString expStr("\\U00010000\\U00010000\\U00010000\\U000100000", ""); expStr = expStr.unescape(); expect2(new DecimalFormat(patternStr, custom, status), int32_t(0), expStr, status); status = U_ZERO_ERROR; expect2(new DecimalFormat("*^##.##", custom, status), int32_t(0), "^^^^0", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##.##", custom, status), -1.3, " minus 1decimal3", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), int32_t(0), "0decimal0exponent0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), 1.0/3, "333decimal333exponent minus 3 g-m/s^2", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), int32_t(0), "0decimal0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), 1.0/3, "0decimal33333 g-m/s^2", status); UnicodeString zero((UChar32)0x10000); UnicodeString one((UChar32)0x10001); UnicodeString two((UChar32)0x10002); UnicodeString five((UChar32)0x10005); custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, zero); custom.setSymbol(DecimalFormatSymbols::kOneDigitSymbol, one); custom.setSymbol(DecimalFormatSymbols::kTwoDigitSymbol, two); custom.setSymbol(DecimalFormatSymbols::kFiveDigitSymbol, five); expStr = UnicodeString("\\U00010001decimal\\U00010002\\U00010005\\U00010000", ""); expStr = expStr.unescape(); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.000", custom, status), 1.25, expStr, status); custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, (UChar)0x30); custom.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "units of money"); custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, "money separator"); patternStr = UNICODE_STRING_SIMPLE("0.00 \\u00A4' in your bank account'"); patternStr = patternStr.unescape(); expStr = UnicodeString(" minus 20money separator00 units of money in your bank account", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), int32_t(-20), expStr, status); custom.setSymbol(DecimalFormatSymbols::kPercentSymbol, "percent"); patternStr = "'You''ve lost ' -0.00 %' of your money today'"; patternStr = patternStr.unescape(); expStr = UnicodeString(" minus You've lost minus 2000decimal00 percent of your money today", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), int32_t(-20), expStr, status); } void NumberFormatTest::TestCurrencyPatterns(void) { int32_t i, locCount; const Locale* locs = NumberFormat::getAvailableLocales(locCount); for (i=0; i<locCount; ++i) { UErrorCode ec = U_ZERO_ERROR; NumberFormat* nf = NumberFormat::createCurrencyInstance(locs[i], ec); if (U_FAILURE(ec)) { errln("FAIL: Can't create NumberFormat(%s) - %s", locs[i].getName(), u_errorName(ec)); } else { // Make sure currency formats do not have a variable number // of fraction digits int32_t min = nf->getMinimumFractionDigits(); int32_t max = nf->getMaximumFractionDigits(); if (min != max) { UnicodeString a, b; nf->format(1.0, a); nf->format(1.125, b); errln((UnicodeString)"FAIL: " + locs[i].getName() + " min fraction digits != max fraction digits; " "x 1.0 => " + escape(a) + "; x 1.125 => " + escape(b)); } // Make sure EURO currency formats have exactly 2 fraction digits DecimalFormat* df = dynamic_cast<DecimalFormat*>(nf); if (df != NULL) { if (u_strcmp(EUR, df->getCurrency()) == 0) { if (min != 2 || max != 2) { UnicodeString a; nf->format(1.0, a); errln((UnicodeString)"FAIL: " + locs[i].getName() + " is a EURO format but it does not have 2 fraction digits; " "x 1.0 => " + escape(a)); } } } } delete nf; } } void NumberFormatTest::TestRegCurrency(void) { #if !UCONFIG_NO_SERVICE UErrorCode status = U_ZERO_ERROR; UChar USD[4]; ucurr_forLocale("en_US", USD, 4, &status); UChar YEN[4]; ucurr_forLocale("ja_JP", YEN, 4, &status); UChar TMP[4]; static const UChar QQQ[] = {0x51, 0x51, 0x51, 0}; if(U_FAILURE(status)) { errcheckln(status, "Unable to get currency for locale, error %s", u_errorName(status)); return; } UCurrRegistryKey enkey = ucurr_register(YEN, "en_US", &status); UCurrRegistryKey enUSEUROkey = ucurr_register(QQQ, "en_US_EURO", &status); ucurr_forLocale("en_US", TMP, 4, &status); if (u_strcmp(YEN, TMP) != 0) { errln("FAIL: didn't return YEN registered for en_US"); } ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(QQQ, TMP) != 0) { errln("FAIL: didn't return QQQ for en_US_EURO"); } int32_t fallbackLen = ucurr_forLocale("en_XX_BAR", TMP, 4, &status); if (fallbackLen) { errln("FAIL: tried to fallback en_XX_BAR"); } status = U_ZERO_ERROR; // reset if (!ucurr_unregister(enkey, &status)) { errln("FAIL: couldn't unregister enkey"); } ucurr_forLocale("en_US", TMP, 4, &status); if (u_strcmp(USD, TMP) != 0) { errln("FAIL: didn't return USD for en_US after unregister of en_US"); } status = U_ZERO_ERROR; // reset ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(QQQ, TMP) != 0) { errln("FAIL: didn't return QQQ for en_US_EURO after unregister of en_US"); } ucurr_forLocale("en_US_BLAH", TMP, 4, &status); if (u_strcmp(USD, TMP) != 0) { errln("FAIL: could not find USD for en_US_BLAH after unregister of en"); } status = U_ZERO_ERROR; // reset if (!ucurr_unregister(enUSEUROkey, &status)) { errln("FAIL: couldn't unregister enUSEUROkey"); } ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(EUR, TMP) != 0) { errln("FAIL: didn't return EUR for en_US_EURO after unregister of en_US_EURO"); } status = U_ZERO_ERROR; // reset #endif } void NumberFormatTest::TestCurrencyNames(void) { // Do a basic check of getName() // USD { "US$", "US Dollar" } // 04/04/1792- UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = {0x55, 0x53, 0x44, 0}; /*USD*/ static const UChar USX[] = {0x55, 0x53, 0x58, 0}; /*USX*/ static const UChar CAD[] = {0x43, 0x41, 0x44, 0}; /*CAD*/ static const UChar ITL[] = {0x49, 0x54, 0x4C, 0}; /*ITL*/ UBool isChoiceFormat; int32_t len; const UBool possibleDataError = TRUE; // Warning: HARD-CODED LOCALE DATA in this test. If it fails, CHECK // THE LOCALE DATA before diving into the code. assertEquals("USD.getName(SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(NARROW_SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(LONG_NAME, en)", UnicodeString("US Dollar"), UnicodeString(ucurr_getName(USD, "en", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME, en)", UnicodeString("CA$"), UnicodeString(ucurr_getName(CAD, "en", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(NARROW_SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(CAD, "en", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME, en_CA)", UnicodeString("$"), UnicodeString(ucurr_getName(CAD, "en_CA", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(SYMBOL_NAME, en_CA)", UnicodeString("US$"), UnicodeString(ucurr_getName(USD, "en_CA", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(NARROW_SYMBOL_NAME, en_CA)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en_CA", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(SYMBOL_NAME) in en_NZ", UnicodeString("US$"), UnicodeString(ucurr_getName(USD, "en_NZ", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME)", UnicodeString("CA$"), UnicodeString(ucurr_getName(CAD, "en_NZ", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(SYMBOL_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(NARROW_SYMBOL_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(LONG_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertSuccess("ucurr_getName", ec); ec = U_ZERO_ERROR; // Test that a default or fallback warning is being returned. JB 4239. ucurr_getName(CAD, "es_ES", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (es_ES fallback)", U_USING_FALLBACK_WARNING == ec, TRUE, possibleDataError); ucurr_getName(CAD, "zh_TW", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (zh_TW fallback)", U_USING_FALLBACK_WARNING == ec, TRUE, possibleDataError); ucurr_getName(CAD, "en_US", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (en_US default)", U_USING_DEFAULT_WARNING == ec || U_USING_FALLBACK_WARNING == ec, TRUE); ucurr_getName(CAD, "ti", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (ti default)", U_USING_DEFAULT_WARNING == ec, TRUE); // Test that a default warning is being returned when falling back to root. JB 4536. ucurr_getName(ITL, "cy", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (cy default to root)", U_USING_DEFAULT_WARNING == ec, TRUE); // TODO add more tests later } void NumberFormatTest::TestCurrencyUnit(void){ UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = u"USD"; static const char USD8[] = "USD"; static const UChar BAD[] = u"???"; static const UChar BAD2[] = u"??A"; static const UChar XXX[] = u"XXX"; static const char XXX8[] = "XXX"; CurrencyUnit cu(USD, ec); assertSuccess("CurrencyUnit", ec); assertEquals("getISOCurrency()", USD, cu.getISOCurrency()); assertEquals("getSubtype()", USD8, cu.getSubtype()); CurrencyUnit cu2(cu); if (!(cu2 == cu)){ errln("CurrencyUnit copy constructed object should be same"); } CurrencyUnit * cu3 = (CurrencyUnit *)cu.clone(); if (!(*cu3 == cu)){ errln("CurrencyUnit cloned object should be same"); } CurrencyUnit bad(BAD, ec); assertSuccess("CurrencyUnit", ec); if (cu.getIndex() == bad.getIndex()) { errln("Indexes of different currencies should differ."); } CurrencyUnit bad2(BAD2, ec); assertSuccess("CurrencyUnit", ec); if (bad2.getIndex() != bad.getIndex()) { errln("Indexes of unrecognized currencies should be the same."); } if (bad == bad2) { errln("Different unrecognized currencies should not be equal."); } bad = bad2; if (bad != bad2) { errln("Currency unit assignment should be the same."); } delete cu3; // Test default constructor CurrencyUnit def; assertEquals("Default currency", XXX, def.getISOCurrency()); assertEquals("Default currency as subtype", XXX8, def.getSubtype()); // Test slicing MeasureUnit sliced1 = cu; MeasureUnit sliced2 = cu; assertEquals("Subtype after slicing 1", USD8, sliced1.getSubtype()); assertEquals("Subtype after slicing 2", USD8, sliced2.getSubtype()); CurrencyUnit restored1(sliced1, ec); CurrencyUnit restored2(sliced2, ec); assertSuccess("Restoring from MeasureUnit", ec); assertEquals("Subtype after restoring 1", USD8, restored1.getSubtype()); assertEquals("Subtype after restoring 2", USD8, restored2.getSubtype()); assertEquals("ISO Code after restoring 1", USD, restored1.getISOCurrency()); assertEquals("ISO Code after restoring 2", USD, restored2.getISOCurrency()); // Test copy constructor failure LocalPointer<MeasureUnit> meter(MeasureUnit::createMeter(ec)); assertSuccess("Creating meter", ec); CurrencyUnit failure(*meter, ec); assertEquals("Copying from meter should fail", ec, U_ILLEGAL_ARGUMENT_ERROR); assertEquals("Copying should not give uninitialized ISO code", u"", failure.getISOCurrency()); } void NumberFormatTest::TestCurrencyAmount(void){ UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = {85, 83, 68, 0}; /*USD*/ CurrencyAmount ca(9, USD, ec); assertSuccess("CurrencyAmount", ec); CurrencyAmount ca2(ca); if (!(ca2 == ca)){ errln("CurrencyAmount copy constructed object should be same"); } ca2=ca; if (!(ca2 == ca)){ errln("CurrencyAmount assigned object should be same"); } CurrencyAmount *ca3 = (CurrencyAmount *)ca.clone(); if (!(*ca3 == ca)){ errln("CurrencyAmount cloned object should be same"); } delete ca3; } void NumberFormatTest::TestSymbolsWithBadLocale(void) { Locale locDefault; static const char *badLocales[] = { // length < ULOC_FULLNAME_CAPACITY "x-crazy_ZZ_MY_SPECIAL_ADMINISTRATION_REGION_NEEDS_A_SPECIAL_VARIANT_WITH_A_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_LONG_NAME", // length > ULOC_FULLNAME_CAPACITY "x-crazy_ZZ_MY_SPECIAL_ADMINISTRATION_REGION_NEEDS_A_SPECIAL_VARIANT_WITH_A_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_LONG_NAME" }; // expect U_USING_DEFAULT_WARNING for both unsigned int i; for (i = 0; i < UPRV_LENGTHOF(badLocales); i++) { const char *localeName = badLocales[i]; Locale locBad(localeName); TEST_ASSERT_TRUE(!locBad.isBogus()); UErrorCode status = U_ZERO_ERROR; UnicodeString intlCurrencySymbol((UChar)0xa4); intlCurrencySymbol.append((UChar)0xa4); logln("Current locale is %s", Locale::getDefault().getName()); Locale::setDefault(locBad, status); logln("Current locale is %s", Locale::getDefault().getName()); DecimalFormatSymbols mySymbols(status); if (status != U_USING_DEFAULT_WARNING) { errln("DecimalFormatSymbols should return U_USING_DEFAULT_WARNING."); } if (strcmp(mySymbols.getLocale().getName(), locBad.getName()) != 0) { errln("DecimalFormatSymbols does not have the right locale.", locBad.getName()); } int symbolEnum = (int)DecimalFormatSymbols::kDecimalSeparatorSymbol; for (; symbolEnum < (int)DecimalFormatSymbols::kFormatSymbolCount; symbolEnum++) { UnicodeString symbolString = mySymbols.getSymbol((DecimalFormatSymbols::ENumberFormatSymbol)symbolEnum); logln(UnicodeString("DecimalFormatSymbols[") + symbolEnum + UnicodeString("] = ") + prettify(symbolString)); if (symbolString.length() == 0 && symbolEnum != (int)DecimalFormatSymbols::kGroupingSeparatorSymbol && symbolEnum != (int)DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol) { errln("DecimalFormatSymbols has an empty string at index %d.", symbolEnum); } } status = U_ZERO_ERROR; Locale::setDefault(locDefault, status); logln("Current locale is %s", Locale::getDefault().getName()); } } /** * Check that adoptDecimalFormatSymbols and setDecimalFormatSymbols * behave the same, except for memory ownership semantics. (No * version of this test on Java, since Java has only one method.) */ void NumberFormatTest::TestAdoptDecimalFormatSymbols(void) { UErrorCode ec = U_ZERO_ERROR; DecimalFormatSymbols *sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errcheckln(ec, "Fail: DecimalFormatSymbols constructor - %s", u_errorName(ec)); delete sym; return; } UnicodeString pat(" #,##0.00"); pat.insert(0, (UChar)0x00A4); DecimalFormat fmt(pat, sym, ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormat constructor"); return; } UnicodeString str; fmt.format(2350.75, str); if (str == "$ 2,350.75") { logln(str); } else { dataerrln("Fail: " + str + ", expected $ 2,350.75"); } sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); delete sym; return; } sym->setSymbol(DecimalFormatSymbols::kCurrencySymbol, "Q"); fmt.adoptDecimalFormatSymbols(sym); str.truncate(0); fmt.format(2350.75, str); if (str == "Q 2,350.75") { logln(str); } else { dataerrln("Fail: adoptDecimalFormatSymbols -> " + str + ", expected Q 2,350.75"); } sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); delete sym; return; } DecimalFormat fmt2(pat, sym, ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormat constructor"); return; } DecimalFormatSymbols sym2(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); return; } sym2.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "Q"); fmt2.setDecimalFormatSymbols(sym2); str.truncate(0); fmt2.format(2350.75, str); if (str == "Q 2,350.75") { logln(str); } else { dataerrln("Fail: setDecimalFormatSymbols -> " + str + ", expected Q 2,350.75"); } } void NumberFormatTest::TestPerMill() { UErrorCode ec = U_ZERO_ERROR; UnicodeString str; DecimalFormat fmt(ctou("###.###\\u2030"), ec); if (!assertSuccess("DecimalFormat ct", ec)) return; assertEquals("0.4857 x ###.###\\u2030", ctou("485.7\\u2030"), fmt.format(0.4857, str), true); DecimalFormatSymbols sym(Locale::getUS(), ec); if (!assertSuccess("", ec, true, __FILE__, __LINE__)) { return; } sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, ctou("m")); DecimalFormat fmt2("", sym, ec); if (!assertSuccess("", ec, true, __FILE__, __LINE__)) { return; } fmt2.applyLocalizedPattern("###.###m", ec); if (!assertSuccess("setup", ec)) return; str.truncate(0); assertEquals("0.4857 x ###.###m", "485.7m", fmt2.format(0.4857, str)); } /** * Generic test for patterns that should be legal/illegal. */ void NumberFormatTest::TestIllegalPatterns() { // Test cases: // Prefix with "-:" for illegal patterns // Prefix with "+:" for legal patterns const char* DATA[] = { // Unquoted special characters in the suffix are illegal "-:000.000|###", "+:000.000'|###'", 0 }; for (int32_t i=0; DATA[i]; ++i) { const char* pat=DATA[i]; UBool valid = (*pat) == '+'; pat += 2; UErrorCode ec = U_ZERO_ERROR; DecimalFormat fmt(pat, ec); // locale doesn't matter here if (U_SUCCESS(ec) == valid) { logln("Ok: pattern \"%s\": %s", pat, u_errorName(ec)); } else { errcheckln(ec, "FAIL: pattern \"%s\" should have %s; got %s", pat, (valid?"succeeded":"failed"), u_errorName(ec)); } } } //---------------------------------------------------------------------- static const char* KEYWORDS[] = { /*0*/ "ref=", // <reference pattern to parse numbers> /*1*/ "loc=", // <locale for formats> /*2*/ "f:", // <pattern or '-'> <number> <exp. string> /*3*/ "fp:", // <pattern or '-'> <number> <exp. string> <exp. number> /*4*/ "rt:", // <pattern or '-'> <(exp.) number> <(exp.) string> /*5*/ "p:", // <pattern or '-'> <string> <exp. number> /*6*/ "perr:", // <pattern or '-'> <invalid string> /*7*/ "pat:", // <pattern or '-'> <exp. toPattern or '-' or 'err'> /*8*/ "fpc:", // <pattern or '-'> <curr.amt> <exp. string> <exp. curr.amt> 0 }; /** * Return an integer representing the next token from this * iterator. The integer will be an index into the given list, or * -1 if there are no more tokens, or -2 if the token is not on * the list. */ static int32_t keywordIndex(const UnicodeString& tok) { for (int32_t i=0; KEYWORDS[i]!=0; ++i) { if (tok==KEYWORDS[i]) { return i; } } return -1; } /** * Parse a CurrencyAmount using the given NumberFormat, with * the 'delim' character separating the number and the currency. */ static void parseCurrencyAmount(const UnicodeString& str, const NumberFormat& fmt, UChar delim, Formattable& result, UErrorCode& ec) { UnicodeString num, cur; int32_t i = str.indexOf(delim); str.extractBetween(0, i, num); str.extractBetween(i+1, INT32_MAX, cur); Formattable n; fmt.parse(num, n, ec); result.adoptObject(new CurrencyAmount(n, cur.getTerminatedBuffer(), ec)); } void NumberFormatTest::TestCases() { UErrorCode ec = U_ZERO_ERROR; TextFile reader("NumberFormatTestCases.txt", "UTF8", ec); if (U_FAILURE(ec)) { dataerrln("Couldn't open NumberFormatTestCases.txt"); return; } TokenIterator tokens(&reader); Locale loc("en", "US", ""); DecimalFormat *ref = 0, *fmt = 0; MeasureFormat *mfmt = 0; UnicodeString pat, tok, mloc, str, out, where, currAmt; Formattable n; for (;;) { ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) { break; } where = UnicodeString("(") + tokens.getLineNumber() + ") "; int32_t cmd = keywordIndex(tok); switch (cmd) { case 0: // ref= <reference pattern> if (!tokens.next(tok, ec)) goto error; delete ref; ref = new DecimalFormat(tok, new DecimalFormatSymbols(Locale::getUS(), ec), ec); if (U_FAILURE(ec)) { dataerrln("Error constructing DecimalFormat"); goto error; } break; case 1: // loc= <locale> if (!tokens.next(tok, ec)) goto error; loc = Locale::createFromName(CharString().appendInvariantChars(tok, ec).data()); break; case 2: // f: case 3: // fp: case 4: // rt: case 5: // p: if (!tokens.next(tok, ec)) goto error; if (tok != "-") { pat = tok; delete fmt; fmt = new DecimalFormat(pat, new DecimalFormatSymbols(loc, ec), ec); if (U_FAILURE(ec)) { errln("FAIL: " + where + "Pattern \"" + pat + "\": " + u_errorName(ec)); ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (cmd == 3) { if (!tokens.next(tok, ec)) goto error; } continue; } } if (cmd == 2 || cmd == 3 || cmd == 4) { // f: <pattern or '-'> <number> <exp. string> // fp: <pattern or '-'> <number> <exp. string> <exp. number> // rt: <pattern or '-'> <number> <string> UnicodeString num; if (!tokens.next(num, ec)) goto error; if (!tokens.next(str, ec)) goto error; ref->parse(num, n, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".format(" + num + ")", str, fmt->format(n, out.remove(), ec)); assertSuccess("format", ec); if (cmd == 3) { // fp: if (!tokens.next(num, ec)) goto error; ref->parse(num, n, ec); assertSuccess("parse", ec); } if (cmd != 2) { // != f: Formattable m; fmt->parse(str, m, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".parse(\"" + str + "\")", n, m); } } // p: <pattern or '-'> <string to parse> <exp. number> else { UnicodeString expstr; if (!tokens.next(str, ec)) goto error; if (!tokens.next(expstr, ec)) goto error; Formattable exp, n; ref->parse(expstr, exp, ec); assertSuccess("parse", ec); fmt->parse(str, n, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".parse(\"" + str + "\")", exp, n); } break; case 8: // fpc: if (!tokens.next(tok, ec)) goto error; if (tok != "-") { mloc = tok; delete mfmt; mfmt = MeasureFormat::createCurrencyFormat( Locale::createFromName( CharString().appendInvariantChars(mloc, ec).data()), ec); if (U_FAILURE(ec)) { errln("FAIL: " + where + "Loc \"" + mloc + "\": " + u_errorName(ec)); ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; continue; } } else if (mfmt == NULL) { errln("FAIL: " + where + "Loc \"" + mloc + "\": skip case using previous locale, no valid MeasureFormat"); if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; continue; } // fpc: <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> if (!tokens.next(currAmt, ec)) goto error; if (!tokens.next(str, ec)) goto error; parseCurrencyAmount(currAmt, *ref, (UChar)0x2F/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, mfmt->format(n, out.remove(), ec)); assertSuccess("format", ec); } if (!tokens.next(currAmt, ec)) goto error; parseCurrencyAmount(currAmt, *ref, (UChar)0x2F/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { Formattable m; mfmt->parseObject(str, m, ec); if (assertSuccess("parseCurrency", ec)) { assertEquals(where + "getCurrencyFormat(" + mloc + ").parse(\"" + str + "\")", n, m); } else { errln("FAIL: source " + str); } } break; case 6: // perr: <pattern or '-'> <invalid string> errln("FAIL: Under construction"); goto done; case 7: { // pat: <pattern> <exp. toPattern, or '-' or 'err'> UnicodeString testpat; UnicodeString exppat; if (!tokens.next(testpat, ec)) goto error; if (!tokens.next(exppat, ec)) goto error; UBool err = exppat == "err"; UBool existingPat = FALSE; if (testpat == "-") { if (err) { errln("FAIL: " + where + "Invalid command \"pat: - err\""); continue; } existingPat = TRUE; testpat = pat; } if (exppat == "-") exppat = testpat; DecimalFormat* f = 0; UErrorCode ec2 = U_ZERO_ERROR; if (existingPat) { f = fmt; } else { f = new DecimalFormat(testpat, ec2); } if (U_SUCCESS(ec2)) { if (err) { errln("FAIL: " + where + "Invalid pattern \"" + testpat + "\" was accepted"); } else { UnicodeString pat2; assertEquals(where + "\"" + testpat + "\".toPattern()", exppat, f->toPattern(pat2)); } } else { if (err) { logln("Ok: " + where + "Invalid pattern \"" + testpat + "\" failed: " + u_errorName(ec2)); } else { errln("FAIL: " + where + "Valid pattern \"" + testpat + "\" failed: " + u_errorName(ec2)); } } if (!existingPat) delete f; } break; case -1: errln("FAIL: " + where + "Unknown command \"" + tok + "\""); goto done; } } goto done; error: if (U_SUCCESS(ec)) { errln("FAIL: Unexpected EOF"); } else { errcheckln(ec, "FAIL: " + where + "Unexpected " + u_errorName(ec)); } done: delete mfmt; delete fmt; delete ref; } //---------------------------------------------------------------------- // Support methods //---------------------------------------------------------------------- UBool NumberFormatTest::equalValue(const Formattable& a, const Formattable& b) { if (a.getType() == b.getType()) { return a == b; } if (a.getType() == Formattable::kLong) { if (b.getType() == Formattable::kInt64) { return a.getLong() == b.getLong(); } else if (b.getType() == Formattable::kDouble) { return (double) a.getLong() == b.getDouble(); // TODO check use of double instead of long } } else if (a.getType() == Formattable::kDouble) { if (b.getType() == Formattable::kLong) { return a.getDouble() == (double) b.getLong(); } else if (b.getType() == Formattable::kInt64) { return a.getDouble() == (double)b.getInt64(); } } else if (a.getType() == Formattable::kInt64) { if (b.getType() == Formattable::kLong) { return a.getInt64() == (int64_t)b.getLong(); } else if (b.getType() == Formattable::kDouble) { return a.getInt64() == (int64_t)b.getDouble(); } } return FALSE; } void NumberFormatTest::expect3(NumberFormat& fmt, const Formattable& n, const UnicodeString& str) { // Don't round-trip format test, since we explicitly do it expect_rbnf(fmt, n, str, FALSE); expect_rbnf(fmt, str, n); } void NumberFormatTest::expect2(NumberFormat& fmt, const Formattable& n, const UnicodeString& str) { // Don't round-trip format test, since we explicitly do it expect(fmt, n, str, FALSE); expect(fmt, str, n); } void NumberFormatTest::expect2(NumberFormat* fmt, const Formattable& n, const UnicodeString& exp, UErrorCode status) { if (fmt == NULL || U_FAILURE(status)) { dataerrln("FAIL: NumberFormat constructor"); } else { expect2(*fmt, n, exp); } delete fmt; } void NumberFormatTest::expect(NumberFormat& fmt, const UnicodeString& str, const Formattable& n) { UErrorCode status = U_ZERO_ERROR; Formattable num; fmt.parse(str, num, status); if (U_FAILURE(status)) { dataerrln(UnicodeString("FAIL: Parse failed for \"") + str + "\" - " + u_errorName(status)); return; } UnicodeString pat; ((DecimalFormat*) &fmt)->toPattern(pat); if (equalValue(num, n)) { logln(UnicodeString("Ok \"") + str + "\" x " + pat + " = " + toString(num)); } else { dataerrln(UnicodeString("FAIL \"") + str + "\" x " + pat + " = " + toString(num) + ", expected " + toString(n)); } } void NumberFormatTest::expect_rbnf(NumberFormat& fmt, const UnicodeString& str, const Formattable& n) { UErrorCode status = U_ZERO_ERROR; Formattable num; fmt.parse(str, num, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + str + "\""); return; } if (equalValue(num, n)) { logln(UnicodeString("Ok \"") + str + " = " + toString(num)); } else { errln(UnicodeString("FAIL \"") + str + " = " + toString(num) + ", expected " + toString(n)); } } void NumberFormatTest::expect_rbnf(NumberFormat& fmt, const Formattable& n, const UnicodeString& exp, UBool rt) { UnicodeString saw; FieldPosition pos; UErrorCode status = U_ZERO_ERROR; fmt.format(n, saw, pos, status); CHECK(status, "NumberFormat::format"); if (saw == exp) { logln(UnicodeString("Ok ") + toString(n) + " = \"" + escape(saw) + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { Formattable n2; fmt.parse(exp, n2, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + exp + "\""); return; } UnicodeString saw2; fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } } else { errln(UnicodeString("FAIL ") + toString(n) + " = \"" + escape(saw) + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expect(NumberFormat& fmt, const Formattable& n, const UnicodeString& exp, UBool rt) { UnicodeString saw; FieldPosition pos; UErrorCode status = U_ZERO_ERROR; fmt.format(n, saw, pos, status); CHECK(status, "NumberFormat::format"); UnicodeString pat; ((DecimalFormat*) &fmt)->toPattern(pat); if (saw == exp) { logln(UnicodeString("Ok ") + toString(n) + " x " + escape(pat) + " = \"" + escape(saw) + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { Formattable n2; fmt.parse(exp, n2, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + exp + "\" - " + u_errorName(status)); return; } UnicodeString saw2; fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } } else { dataerrln(UnicodeString("FAIL ") + toString(n) + " x " + escape(pat) + " = \"" + escape(saw) + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expect(NumberFormat* fmt, const Formattable& n, const UnicodeString& exp, UBool rt, UErrorCode status) { if (fmt == NULL || U_FAILURE(status)) { dataerrln("FAIL: NumberFormat constructor"); } else { expect(*fmt, n, exp, rt); } delete fmt; } void NumberFormatTest::expectCurrency(NumberFormat& nf, const Locale& locale, double value, const UnicodeString& string) { UErrorCode ec = U_ZERO_ERROR; DecimalFormat& fmt = * (DecimalFormat*) &nf; const UChar DEFAULT_CURR[] = {45/*-*/,0}; UChar curr[4]; u_strcpy(curr, DEFAULT_CURR); if (*locale.getLanguage() != 0) { ucurr_forLocale(locale.getName(), curr, 4, &ec); assertSuccess("ucurr_forLocale", ec); fmt.setCurrency(curr, ec); assertSuccess("DecimalFormat::setCurrency", ec); fmt.setCurrency(curr); //Deprecated variant, for coverage only } UnicodeString s; fmt.format(value, s); s.findAndReplace((UChar32)0x00A0, (UChar32)0x0020); // Default display of the number yields "1234.5599999999999" // instead of "1234.56". Use a formatter to fix this. NumberFormat* f = NumberFormat::createInstance(Locale::getUS(), ec); UnicodeString v; if (U_FAILURE(ec)) { // Oops; bad formatter. Use default op+= display. v = (UnicodeString)"" + value; } else { f->setMaximumFractionDigits(4); f->setGroupingUsed(FALSE); f->format(value, v); } delete f; if (s == string) { logln((UnicodeString)"Ok: " + v + " x " + curr + " => " + prettify(s)); } else { errln((UnicodeString)"FAIL: " + v + " x " + curr + " => " + prettify(s) + ", expected " + prettify(string)); } } void NumberFormatTest::expectPat(DecimalFormat& fmt, const UnicodeString& exp) { UnicodeString pat; fmt.toPattern(pat); if (pat == exp) { logln(UnicodeString("Ok \"") + pat + "\""); } else { errln(UnicodeString("FAIL \"") + pat + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos) { expectPad(fmt, pat, pos, 0, (UnicodeString)""); } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos, int32_t width, UChar pad) { expectPad(fmt, pat, pos, width, UnicodeString(pad)); } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos, int32_t width, const UnicodeString& pad) { int32_t apos = 0, awidth = 0; UnicodeString apadStr; UErrorCode status = U_ZERO_ERROR; fmt.applyPattern(pat, status); if (U_SUCCESS(status)) { apos = fmt.getPadPosition(); awidth = fmt.getFormatWidth(); apadStr=fmt.getPadCharacterString(); } else { apos = -1; awidth = width; apadStr = pad; } if (apos == pos && awidth == width && apadStr == pad) { UnicodeString infoStr; if (pos == ILLEGAL) { infoStr = UnicodeString(" width=", "") + awidth + UnicodeString(" pad=", "") + apadStr; } logln(UnicodeString("Ok \"") + pat + "\" pos=" + apos + infoStr); } else { errln(UnicodeString("FAIL \"") + pat + "\" pos=" + apos + " width=" + awidth + " pad=" + apadStr + ", expected " + pos + " " + width + " " + pad); } } // This test is flaky b/c the symbols for CNY and JPY are equivalent in this locale - FIXME void NumberFormatTest::TestCompatibleCurrencies() { /* static const UChar JPY[] = {0x4A, 0x50, 0x59, 0}; static const UChar CNY[] = {0x43, 0x4E, 0x59, 0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createCurrencyInstance(Locale::getUS(), status)); if (U_FAILURE(status)) { errln("Could not create number format instance."); return; } logln("%s:%d - testing parse of halfwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, JPY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, JPY, 1235, "\\uFFE51,235"); logln("%s:%d - testing parse of halfwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, CNY, 1235, "CN\\u00A51,235"); LocalPointer<NumberFormat> fmtTW( NumberFormat::createCurrencyInstance(Locale::getTaiwan(), status)); logln("%s:%d - testing parse of halfwidth yen sign in TW\n", __FILE__, __LINE__); expectParseCurrency(*fmtTW, CNY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign in TW\n", __FILE__, __LINE__); expectParseCurrency(*fmtTW, CNY, 1235, "\\uFFE51,235"); LocalPointer<NumberFormat> fmtJP( NumberFormat::createCurrencyInstance(Locale::getJapan(), status)); logln("%s:%d - testing parse of halfwidth yen sign in JP\n", __FILE__, __LINE__); expectParseCurrency(*fmtJP, JPY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign in JP\n", __FILE__, __LINE__); expectParseCurrency(*fmtJP, JPY, 1235, "\\uFFE51,235"); // more.. */ } void NumberFormatTest::expectParseCurrency(const NumberFormat &fmt, const UChar* currency, double amount, const char *text) { ParsePosition ppos; UnicodeString utext = ctou(text); LocalPointer<CurrencyAmount> currencyAmount(fmt.parseCurrency(utext, ppos)); if (!ppos.getIndex()) { errln(UnicodeString("Parse of ") + utext + " should have succeeded."); return; } UErrorCode status = U_ZERO_ERROR; char theInfo[100]; sprintf(theInfo, "For locale %s, string \"%s\", currency ", fmt.getLocale(ULOC_ACTUAL_LOCALE, status).getBaseName(), text); u_austrcpy(theInfo+uprv_strlen(theInfo), currency); char theOperation[100]; uprv_strcpy(theOperation, theInfo); uprv_strcat(theOperation, ", check amount:"); assertTrue(theOperation, amount == currencyAmount->getNumber().getDouble(status)); uprv_strcpy(theOperation, theInfo); uprv_strcat(theOperation, ", check currency:"); assertEquals(theOperation, currency, currencyAmount->getISOCurrency()); } void NumberFormatTest::TestJB3832(){ const char* localeID = "pt_PT@currency=PTE"; Locale loc(localeID); UErrorCode status = U_ZERO_ERROR; UnicodeString expected(CharsToUnicodeString("1,150$50\\u00A0\\u200B")); // per cldrbug 7670 UnicodeString s; NumberFormat* currencyFmt = NumberFormat::createCurrencyInstance(loc, status); if(U_FAILURE(status)){ dataerrln("Could not create currency formatter for locale %s - %s", localeID, u_errorName(status)); return; } currencyFmt->format(1150.50, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } delete currencyFmt; } void NumberFormatTest::TestHost() { #if U_PLATFORM_USES_ONLY_WIN32_API Win32NumberTest::testLocales(this); #endif Locale loc("en_US@compat=host"); for (UNumberFormatStyle k = UNUM_DECIMAL; k < UNUM_FORMAT_STYLE_COUNT; k = (UNumberFormatStyle)(k+1)) { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> full(NumberFormat::createInstance(loc, k, status)); if (!NumberFormat::isStyleSupported(k)) { if (status != U_UNSUPPORTED_ERROR) { errln("FAIL: expected style %d to be unsupported - %s", k, u_errorName(status)); } continue; } if (full.isNull() || U_FAILURE(status)) { dataerrln("FAIL: Can't create number instance of style %d for host - %s", k, u_errorName(status)); return; } UnicodeString result1; Formattable number(10.00); full->format(number, result1, status); if (U_FAILURE(status)) { errln("FAIL: Can't format for host"); return; } Formattable formattable; full->parse(result1, formattable, status); if (U_FAILURE(status)) { errln("FAIL: Can't parse for host"); return; } } } void NumberFormatTest::TestHostClone() { /* Verify that a cloned formatter gives the same results and is useable after the original has been deleted. */ // This is mainly important on Windows. UErrorCode status = U_ZERO_ERROR; Locale loc("en_US@compat=host"); UDate now = Calendar::getNow(); NumberFormat *full = NumberFormat::createInstance(loc, status); if (full == NULL || U_FAILURE(status)) { dataerrln("FAIL: Can't create NumberFormat date instance - %s", u_errorName(status)); return; } UnicodeString result1; full->format(now, result1, status); Format *fullClone = full->clone(); delete full; full = NULL; UnicodeString result2; fullClone->format(now, result2, status); if (U_FAILURE(status)) { errln("FAIL: format failure."); } if (result1 != result2) { errln("FAIL: Clone returned different result from non-clone."); } delete fullClone; } void NumberFormatTest::TestCurrencyFormat() { // This test is here to increase code coverage. UErrorCode status = U_ZERO_ERROR; MeasureFormat *cloneObj; UnicodeString str; Formattable toFormat, result; static const UChar ISO_CODE[4] = {0x0047, 0x0042, 0x0050, 0}; Locale saveDefaultLocale = Locale::getDefault(); Locale::setDefault( Locale::getUK(), status ); if (U_FAILURE(status)) { errln("couldn't set default Locale!"); return; } MeasureFormat *measureObj = MeasureFormat::createCurrencyFormat(status); Locale::setDefault( saveDefaultLocale, status ); if (U_FAILURE(status)){ dataerrln("FAIL: Status %s", u_errorName(status)); return; } cloneObj = (MeasureFormat *)measureObj->clone(); if (cloneObj == NULL) { errln("Clone doesn't work"); return; } toFormat.adoptObject(new CurrencyAmount(1234.56, ISO_CODE, status)); measureObj->format(toFormat, str, status); measureObj->parseObject(str, result, status); if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } if (result != toFormat) { errln("measureObj does not round trip. Formatted string was \"" + str + "\" Got: " + toString(result) + " Expected: " + toString(toFormat)); } status = U_ZERO_ERROR; str.truncate(0); cloneObj->format(toFormat, str, status); cloneObj->parseObject(str, result, status); if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } if (result != toFormat) { errln("Clone does not round trip. Formatted string was \"" + str + "\" Got: " + toString(result) + " Expected: " + toString(toFormat)); } if (*measureObj != *cloneObj) { errln("Cloned object is not equal to the original object"); } delete measureObj; delete cloneObj; status = U_USELESS_COLLATOR_ERROR; if (MeasureFormat::createCurrencyFormat(status) != NULL) { errln("createCurrencyFormat should have returned NULL."); } } /* Port of ICU4J rounding test. */ void NumberFormatTest::TestRounding() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *df = (DecimalFormat*)NumberFormat::createCurrencyInstance(Locale::getEnglish(), status); if (U_FAILURE(status)) { dataerrln("Unable to create decimal formatter. - %s", u_errorName(status)); return; } int roundingIncrements[]={1, 2, 5, 20, 50, 100}; int testValues[]={0, 300}; for (int j=0; j<2; j++) { for (int mode=DecimalFormat::kRoundUp;mode<DecimalFormat::kRoundHalfEven;mode++) { df->setRoundingMode((DecimalFormat::ERoundingMode)mode); for (int increment=0; increment<6; increment++) { double base=testValues[j]; double rInc=roundingIncrements[increment]; checkRounding(df, base, 20, rInc); rInc=1.000000000/rInc; checkRounding(df, base, 20, rInc); } } } delete df; } void NumberFormatTest::TestRoundingPattern() { UErrorCode status = U_ZERO_ERROR; struct { UnicodeString pattern; double testCase; UnicodeString expected; } tests[] = { { (UnicodeString)"##0.65", 1.234, (UnicodeString)"1.30" }, { (UnicodeString)"#50", 1230, (UnicodeString)"1250" } }; int32_t numOfTests = UPRV_LENGTHOF(tests); UnicodeString result; DecimalFormat *df = (DecimalFormat*)NumberFormat::createCurrencyInstance(Locale::getEnglish(), status); if (U_FAILURE(status)) { dataerrln("Unable to create decimal formatter. - %s", u_errorName(status)); return; } for (int32_t i = 0; i < numOfTests; i++) { result.remove(); df->applyPattern(tests[i].pattern, status); if (U_FAILURE(status)) { errln("Unable to apply pattern to decimal formatter. - %s", u_errorName(status)); } df->format(tests[i].testCase, result); if (result != tests[i].expected) { errln("String Pattern Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } } delete df; } void NumberFormatTest::checkRounding(DecimalFormat* df, double base, int iterations, double increment) { df->setRoundingIncrement(increment); double lastParsed=INT32_MIN; //Intger.MIN_VALUE for (int i=-iterations; i<=iterations;i++) { double iValue=base+(increment*(i*0.1)); double smallIncrement=0.00000001; if (iValue!=0) { smallIncrement*=iValue; } //we not only test the value, but some values in a small range around it lastParsed=checkRound(df, iValue-smallIncrement, lastParsed); lastParsed=checkRound(df, iValue, lastParsed); lastParsed=checkRound(df, iValue+smallIncrement, lastParsed); } } double NumberFormatTest::checkRound(DecimalFormat* df, double iValue, double lastParsed) { UErrorCode status=U_ZERO_ERROR; UnicodeString formattedDecimal; double parsed; Formattable result; df->format(iValue, formattedDecimal, status); if (U_FAILURE(status)) { errln("Error formatting number."); } df->parse(formattedDecimal, result, status); if (U_FAILURE(status)) { errln("Error parsing number."); } parsed=result.getDouble(); if (lastParsed>parsed) { errln("Rounding wrong direction! %d > %d", lastParsed, parsed); } return lastParsed; } void NumberFormatTest::TestNonpositiveMultiplier() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat df(UnicodeString("0"), US, status); CHECK(status, "DecimalFormat(0)"); // test zero multiplier int32_t mult = df.getMultiplier(); df.setMultiplier(0); if (df.getMultiplier() != mult) { errln("DecimalFormat.setMultiplier(0) did not ignore its zero input"); } // test negative multiplier df.setMultiplier(-1); if (df.getMultiplier() != -1) { errln("DecimalFormat.setMultiplier(-1) ignored its negative input"); return; } expect(df, "1122.123", -1122.123); expect(df, "-1122.123", 1122.123); expect(df, "1.2", -1.2); expect(df, "-1.2", 1.2); // Note: the tests with the final parameter of FALSE will not round trip. // The initial numeric value will format correctly, after the multiplier. // Parsing the formatted text will be out-of-range for an int64, however. // The expect() function could be modified to detect this and fall back // to looking at the decimal parsed value, but it doesn't. expect(df, U_INT64_MIN, "9223372036854775808", FALSE); expect(df, U_INT64_MIN+1, "9223372036854775807"); expect(df, (int64_t)-123, "123"); expect(df, (int64_t)123, "-123"); expect(df, U_INT64_MAX-1, "-9223372036854775806"); expect(df, U_INT64_MAX, "-9223372036854775807"); df.setMultiplier(-2); expect(df, -(U_INT64_MIN/2)-1, "-9223372036854775806"); expect(df, -(U_INT64_MIN/2), "-9223372036854775808"); expect(df, -(U_INT64_MIN/2)+1, "-9223372036854775810", FALSE); df.setMultiplier(-7); expect(df, -(U_INT64_MAX/7)-1, "9223372036854775814", FALSE); expect(df, -(U_INT64_MAX/7), "9223372036854775807"); expect(df, -(U_INT64_MAX/7)+1, "9223372036854775800"); // TODO: uncomment (and fix up) all the following int64_t tests once BigInteger is ported // (right now the big numbers get turned into doubles and lose tons of accuracy) //expect2(df, U_INT64_MAX, Int64ToUnicodeString(-U_INT64_MAX)); //expect2(df, U_INT64_MIN, UnicodeString(Int64ToUnicodeString(U_INT64_MIN), 1)); //expect2(df, U_INT64_MAX / 2, Int64ToUnicodeString(-(U_INT64_MAX / 2))); //expect2(df, U_INT64_MIN / 2, Int64ToUnicodeString(-(U_INT64_MIN / 2))); // TODO: uncomment (and fix up) once BigDecimal is ported and DecimalFormat can handle it //expect2(df, BigDecimal.valueOf(Long.MAX_VALUE), BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); //expect2(df, BigDecimal.valueOf(Long.MIN_VALUE), BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); //expect2(df, java.math.BigDecimal.valueOf(Long.MAX_VALUE), java.math.BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); //expect2(df, java.math.BigDecimal.valueOf(Long.MIN_VALUE), java.math.BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); } typedef struct { const char * stringToParse; int parsedPos; int errorIndex; UBool lenient; } TestSpaceParsingItem; void NumberFormatTest::TestSpaceParsing() { // the data are: // the string to be parsed, parsed position, parsed error index const TestSpaceParsingItem DATA[] = { {"$124", 4, -1, FALSE}, {"$124 $124", 4, -1, FALSE}, {"$124 ", 4, -1, FALSE}, {"$ 124 ", 0, 1, FALSE}, {"$\\u00A0124 ", 5, -1, FALSE}, {" $ 124 ", 0, 0, FALSE}, {"124$", 0, 4, FALSE}, {"124 $", 0, 3, FALSE}, {"$124", 4, -1, TRUE}, {"$124 $124", 4, -1, TRUE}, {"$124 ", 4, -1, TRUE}, {"$ 124 ", 5, -1, TRUE}, {"$\\u00A0124 ", 5, -1, TRUE}, {" $ 124 ", 6, -1, TRUE}, {"124$", 4, -1, TRUE}, {"124$", 4, -1, TRUE}, {"124 $", 5, -1, TRUE}, {"124 $", 5, -1, TRUE}, }; UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); NumberFormat* foo = NumberFormat::createCurrencyInstance(locale, status); if (U_FAILURE(status)) { delete foo; return; } for (uint32_t i = 0; i < UPRV_LENGTHOF(DATA); ++i) { ParsePosition parsePosition(0); UnicodeString stringToBeParsed = ctou(DATA[i].stringToParse); int parsedPosition = DATA[i].parsedPos; int errorIndex = DATA[i].errorIndex; foo->setLenient(DATA[i].lenient); Formattable result; foo->parse(stringToBeParsed, result, parsePosition); logln("Parsing: " + stringToBeParsed); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAILED parse " + stringToBeParsed + "; lenient: " + DATA[i].lenient + "; wrong position, expected: (" + parsedPosition + ", " + errorIndex + "); got (" + parsePosition.getIndex() + ", " + parsePosition.getErrorIndex() + ")"); } if (parsePosition.getErrorIndex() == -1 && result.getType() == Formattable::kLong && result.getLong() != 124) { errln("FAILED parse " + stringToBeParsed + "; wrong number, expect: 124, got " + result.getLong()); } } delete foo; } /** * Test using various numbering systems and numbering system keyword. */ typedef struct { const char *localeName; double value; UBool isRBNF; const char *expectedResult; } TestNumberingSystemItem; void NumberFormatTest::TestNumberingSystems() { const TestNumberingSystemItem DATA[] = { { "en_US@numbers=thai", 1234.567, FALSE, "\\u0E51,\\u0E52\\u0E53\\u0E54.\\u0E55\\u0E56\\u0E57" }, { "en_US@numbers=hebr", 5678.0, TRUE, "\\u05D4\\u05F3\\u05EA\\u05E8\\u05E2\\u05F4\\u05D7" }, { "en_US@numbers=arabext", 1234.567, FALSE, "\\u06F1\\u066c\\u06F2\\u06F3\\u06F4\\u066b\\u06F5\\u06F6\\u06F7" }, { "ar_EG", 1234.567, FALSE, "\\u0661\\u066C\\u0662\\u0663\\u0664\\u066b\\u0665\\u0666\\u0667" }, { "th_TH@numbers=traditional", 1234.567, FALSE, "\\u0E51,\\u0E52\\u0E53\\u0E54.\\u0E55\\u0E56\\u0E57" }, // fall back to native per TR35 { "ar_MA", 1234.567, FALSE, "1.234,567" }, { "en_US@numbers=hanidec", 1234.567, FALSE, "\\u4e00,\\u4e8c\\u4e09\\u56db.\\u4e94\\u516d\\u4e03" }, { "ta_IN@numbers=native", 1234.567, FALSE, "\\u0BE7,\\u0BE8\\u0BE9\\u0BEA.\\u0BEB\\u0BEC\\u0BED" }, { "ta_IN@numbers=traditional", 1235.0, TRUE, "\\u0BF2\\u0BE8\\u0BF1\\u0BE9\\u0BF0\\u0BEB" }, { "ta_IN@numbers=finance", 1234.567, FALSE, "1,234.567" }, // fall back to default per TR35 { "zh_TW@numbers=native", 1234.567, FALSE, "\\u4e00,\\u4e8c\\u4e09\\u56db.\\u4e94\\u516d\\u4e03" }, { "zh_TW@numbers=traditional", 1234.567, TRUE, "\\u4E00\\u5343\\u4E8C\\u767E\\u4E09\\u5341\\u56DB\\u9EDE\\u4E94\\u516D\\u4E03" }, { "zh_TW@numbers=finance", 1234.567, TRUE, "\\u58F9\\u4EDF\\u8CB3\\u4F70\\u53C3\\u62FE\\u8086\\u9EDE\\u4F0D\\u9678\\u67D2" }, { NULL, 0, FALSE, NULL } }; UErrorCode ec; const TestNumberingSystemItem *item; for (item = DATA; item->localeName != NULL; item++) { ec = U_ZERO_ERROR; Locale loc = Locale::createFromName(item->localeName); NumberFormat *origFmt = NumberFormat::createInstance(loc,ec); if (U_FAILURE(ec)) { dataerrln("FAIL: getInstance(%s) - %s", item->localeName, u_errorName(ec)); continue; } // Clone to test ticket #10682 NumberFormat *fmt = (NumberFormat *) origFmt->clone(); delete origFmt; if (item->isRBNF) { expect3(*fmt,item->value,CharsToUnicodeString(item->expectedResult)); } else { expect2(*fmt,item->value,CharsToUnicodeString(item->expectedResult)); } delete fmt; } // Test bogus keyword value ec = U_ZERO_ERROR; Locale loc4 = Locale::createFromName("en_US@numbers=foobar"); NumberFormat* fmt4= NumberFormat::createInstance(loc4, ec); if ( ec != U_UNSUPPORTED_ERROR ) { errln("FAIL: getInstance(en_US@numbers=foobar) should have returned U_UNSUPPORTED_ERROR"); delete fmt4; } ec = U_ZERO_ERROR; NumberingSystem *ns = NumberingSystem::createInstance(ec); if (U_FAILURE(ec)) { dataerrln("FAIL: NumberingSystem::createInstance(ec); - %s", u_errorName(ec)); } if ( ns != NULL ) { ns->getDynamicClassID(); ns->getStaticClassID(); } else { errln("FAIL: getInstance() returned NULL."); } NumberingSystem *ns1 = new NumberingSystem(*ns); if (ns1 == NULL) { errln("FAIL: NumberSystem copy constructor returned NULL."); } delete ns1; delete ns; } void NumberFormatTest::TestMultiCurrencySign() { const char* DATA[][6] = { // the fields in the following test are: // locale, // currency pattern (with negative pattern), // currency number to be formatted, // currency format using currency symbol name, such as "$" for USD, // currency format using currency ISO name, such as "USD", // currency format using plural name, such as "US dollars". // for US locale {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "1234.56", "$1,234.56", "USD\\u00A01,234.56", "US dollars\\u00A01,234.56"}, {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "-1234.56", "-$1,234.56", "-USD\\u00A01,234.56", "-US dollars\\u00A01,234.56"}, {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "1", "$1.00", "USD\\u00A01.00", "US dollars\\u00A01.00"}, // for CHINA locale {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "1234.56", "\\uFFE51,234.56", "CNY\\u00A01,234.56", "\\u4EBA\\u6C11\\u5E01\\u00A01,234.56"}, {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "-1234.56", "(\\uFFE51,234.56)", "(CNY\\u00A01,234.56)", "(\\u4EBA\\u6C11\\u5E01\\u00A01,234.56)"}, {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "1", "\\uFFE51.00", "CNY\\u00A01.00", "\\u4EBA\\u6C11\\u5E01\\u00A01.00"} }; const UChar doubleCurrencySign[] = {0xA4, 0xA4, 0}; UnicodeString doubleCurrencyStr(doubleCurrencySign); const UChar tripleCurrencySign[] = {0xA4, 0xA4, 0xA4, 0}; UnicodeString tripleCurrencyStr(tripleCurrencySign); for (uint32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { const char* locale = DATA[i][0]; UnicodeString pat = ctou(DATA[i][1]); double numberToBeFormat = atof(DATA[i][2]); UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale(locale), status); if (U_FAILURE(status)) { delete sym; continue; } for (int j=1; j<=3; ++j) { // j represents the number of currency sign in the pattern. if (j == 2) { pat = pat.findAndReplace(ctou("\\u00A4"), doubleCurrencyStr); } else if (j == 3) { pat = pat.findAndReplace(ctou("\\u00A4\\u00A4"), tripleCurrencyStr); } DecimalFormat* fmt = new DecimalFormat(pat, new DecimalFormatSymbols(*sym), status); if (U_FAILURE(status)) { errln("FAILED init DecimalFormat "); delete fmt; continue; } UnicodeString s; ((NumberFormat*) fmt)->format(numberToBeFormat, s); // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // DATA[i][j+2] is the currency format result using // 'j' number of currency sign. UnicodeString currencyFormatResult = ctou(DATA[i][2+j]); if (s.compare(currencyFormatResult)) { errln("FAIL format: Expected " + currencyFormatResult + "; Got " + s); } // mix style parsing for (int k=3; k<=5; ++k) { // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. UnicodeString oneCurrencyFormat = ctou(DATA[i][k]); UErrorCode status = U_ZERO_ERROR; Formattable parseRes; fmt->parse(oneCurrencyFormat, parseRes, status); if (U_FAILURE(status) || (parseRes.getType() == Formattable::kDouble && parseRes.getDouble() != numberToBeFormat) || (parseRes.getType() == Formattable::kLong && parseRes.getLong() != numberToBeFormat)) { errln("FAILED parse " + oneCurrencyFormat + "; (i, j, k): " + i + ", " + j + ", " + k); } } delete fmt; } delete sym; } } void NumberFormatTest::TestCurrencyFormatForMixParsing() { UErrorCode status = U_ZERO_ERROR; MeasureFormat* curFmt = MeasureFormat::createCurrencyFormat(Locale("en_US"), status); if (U_FAILURE(status)) { delete curFmt; return; } const char* formats[] = { "$1,234.56", // string to be parsed "USD1,234.56", "US dollars1,234.56", // "1,234.56 US dollars" // Fails in 62 because currency format is not compatible with pattern. }; const CurrencyAmount* curramt = NULL; for (uint32_t i = 0; i < UPRV_LENGTHOF(formats); ++i) { UnicodeString stringToBeParsed = ctou(formats[i]); logln(UnicodeString("stringToBeParsed: ") + stringToBeParsed); Formattable result; UErrorCode status = U_ZERO_ERROR; curFmt->parseObject(stringToBeParsed, result, status); if (U_FAILURE(status)) { errln("FAIL: measure format parsing: '%s' ec: %s", formats[i], u_errorName(status)); } else if (result.getType() != Formattable::kObject || (curramt = dynamic_cast<const CurrencyAmount*>(result.getObject())) == NULL || curramt->getNumber().getDouble() != 1234.56 || UnicodeString(curramt->getISOCurrency()).compare(ISO_CURRENCY_USD) ) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number "); if (curramt->getNumber().getDouble() != 1234.56) { errln((UnicodeString)"wong number, expect: 1234.56" + ", got: " + curramt->getNumber().getDouble()); } if (curramt->getISOCurrency() != ISO_CURRENCY_USD) { errln((UnicodeString)"wong currency, expect: USD" + ", got: " + curramt->getISOCurrency()); } } } delete curFmt; } /** Starting in ICU 62, strict mode is actually strict with currency formats. */ void NumberFormatTest::TestMismatchedCurrencyFormatFail() { IcuTestErrorCode status(*this, "TestMismatchedCurrencyFormatFail"); LocalPointer<DecimalFormat> df( dynamic_cast<DecimalFormat*>(DecimalFormat::createCurrencyInstance("en", status)), status); if (!assertSuccess("createCurrencyInstance() failed.", status, true, __FILE__, __LINE__)) {return;} UnicodeString pattern; assertEquals("Test assumes that currency sign is at the beginning", u"\u00A4#,##0.00", df->toPattern(pattern)); // Should round-trip on the correct currency format: expect2(*df, 1.23, u"\u00A41.23"); df->setCurrency(u"EUR", status); expect2(*df, 1.23, u"\u20AC1.23"); // Should parse with currency in the wrong place in lenient mode df->setLenient(TRUE); expect(*df, u"1.23\u20AC", 1.23); expectParseCurrency(*df, u"EUR", 1.23, "1.23\\u20AC"); // Should NOT parse with currency in the wrong place in STRICT mode df->setLenient(FALSE); { Formattable result; ErrorCode failStatus; df->parse(u"1.23\u20AC", result, failStatus); assertEquals("Should fail to parse", U_INVALID_FORMAT_ERROR, failStatus); } { ParsePosition ppos; df->parseCurrency(u"1.23\u20AC", ppos); assertEquals("Should fail to parse currency", 0, ppos.getIndex()); } } void NumberFormatTest::TestDecimalFormatCurrencyParse() { // Locale.US UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale("en_US"), status); if (U_FAILURE(status)) { delete sym; return; } UnicodeString pat; UChar currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append(currency).append(currency).append("#,##0.00;-").append(currency).append(currency).append(currency).append("#,##0.00"); DecimalFormat* fmt = new DecimalFormat(pat, sym, status); if (U_FAILURE(status)) { delete fmt; errln("failed to new DecimalFormat in TestDecimalFormatCurrencyParse"); return; } const char* DATA[][2] = { // the data are: // string to be parsed, the parsed result (number) {"$1.00", "1"}, {"USD1.00", "1"}, {"1.00 US dollar", "1"}, {"$1,234.56", "1234.56"}, {"USD1,234.56", "1234.56"}, {"1,234.56 US dollar", "1234.56"}, }; // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. fmt->setLenient(TRUE); for (uint32_t i = 0; i < UPRV_LENGTHOF(DATA); ++i) { UnicodeString stringToBeParsed = ctou(DATA[i][0]); double parsedResult = atof(DATA[i][1]); UErrorCode status = U_ZERO_ERROR; Formattable result; fmt->parse(stringToBeParsed, result, status); logln((UnicodeString)"Input: " + stringToBeParsed + "; output: " + result.getDouble(status)); if (U_FAILURE(status) || (result.getType() == Formattable::kDouble && result.getDouble() != parsedResult) || (result.getType() == Formattable::kLong && result.getLong() != parsedResult)) { errln((UnicodeString)"FAIL parse: Expected " + parsedResult); } } delete fmt; } void NumberFormatTest::TestCurrencyIsoPluralFormat() { static const char* DATA[][6] = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00 US dollars"}, {"en_US", "1234.56", "USD", "$1,234.56", "USD\\u00A01,234.56", "1,234.56 US dollars"}, {"en_US", "-1234.56", "USD", "-$1,234.56", "-USD\\u00A01,234.56", "-1,234.56 US dollars"}, {"zh_CN", "1", "USD", "US$1.00", "USD\\u00A01.00", "1.00\\u00A0\\u7F8E\\u5143"}, {"zh_CN", "1234.56", "USD", "US$1,234.56", "USD\\u00A01,234.56", "1,234.56\\u00A0\\u7F8E\\u5143"}, {"zh_CN", "1", "CNY", "\\uFFE51.00", "CNY\\u00A01.00", "1.00\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"zh_CN", "1234.56", "CNY", "\\uFFE51,234.56", "CNY\\u00A01,234.56", "1,234.56\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"ru_RU", "1", "RUB", "1,00\\u00A0\\u20BD", "1,00\\u00A0RUB", "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, {"ru_RU", "2", "RUB", "2,00\\u00A0\\u20BD", "2,00\\u00A0RUB", "2,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, {"ru_RU", "5", "RUB", "5,00\\u00A0\\u20BD", "5,00\\u00A0RUB", "5,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, // test locale without currency information {"root", "-1.23", "USD", "-US$\\u00A01.23", "-USD\\u00A01.23", "-1.23 USD"}, // test choice format {"es_AR", "1", "INR", "INR\\u00A01,00", "INR\\u00A01,00", "1,00 rupia india"}, }; static const UNumberFormatStyle currencyStyles[] = { UNUM_CURRENCY, UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL }; for (int32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { const char* localeString = DATA[i][0]; double numberToBeFormat = atof(DATA[i][1]); const char* currencyISOCode = DATA[i][2]; logln(UnicodeString(u"Locale: ") + localeString + "; amount: " + numberToBeFormat); Locale locale(localeString); for (int32_t kIndex = 0; kIndex < UPRV_LENGTHOF(currencyStyles); ++kIndex) { UNumberFormatStyle k = currencyStyles[kIndex]; logln(UnicodeString(u"UNumberFormatStyle: ") + k); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, k, status); if (U_FAILURE(status)) { delete numFmt; dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } UChar currencyCode[4]; u_charsToUChars(currencyISOCode, currencyCode, 4); numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; errln((UnicodeString)"can not set currency:" + currencyISOCode); continue; } UnicodeString strBuf; numFmt->format(numberToBeFormat, strBuf); int resultDataIndex = 3 + kIndex; // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. UnicodeString formatResult = ctou(DATA[i][resultDataIndex]); if (strBuf.compare(formatResult)) { errln("FAIL: Expected " + formatResult + " actual: " + strBuf); } // test parsing, and test parsing for all currency formats. // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. UnicodeString oneCurrencyFormatResult = ctou(DATA[i][j]); UErrorCode status = U_ZERO_ERROR; Formattable parseResult; numFmt->parse(oneCurrencyFormatResult, parseResult, status); if (U_FAILURE(status) || (parseResult.getType() == Formattable::kDouble && parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { errln((UnicodeString)"FAIL: getCurrencyFormat of locale " + localeString + " failed roundtripping the number"); if (parseResult.getType() == Formattable::kDouble) { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getDouble()); } else { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getLong()); } } } delete numFmt; } } } void NumberFormatTest::TestCurrencyParsing() { static const char* DATA[][6] = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00 US dollars"}, {"pa_IN", "1", "USD", "US$\\u00A01.00", "USD\\u00A01.00", "1.00 \\u0a2f\\u0a42.\\u0a10\\u0a38. \\u0a21\\u0a3e\\u0a32\\u0a30"}, {"es_AR", "1", "USD", "US$\\u00A01,00", "USD\\u00A01,00", "1,00 d\\u00f3lar estadounidense"}, {"ar_EG", "1", "USD", "\\u0661\\u066b\\u0660\\u0660\\u00a0US$", "\\u0661\\u066b\\u0660\\u0660\\u00a0USD", "\\u0661\\u066b\\u0660\\u0660 \\u062f\\u0648\\u0644\\u0627\\u0631 \\u0623\\u0645\\u0631\\u064a\\u0643\\u064a"}, {"fa_CA", "1", "USD", "\\u200e$\\u06f1\\u066b\\u06f0\\u06f0", "\\u200eUSD\\u06f1\\u066b\\u06f0\\u06f0", "\\u06f1\\u066b\\u06f0\\u06f0 \\u062f\\u0644\\u0627\\u0631 \\u0627\\u0645\\u0631\\u06cc\\u06a9\\u0627"}, {"he_IL", "1", "USD", "\\u200f1.00\\u00a0$", "\\u200f1.00\\u00a0USD", "1.00 \\u05d3\\u05d5\\u05dc\\u05e8 \\u05d0\\u05de\\u05e8\\u05d9\\u05e7\\u05d0\\u05d9"}, {"hr_HR", "1", "USD", "1,00\\u00a0USD", "1,00\\u00a0USD", "1,00 ameri\\u010Dkih dolara"}, {"id_ID", "1", "USD", "US$\\u00A01,00", "USD\\u00A01,00", "1,00 Dolar Amerika Serikat"}, {"it_IT", "1", "USD", "1,00\\u00a0USD", "1,00\\u00a0USD", "1,00 dollari statunitensi"}, {"ko_KR", "1", "USD", "US$\\u00A01.00", "USD\\u00A01.00", "1.00 \\ubbf8\\uad6d \\ub2ec\\ub7ec"}, {"ja_JP", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00\\u00A0\\u7c73\\u30c9\\u30eb"}, {"zh_CN", "1", "CNY", "\\uFFE51.00", "CNY\\u00A001.00", "1.00\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"zh_TW", "1", "CNY", "CN\\u00A51.00", "CNY\\u00A01.00", "1.00 \\u4eba\\u6c11\\u5e63"}, {"zh_Hant", "1", "CNY", "CN\\u00A51.00", "CNY\\u00A01.00", "1.00 \\u4eba\\u6c11\\u5e63"}, {"zh_Hant", "1", "JPY", "\\u00A51.00", "JPY\\u00A01.00", "1 \\u65E5\\u5713"}, {"ja_JP", "1", "JPY", "\\uFFE51.00", "JPY\\u00A01.00", "1\\u00A0\\u5186"}, // ICU 62 requires #parseCurrency() to recognize variants when parsing // {"ja_JP", "1", "JPY", "\\u00A51.00", "JPY\\u00A01.00", "1\\u00A0\\u5186"}, {"ru_RU", "1", "RUB", "1,00\\u00A0\\u00A0\\u20BD", "1,00\\u00A0\\u00A0RUB", "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"} }; static const UNumberFormatStyle currencyStyles[] = { UNUM_CURRENCY, UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL }; static const char* currencyStyleNames[] = { "UNUM_CURRENCY", "UNUM_CURRENCY_ISO", "UNUM_CURRENCY_PLURAL" }; #ifdef NUMFMTST_CACHE_DEBUG int deadloop = 0; for (;;) { printf("loop: %d\n", deadloop++); #endif for (uint32_t i=0; i< UPRV_LENGTHOF(DATA); ++i) { /* i = test case # - should be i=0*/ for (int32_t kIndex = 2; kIndex < UPRV_LENGTHOF(currencyStyles); ++kIndex) { UNumberFormatStyle k = currencyStyles[kIndex]; /* k = style */ const char* localeString = DATA[i][0]; double numberToBeFormat = atof(DATA[i][1]); const char* currencyISOCode = DATA[i][2]; Locale locale(localeString); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, k, status); logln("#%d NumberFormat(%s, %s) Currency=%s\n", i, localeString, currencyStyleNames[kIndex], currencyISOCode); if (U_FAILURE(status)) { delete numFmt; dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } UChar currencyCode[4]; u_charsToUChars(currencyISOCode, currencyCode, 4); numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; errln((UnicodeString)"can not set currency:" + currencyISOCode); continue; } UnicodeString strBuf; numFmt->format(numberToBeFormat, strBuf); int resultDataIndex = 3 + kIndex; // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. UnicodeString formatResult = ctou(DATA[i][resultDataIndex]); if (strBuf.compare(formatResult)) { errln("FAIL: Expected " + formatResult + " actual: " + strBuf); } // test parsing, and test parsing for all currency formats. // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. UnicodeString oneCurrencyFormatResult = ctou(DATA[i][j]); UErrorCode status = U_ZERO_ERROR; Formattable parseResult; logln("parse(%s)", DATA[i][j]); numFmt->parse(oneCurrencyFormatResult, parseResult, status); if (U_FAILURE(status) || (parseResult.getType() == Formattable::kDouble && parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { errln((UnicodeString)"FAIL: NumberFormat(" + localeString +", " + currencyStyleNames[kIndex] + "), Currency="+currencyISOCode+", parse("+DATA[i][j]+") returned error " + (UnicodeString)u_errorName(status)+". Testcase: data[" + i + "][" + currencyStyleNames[j-3] +"="+j+"]"); if (parseResult.getType() == Formattable::kDouble) { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (double): " +parseResult.getDouble()); } else { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (long): " +parseResult.getLong()); } errln((UnicodeString)" round-trip would be: " + strBuf); } } delete numFmt; } } #ifdef NUMFMTST_CACHE_DEBUG } #endif } void NumberFormatTest::TestParseCurrencyInUCurr() { const char* DATA[] = { "1.00 US DOLLAR", // case in-sensitive "$1.00", "USD1.00", "usd1.00", // case in-sensitive: #13696 "US dollar1.00", "US dollars1.00", "$1.00", "A$1.00", "ADP1.00", "ADP1.00", "AED1.00", "AED1.00", "AFA1.00", "AFA1.00", "AFN1.00", "ALL1.00", "AMD1.00", "ANG1.00", "AOA1.00", "AOK1.00", "AOK1.00", "AON1.00", "AON1.00", "AOR1.00", "AOR1.00", "ARS1.00", "ARA1.00", "ARA1.00", "ARP1.00", "ARP1.00", "ARS1.00", "ATS1.00", "ATS1.00", "AUD1.00", "AWG1.00", "AZM1.00", "AZM1.00", "AZN1.00", "Afghan Afghani (1927\\u20132002)1.00", "Afghan afghani (1927\\u20132002)1.00", "Afghan Afghani1.00", "Afghan Afghanis1.00", "Albanian Lek1.00", "Albanian lek1.00", "Albanian lek\\u00eb1.00", "Algerian Dinar1.00", "Algerian dinar1.00", "Algerian dinars1.00", "Andorran Peseta1.00", "Andorran peseta1.00", "Andorran pesetas1.00", "Angolan Kwanza (1977\\u20131991)1.00", "Angolan Readjusted Kwanza (1995\\u20131999)1.00", "Angolan Kwanza1.00", "Angolan New Kwanza (1990\\u20132000)1.00", "Angolan kwanza (1977\\u20131991)1.00", "Angolan readjusted kwanza (1995\\u20131999)1.00", "Angolan kwanza1.00", "Angolan kwanzas (1977\\u20131991)1.00", "Angolan readjusted kwanzas (1995\\u20131999)1.00", "Angolan kwanzas1.00", "Angolan new kwanza (1990\\u20132000)1.00", "Angolan new kwanzas (1990\\u20132000)1.00", "Argentine Austral1.00", "Argentine Peso (1983\\u20131985)1.00", "Argentine Peso1.00", "Argentine austral1.00", "Argentine australs1.00", "Argentine peso (1983\\u20131985)1.00", "Argentine peso1.00", "Argentine pesos (1983\\u20131985)1.00", "Argentine pesos1.00", "Armenian Dram1.00", "Armenian dram1.00", "Armenian drams1.00", "Aruban Florin1.00", "Aruban florin1.00", "Australian Dollar1.00", "Australian dollar1.00", "Australian dollars1.00", "Austrian Schilling1.00", "Austrian schilling1.00", "Austrian schillings1.00", "Azerbaijani Manat (1993\\u20132006)1.00", "Azerbaijani Manat1.00", "Azerbaijani manat (1993\\u20132006)1.00", "Azerbaijani manat1.00", "Azerbaijani manats (1993\\u20132006)1.00", "Azerbaijani manats1.00", "BAD1.00", "BAD1.00", "BAM1.00", "BBD1.00", "BDT1.00", "BEC1.00", "BEC1.00", "BEF1.00", "BEL1.00", "BEL1.00", "BGL1.00", "BGN1.00", "BGN1.00", "BHD1.00", "BIF1.00", "BMD1.00", "BND1.00", "BOB1.00", "BOP1.00", "BOP1.00", "BOV1.00", "BOV1.00", "BRB1.00", "BRB1.00", "BRC1.00", "BRC1.00", "BRE1.00", "BRE1.00", "BRL1.00", "BRN1.00", "BRN1.00", "BRR1.00", "BRR1.00", "BSD1.00", "BSD1.00", "BTN1.00", "BUK1.00", "BUK1.00", "BWP1.00", "BYB1.00", "BYB1.00", "BYR1.00", "BZD1.00", "Bahamian Dollar1.00", "Bahamian dollar1.00", "Bahamian dollars1.00", "Bahraini Dinar1.00", "Bahraini dinar1.00", "Bahraini dinars1.00", "Bangladeshi Taka1.00", "Bangladeshi taka1.00", "Bangladeshi takas1.00", "Barbadian Dollar1.00", "Barbadian dollar1.00", "Barbadian dollars1.00", "Belarusian Ruble (1994\\u20131999)1.00", "Belarusian Ruble1.00", "Belarusian ruble (1994\\u20131999)1.00", "Belarusian rubles (1994\\u20131999)1.00", "Belarusian ruble1.00", "Belarusian rubles1.00", "Belgian Franc (convertible)1.00", "Belgian Franc (financial)1.00", "Belgian Franc1.00", "Belgian franc (convertible)1.00", "Belgian franc (financial)1.00", "Belgian franc1.00", "Belgian francs (convertible)1.00", "Belgian francs (financial)1.00", "Belgian francs1.00", "Belize Dollar1.00", "Belize dollar1.00", "Belize dollars1.00", "Bermudan Dollar1.00", "Bermudan dollar1.00", "Bermudan dollars1.00", "Bhutanese Ngultrum1.00", "Bhutanese ngultrum1.00", "Bhutanese ngultrums1.00", "Bolivian Mvdol1.00", "Bolivian Peso1.00", "Bolivian mvdol1.00", "Bolivian mvdols1.00", "Bolivian peso1.00", "Bolivian pesos1.00", "Bolivian Boliviano1.00", "Bolivian Boliviano1.00", "Bolivian Bolivianos1.00", "Bosnia-Herzegovina Convertible Mark1.00", "Bosnia-Herzegovina Dinar (1992\\u20131994)1.00", "Bosnia-Herzegovina convertible mark1.00", "Bosnia-Herzegovina convertible marks1.00", "Bosnia-Herzegovina dinar (1992\\u20131994)1.00", "Bosnia-Herzegovina dinars (1992\\u20131994)1.00", "Botswanan Pula1.00", "Botswanan pula1.00", "Botswanan pulas1.00", "Brazilian New Cruzado (1989\\u20131990)1.00", "Brazilian Cruzado (1986\\u20131989)1.00", "Brazilian Cruzeiro (1990\\u20131993)1.00", "Brazilian New Cruzeiro (1967\\u20131986)1.00", "Brazilian Cruzeiro (1993\\u20131994)1.00", "Brazilian Real1.00", "Brazilian new cruzado (1989\\u20131990)1.00", "Brazilian new cruzados (1989\\u20131990)1.00", "Brazilian cruzado (1986\\u20131989)1.00", "Brazilian cruzados (1986\\u20131989)1.00", "Brazilian cruzeiro (1990\\u20131993)1.00", "Brazilian new cruzeiro (1967\\u20131986)1.00", "Brazilian cruzeiro (1993\\u20131994)1.00", "Brazilian cruzeiros (1990\\u20131993)1.00", "Brazilian new cruzeiros (1967\\u20131986)1.00", "Brazilian cruzeiros (1993\\u20131994)1.00", "Brazilian real1.00", "Brazilian reals1.00", "British Pound1.00", "British pound1.00", "British pounds1.00", "Brunei Dollar1.00", "Brunei dollar1.00", "Brunei dollars1.00", "Bulgarian Hard Lev1.00", "Bulgarian Lev1.00", "Bulgarian Leva1.00", "Bulgarian hard lev1.00", "Bulgarian hard leva1.00", "Bulgarian lev1.00", "Burmese Kyat1.00", "Burmese kyat1.00", "Burmese kyats1.00", "Burundian Franc1.00", "Burundian franc1.00", "Burundian francs1.00", "CA$1.00", "CAD1.00", "CDF1.00", "CDF1.00", "West African CFA Franc1.00", "Central African CFA Franc1.00", "West African CFA franc1.00", "Central African CFA franc1.00", "West African CFA francs1.00", "Central African CFA francs1.00", "CFP Franc1.00", "CFP franc1.00", "CFP francs1.00", "CFPF1.00", "CHE1.00", "CHE1.00", "CHF1.00", "CHW1.00", "CHW1.00", "CLF1.00", "CLF1.00", "CLP1.00", "CNY1.00", "COP1.00", "COU1.00", "COU1.00", "CRC1.00", "CSD1.00", "CSD1.00", "CSK1.00", "CSK1.00", "CUP1.00", "CUP1.00", "CVE1.00", "CYP1.00", "CZK1.00", "Cambodian Riel1.00", "Cambodian riel1.00", "Cambodian riels1.00", "Canadian Dollar1.00", "Canadian dollar1.00", "Canadian dollars1.00", "Cape Verdean Escudo1.00", "Cape Verdean escudo1.00", "Cape Verdean escudos1.00", "Cayman Islands Dollar1.00", "Cayman Islands dollar1.00", "Cayman Islands dollars1.00", "Chilean Peso1.00", "Chilean Unit of Account (UF)1.00", "Chilean peso1.00", "Chilean pesos1.00", "Chilean unit of account (UF)1.00", "Chilean units of account (UF)1.00", "Chinese Yuan1.00", "Chinese yuan1.00", "Colombian Peso1.00", "Colombian peso1.00", "Colombian pesos1.00", "Comorian Franc1.00", "Comorian franc1.00", "Comorian francs1.00", "Congolese Franc1.00", "Congolese franc1.00", "Congolese francs1.00", "Costa Rican Col\\u00f3n1.00", "Costa Rican col\\u00f3n1.00", "Costa Rican col\\u00f3ns1.00", "Croatian Dinar1.00", "Croatian Kuna1.00", "Croatian dinar1.00", "Croatian dinars1.00", "Croatian kuna1.00", "Croatian kunas1.00", "Cuban Peso1.00", "Cuban peso1.00", "Cuban pesos1.00", "Cypriot Pound1.00", "Cypriot pound1.00", "Cypriot pounds1.00", "Czech Koruna1.00", "Czech koruna1.00", "Czech korunas1.00", "Czechoslovak Hard Koruna1.00", "Czechoslovak hard koruna1.00", "Czechoslovak hard korunas1.00", "DDM1.00", "DDM1.00", "DEM1.00", "DEM1.00", "DJF1.00", "DKK1.00", "DOP1.00", "DZD1.00", "Danish Krone1.00", "Danish krone1.00", "Danish kroner1.00", "German Mark1.00", "German mark1.00", "German marks1.00", "Djiboutian Franc1.00", "Djiboutian franc1.00", "Djiboutian francs1.00", "Dominican Peso1.00", "Dominican peso1.00", "Dominican pesos1.00", "EC$1.00", "ECS1.00", "ECS1.00", "ECV1.00", "ECV1.00", "EEK1.00", "EEK1.00", "EGP1.00", "EGP1.00", "ERN1.00", "ERN1.00", "ESA1.00", "ESA1.00", "ESB1.00", "ESB1.00", "ESP1.00", "ETB1.00", "EUR1.00", "East Caribbean Dollar1.00", "East Caribbean dollar1.00", "East Caribbean dollars1.00", "East German Mark1.00", "East German mark1.00", "East German marks1.00", "Ecuadorian Sucre1.00", "Ecuadorian Unit of Constant Value1.00", "Ecuadorian sucre1.00", "Ecuadorian sucres1.00", "Ecuadorian unit of constant value1.00", "Ecuadorian units of constant value1.00", "Egyptian Pound1.00", "Egyptian pound1.00", "Egyptian pounds1.00", "Salvadoran Col\\u00f3n1.00", "Salvadoran col\\u00f3n1.00", "Salvadoran colones1.00", "Equatorial Guinean Ekwele1.00", "Equatorial Guinean ekwele1.00", "Eritrean Nakfa1.00", "Eritrean nakfa1.00", "Eritrean nakfas1.00", "Estonian Kroon1.00", "Estonian kroon1.00", "Estonian kroons1.00", "Ethiopian Birr1.00", "Ethiopian birr1.00", "Ethiopian birrs1.00", "Euro1.00", "European Composite Unit1.00", "European Currency Unit1.00", "European Monetary Unit1.00", "European Unit of Account (XBC)1.00", "European Unit of Account (XBD)1.00", "European composite unit1.00", "European composite units1.00", "European currency unit1.00", "European currency units1.00", "European monetary unit1.00", "European monetary units1.00", "European unit of account (XBC)1.00", "European unit of account (XBD)1.00", "European units of account (XBC)1.00", "European units of account (XBD)1.00", "FIM1.00", "FIM1.00", "FJD1.00", "FKP1.00", "FKP1.00", "FRF1.00", "FRF1.00", "Falkland Islands Pound1.00", "Falkland Islands pound1.00", "Falkland Islands pounds1.00", "Fijian Dollar1.00", "Fijian dollar1.00", "Fijian dollars1.00", "Finnish Markka1.00", "Finnish markka1.00", "Finnish markkas1.00", "CHF1.00", "French Franc1.00", "French Gold Franc1.00", "French UIC-Franc1.00", "French UIC-franc1.00", "French UIC-francs1.00", "French franc1.00", "French francs1.00", "French gold franc1.00", "French gold francs1.00", "GBP1.00", "GEK1.00", "GEK1.00", "GEL1.00", "GHC1.00", "GHC1.00", "GHS1.00", "GIP1.00", "GIP1.00", "GMD1.00", "GMD1.00", "GNF1.00", "GNS1.00", "GNS1.00", "GQE1.00", "GQE1.00", "GRD1.00", "GRD1.00", "GTQ1.00", "GWE1.00", "GWE1.00", "GWP1.00", "GWP1.00", "GYD1.00", "Gambian Dalasi1.00", "Gambian dalasi1.00", "Gambian dalasis1.00", "Georgian Kupon Larit1.00", "Georgian Lari1.00", "Georgian kupon larit1.00", "Georgian kupon larits1.00", "Georgian lari1.00", "Georgian laris1.00", "Ghanaian Cedi (1979\\u20132007)1.00", "Ghanaian Cedi1.00", "Ghanaian cedi (1979\\u20132007)1.00", "Ghanaian cedi1.00", "Ghanaian cedis (1979\\u20132007)1.00", "Ghanaian cedis1.00", "Gibraltar Pound1.00", "Gibraltar pound1.00", "Gibraltar pounds1.00", "Gold1.00", "Gold1.00", "Greek Drachma1.00", "Greek drachma1.00", "Greek drachmas1.00", "Guatemalan Quetzal1.00", "Guatemalan quetzal1.00", "Guatemalan quetzals1.00", "Guinean Franc1.00", "Guinean Syli1.00", "Guinean franc1.00", "Guinean francs1.00", "Guinean syli1.00", "Guinean sylis1.00", "Guinea-Bissau Peso1.00", "Guinea-Bissau peso1.00", "Guinea-Bissau pesos1.00", "Guyanaese Dollar1.00", "Guyanaese dollar1.00", "Guyanaese dollars1.00", "HK$1.00", "HKD1.00", "HNL1.00", "HRD1.00", "HRD1.00", "HRK1.00", "HRK1.00", "HTG1.00", "HTG1.00", "HUF1.00", "Haitian Gourde1.00", "Haitian gourde1.00", "Haitian gourdes1.00", "Honduran Lempira1.00", "Honduran lempira1.00", "Honduran lempiras1.00", "Hong Kong Dollar1.00", "Hong Kong dollar1.00", "Hong Kong dollars1.00", "Hungarian Forint1.00", "Hungarian forint1.00", "Hungarian forints1.00", "IDR1.00", "IEP1.00", "ILP1.00", "ILP1.00", "ILS1.00", "INR1.00", "IQD1.00", "IRR1.00", "ISK1.00", "ISK1.00", "ITL1.00", "Icelandic Kr\\u00f3na1.00", "Icelandic kr\\u00f3na1.00", "Icelandic kr\\u00f3nur1.00", "Indian Rupee1.00", "Indian rupee1.00", "Indian rupees1.00", "Indonesian Rupiah1.00", "Indonesian rupiah1.00", "Indonesian rupiahs1.00", "Iranian Rial1.00", "Iranian rial1.00", "Iranian rials1.00", "Iraqi Dinar1.00", "Iraqi dinar1.00", "Iraqi dinars1.00", "Irish Pound1.00", "Irish pound1.00", "Irish pounds1.00", "Israeli Pound1.00", "Israeli new shekel1.00", "Israeli pound1.00", "Israeli pounds1.00", "Italian Lira1.00", "Italian lira1.00", "Italian liras1.00", "JMD1.00", "JOD1.00", "JPY1.00", "Jamaican Dollar1.00", "Jamaican dollar1.00", "Jamaican dollars1.00", "Japanese Yen1.00", "Japanese yen1.00", "Jordanian Dinar1.00", "Jordanian dinar1.00", "Jordanian dinars1.00", "KES1.00", "KGS1.00", "KHR1.00", "KMF1.00", "KPW1.00", "KPW1.00", "KRW1.00", "KWD1.00", "KYD1.00", "KYD1.00", "KZT1.00", "Kazakhstani Tenge1.00", "Kazakhstani tenge1.00", "Kazakhstani tenges1.00", "Kenyan Shilling1.00", "Kenyan shilling1.00", "Kenyan shillings1.00", "Kuwaiti Dinar1.00", "Kuwaiti dinar1.00", "Kuwaiti dinars1.00", "Kyrgystani Som1.00", "Kyrgystani som1.00", "Kyrgystani soms1.00", "HNL1.00", "LAK1.00", "LAK1.00", "LBP1.00", "LKR1.00", "LRD1.00", "LRD1.00", "LSL1.00", "LTL1.00", "LTL1.00", "LTT1.00", "LTT1.00", "LUC1.00", "LUC1.00", "LUF1.00", "LUF1.00", "LUL1.00", "LUL1.00", "LVL1.00", "LVL1.00", "LVR1.00", "LVR1.00", "LYD1.00", "Laotian Kip1.00", "Laotian kip1.00", "Laotian kips1.00", "Latvian Lats1.00", "Latvian Ruble1.00", "Latvian lats1.00", "Latvian lati1.00", "Latvian ruble1.00", "Latvian rubles1.00", "Lebanese Pound1.00", "Lebanese pound1.00", "Lebanese pounds1.00", "Lesotho Loti1.00", "Lesotho loti1.00", "Lesotho lotis1.00", "Liberian Dollar1.00", "Liberian dollar1.00", "Liberian dollars1.00", "Libyan Dinar1.00", "Libyan dinar1.00", "Libyan dinars1.00", "Lithuanian Litas1.00", "Lithuanian Talonas1.00", "Lithuanian litas1.00", "Lithuanian litai1.00", "Lithuanian talonas1.00", "Lithuanian talonases1.00", "Luxembourgian Convertible Franc1.00", "Luxembourg Financial Franc1.00", "Luxembourgian Franc1.00", "Luxembourgian convertible franc1.00", "Luxembourgian convertible francs1.00", "Luxembourg financial franc1.00", "Luxembourg financial francs1.00", "Luxembourgian franc1.00", "Luxembourgian francs1.00", "MAD1.00", "MAD1.00", "MAF1.00", "MAF1.00", "MDL1.00", "MDL1.00", "MX$1.00", "MGA1.00", "MGA1.00", "MGF1.00", "MGF1.00", "MKD1.00", "MLF1.00", "MLF1.00", "MMK1.00", "MMK1.00", "MNT1.00", "MOP1.00", "MOP1.00", "MRO1.00", "MTL1.00", "MTP1.00", "MTP1.00", "MUR1.00", "MUR1.00", "MVR1.00", "MVR1.00", "MWK1.00", "MXN1.00", "MXP1.00", "MXP1.00", "MXV1.00", "MXV1.00", "MYR1.00", "MZE1.00", "MZE1.00", "MZM1.00", "MZN1.00", "Macanese Pataca1.00", "Macanese pataca1.00", "Macanese patacas1.00", "Macedonian Denar1.00", "Macedonian denar1.00", "Macedonian denari1.00", "Malagasy Ariaries1.00", "Malagasy Ariary1.00", "Malagasy Ariary1.00", "Malagasy Franc1.00", "Malagasy franc1.00", "Malagasy francs1.00", "Malawian Kwacha1.00", "Malawian Kwacha1.00", "Malawian Kwachas1.00", "Malaysian Ringgit1.00", "Malaysian ringgit1.00", "Malaysian ringgits1.00", "Maldivian Rufiyaa1.00", "Maldivian rufiyaa1.00", "Maldivian rufiyaas1.00", "Malian Franc1.00", "Malian franc1.00", "Malian francs1.00", "Maltese Lira1.00", "Maltese Pound1.00", "Maltese lira1.00", "Maltese lira1.00", "Maltese pound1.00", "Maltese pounds1.00", "Mauritanian Ouguiya1.00", "Mauritanian ouguiya1.00", "Mauritanian ouguiyas1.00", "Mauritian Rupee1.00", "Mauritian rupee1.00", "Mauritian rupees1.00", "Mexican Peso1.00", "Mexican Silver Peso (1861\\u20131992)1.00", "Mexican Investment Unit1.00", "Mexican peso1.00", "Mexican pesos1.00", "Mexican silver peso (1861\\u20131992)1.00", "Mexican silver pesos (1861\\u20131992)1.00", "Mexican investment unit1.00", "Mexican investment units1.00", "Moldovan Leu1.00", "Moldovan leu1.00", "Moldovan lei1.00", "Mongolian Tugrik1.00", "Mongolian tugrik1.00", "Mongolian tugriks1.00", "Moroccan Dirham1.00", "Moroccan Franc1.00", "Moroccan dirham1.00", "Moroccan dirhams1.00", "Moroccan franc1.00", "Moroccan francs1.00", "Mozambican Escudo1.00", "Mozambican Metical1.00", "Mozambican escudo1.00", "Mozambican escudos1.00", "Mozambican metical1.00", "Mozambican meticals1.00", "Myanmar Kyat1.00", "Myanmar kyat1.00", "Myanmar kyats1.00", "NAD1.00", "NGN1.00", "NIC1.00", "NIO1.00", "NIO1.00", "NLG1.00", "NLG1.00", "NOK1.00", "NPR1.00", "NT$1.00", "NZ$1.00", "NZD1.00", "Namibian Dollar1.00", "Namibian dollar1.00", "Namibian dollars1.00", "Nepalese Rupee1.00", "Nepalese rupee1.00", "Nepalese rupees1.00", "Netherlands Antillean Guilder1.00", "Netherlands Antillean guilder1.00", "Netherlands Antillean guilders1.00", "Dutch Guilder1.00", "Dutch guilder1.00", "Dutch guilders1.00", "Israeli New Shekel1.00", "Israeli New Shekels1.00", "New Zealand Dollar1.00", "New Zealand dollar1.00", "New Zealand dollars1.00", "Nicaraguan C\\u00f3rdoba1.00", "Nicaraguan C\\u00f3rdoba (1988\\u20131991)1.00", "Nicaraguan c\\u00f3rdoba1.00", "Nicaraguan c\\u00f3rdobas1.00", "Nicaraguan c\\u00f3rdoba (1988\\u20131991)1.00", "Nicaraguan c\\u00f3rdobas (1988\\u20131991)1.00", "Nigerian Naira1.00", "Nigerian naira1.00", "Nigerian nairas1.00", "North Korean Won1.00", "North Korean won1.00", "North Korean won1.00", "Norwegian Krone1.00", "Norwegian krone1.00", "Norwegian kroner1.00", "OMR1.00", "Mozambican Metical (1980\\u20132006)1.00", "Mozambican metical (1980\\u20132006)1.00", "Mozambican meticals (1980\\u20132006)1.00", "Romanian Lei (1952\\u20132006)1.00", "Romanian Leu (1952\\u20132006)1.00", "Romanian leu (1952\\u20132006)1.00", "Serbian Dinar (2002\\u20132006)1.00", "Serbian dinar (2002\\u20132006)1.00", "Serbian dinars (2002\\u20132006)1.00", "Sudanese Dinar (1992\\u20132007)1.00", "Sudanese Pound (1957\\u20131998)1.00", "Sudanese dinar (1992\\u20132007)1.00", "Sudanese dinars (1992\\u20132007)1.00", "Sudanese pound (1957\\u20131998)1.00", "Sudanese pounds (1957\\u20131998)1.00", "Turkish Lira (1922\\u20132005)1.00", "Turkish Lira (1922\\u20132005)1.00", "Omani Rial1.00", "Omani rial1.00", "Omani rials1.00", "PAB1.00", "PAB1.00", "PEI1.00", "PEI1.00", "PEN1.00", "PEN1.00", "PES1.00", "PES1.00", "PGK1.00", "PGK1.00", "PHP1.00", "PKR1.00", "PLN1.00", "PLZ1.00", "PLZ1.00", "PTE1.00", "PTE1.00", "PYG1.00", "Pakistani Rupee1.00", "Pakistani rupee1.00", "Pakistani rupees1.00", "Palladium1.00", "Palladium1.00", "Panamanian Balboa1.00", "Panamanian balboa1.00", "Panamanian balboas1.00", "Papua New Guinean Kina1.00", "Papua New Guinean kina1.00", "Papua New Guinean kina1.00", "Paraguayan Guarani1.00", "Paraguayan guarani1.00", "Paraguayan guaranis1.00", "Peruvian Inti1.00", "Peruvian Sol1.00", "Peruvian Sol (1863\\u20131965)1.00", "Peruvian inti1.00", "Peruvian intis1.00", "Peruvian sol1.00", "Peruvian soles1.00", "Peruvian sol (1863\\u20131965)1.00", "Peruvian soles (1863\\u20131965)1.00", "Philippine Piso1.00", "Philippine piso1.00", "Philippine pisos1.00", "Platinum1.00", "Platinum1.00", "Polish Zloty (1950\\u20131995)1.00", "Polish Zloty1.00", "Polish zlotys1.00", "Polish zloty (PLZ)1.00", "Polish zloty1.00", "Polish zlotys (PLZ)1.00", "Portuguese Escudo1.00", "Portuguese Guinea Escudo1.00", "Portuguese Guinea escudo1.00", "Portuguese Guinea escudos1.00", "Portuguese escudo1.00", "Portuguese escudos1.00", "GTQ1.00", "QAR1.00", "Qatari Rial1.00", "Qatari rial1.00", "Qatari rials1.00", "RHD1.00", "RHD1.00", "RINET Funds1.00", "RINET Funds1.00", "CN\\u00a51.00", "ROL1.00", "ROL1.00", "RON1.00", "RON1.00", "RSD1.00", "RSD1.00", "RUB1.00", "RUR1.00", "RUR1.00", "RWF1.00", "RWF1.00", "Rhodesian Dollar1.00", "Rhodesian dollar1.00", "Rhodesian dollars1.00", "Romanian Leu1.00", "Romanian lei1.00", "Romanian leu1.00", "Russian Ruble (1991\\u20131998)1.00", "Russian Ruble1.00", "Russian ruble (1991\\u20131998)1.00", "Russian ruble1.00", "Russian rubles (1991\\u20131998)1.00", "Russian rubles1.00", "Rwandan Franc1.00", "Rwandan franc1.00", "Rwandan francs1.00", "SAR1.00", "SBD1.00", "SCR1.00", "SDD1.00", "SDD1.00", "SDG1.00", "SDG1.00", "SDP1.00", "SDP1.00", "SEK1.00", "SGD1.00", "SHP1.00", "SHP1.00", "SIT1.00", "SIT1.00", "SKK1.00", "SLL1.00", "SLL1.00", "SOS1.00", "SRD1.00", "SRD1.00", "SRG1.00", "STD1.00", "SUR1.00", "SUR1.00", "SVC1.00", "SVC1.00", "SYP1.00", "SZL1.00", "St. Helena Pound1.00", "St. Helena pound1.00", "St. Helena pounds1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobra1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobra1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobras1.00", "Saudi Riyal1.00", "Saudi riyal1.00", "Saudi riyals1.00", "Serbian Dinar1.00", "Serbian dinar1.00", "Serbian dinars1.00", "Seychellois Rupee1.00", "Seychellois rupee1.00", "Seychellois rupees1.00", "Sierra Leonean Leone1.00", "Sierra Leonean leone1.00", "Sierra Leonean leones1.00", "Silver1.00", "Silver1.00", "Singapore Dollar1.00", "Singapore dollar1.00", "Singapore dollars1.00", "Slovak Koruna1.00", "Slovak koruna1.00", "Slovak korunas1.00", "Slovenian Tolar1.00", "Slovenian tolar1.00", "Slovenian tolars1.00", "Solomon Islands Dollar1.00", "Solomon Islands dollar1.00", "Solomon Islands dollars1.00", "Somali Shilling1.00", "Somali shilling1.00", "Somali shillings1.00", "South African Rand (financial)1.00", "South African Rand1.00", "South African rand (financial)1.00", "South African rand1.00", "South African rands (financial)1.00", "South African rand1.00", "South Korean Won1.00", "South Korean won1.00", "South Korean won1.00", "Soviet Rouble1.00", "Soviet rouble1.00", "Soviet roubles1.00", "Spanish Peseta (A account)1.00", "Spanish Peseta (convertible account)1.00", "Spanish Peseta1.00", "Spanish peseta (A account)1.00", "Spanish peseta (convertible account)1.00", "Spanish peseta1.00", "Spanish pesetas (A account)1.00", "Spanish pesetas (convertible account)1.00", "Spanish pesetas1.00", "Special Drawing Rights1.00", "Sri Lankan Rupee1.00", "Sri Lankan rupee1.00", "Sri Lankan rupees1.00", "Sudanese Pound1.00", "Sudanese pound1.00", "Sudanese pounds1.00", "Surinamese Dollar1.00", "Surinamese dollar1.00", "Surinamese dollars1.00", "Surinamese Guilder1.00", "Surinamese guilder1.00", "Surinamese guilders1.00", "Swazi Lilangeni1.00", "Swazi lilangeni1.00", "Swazi emalangeni1.00", "Swedish Krona1.00", "Swedish krona1.00", "Swedish kronor1.00", "Swiss Franc1.00", "Swiss franc1.00", "Swiss francs1.00", "Syrian Pound1.00", "Syrian pound1.00", "Syrian pounds1.00", "THB1.00", "TJR1.00", "TJR1.00", "TJS1.00", "TJS1.00", "TMM1.00", "TMM1.00", "TND1.00", "TND1.00", "TOP1.00", "TPE1.00", "TPE1.00", "TRL1.00", "TRY1.00", "TRY1.00", "TTD1.00", "TWD1.00", "TZS1.00", "New Taiwan Dollar1.00", "New Taiwan dollar1.00", "New Taiwan dollars1.00", "Tajikistani Ruble1.00", "Tajikistani Somoni1.00", "Tajikistani ruble1.00", "Tajikistani rubles1.00", "Tajikistani somoni1.00", "Tajikistani somonis1.00", "Tanzanian Shilling1.00", "Tanzanian shilling1.00", "Tanzanian shillings1.00", "Testing Currency Code1.00", "Testing Currency Code1.00", "Thai Baht1.00", "Thai baht1.00", "Thai baht1.00", "Timorese Escudo1.00", "Timorese escudo1.00", "Timorese escudos1.00", "Tongan Pa\\u02bbanga1.00", "Tongan pa\\u02bbanga1.00", "Tongan pa\\u02bbanga1.00", "Trinidad & Tobago Dollar1.00", "Trinidad & Tobago dollar1.00", "Trinidad & Tobago dollars1.00", "Tunisian Dinar1.00", "Tunisian dinar1.00", "Tunisian dinars1.00", "Turkish Lira1.00", "Turkish Lira1.00", "Turkish lira1.00", "Turkmenistani Manat1.00", "Turkmenistani manat1.00", "Turkmenistani manat1.00", "UAE dirham1.00", "UAE dirhams1.00", "UAH1.00", "UAK1.00", "UAK1.00", "UGS1.00", "UGS1.00", "UGX1.00", "US Dollar (Next day)1.00", "US Dollar (Same day)1.00", "US Dollar1.00", "US dollar (next day)1.00", "US dollar (same day)1.00", "US dollar1.00", "US dollars (next day)1.00", "US dollars (same day)1.00", "US dollars1.00", "USD1.00", "USN1.00", "USN1.00", "USS1.00", "USS1.00", "UYI1.00", "UYI1.00", "UYP1.00", "UYP1.00", "UYU1.00", "UZS1.00", "UZS1.00", "Ugandan Shilling (1966\\u20131987)1.00", "Ugandan Shilling1.00", "Ugandan shilling (1966\\u20131987)1.00", "Ugandan shilling1.00", "Ugandan shillings (1966\\u20131987)1.00", "Ugandan shillings1.00", "Ukrainian Hryvnia1.00", "Ukrainian Karbovanets1.00", "Ukrainian hryvnia1.00", "Ukrainian hryvnias1.00", "Ukrainian karbovanets1.00", "Ukrainian karbovantsiv1.00", "Colombian Real Value Unit1.00", "United Arab Emirates Dirham1.00", "Unknown Currency1.00", "Uruguayan Peso (1975\\u20131993)1.00", "Uruguayan Peso1.00", "Uruguayan Peso (Indexed Units)1.00", "Uruguayan peso (1975\\u20131993)1.00", "Uruguayan peso (indexed units)1.00", "Uruguayan peso1.00", "Uruguayan pesos (1975\\u20131993)1.00", "Uruguayan pesos (indexed units)1.00", "Uruguayan pesos1.00", "Uzbekistani Som1.00", "Uzbekistani som1.00", "Uzbekistani som1.00", "VEB1.00", "VEF1.00", "VND1.00", "VUV1.00", "Vanuatu Vatu1.00", "Vanuatu vatu1.00", "Vanuatu vatus1.00", "Venezuelan Bol\\u00edvar1.00", "Venezuelan Bol\\u00edvar (1871\\u20132008)1.00", "Venezuelan bol\\u00edvar1.00", "Venezuelan bol\\u00edvars1.00", "Venezuelan bol\\u00edvar (1871\\u20132008)1.00", "Venezuelan bol\\u00edvars (1871\\u20132008)1.00", "Vietnamese Dong1.00", "Vietnamese dong1.00", "Vietnamese dong1.00", "WIR Euro1.00", "WIR Franc1.00", "WIR euro1.00", "WIR euros1.00", "WIR franc1.00", "WIR francs1.00", "WST1.00", "WST1.00", "Samoan Tala1.00", "Samoan tala1.00", "Samoan tala1.00", "XAF1.00", "XAF1.00", "XAG1.00", "XAG1.00", "XAU1.00", "XAU1.00", "XBA1.00", "XBA1.00", "XBB1.00", "XBB1.00", "XBC1.00", "XBC1.00", "XBD1.00", "XBD1.00", "XCD1.00", "XDR1.00", "XDR1.00", "XEU1.00", "XEU1.00", "XFO1.00", "XFO1.00", "XFU1.00", "XFU1.00", "XOF1.00", "XOF1.00", "XPD1.00", "XPD1.00", "XPF1.00", "XPT1.00", "XPT1.00", "XRE1.00", "XRE1.00", "XTS1.00", "XTS1.00", "XXX1.00", "XXX1.00", "YDD1.00", "YDD1.00", "YER1.00", "YUD1.00", "YUD1.00", "YUM1.00", "YUM1.00", "YUN1.00", "YUN1.00", "Yemeni Dinar1.00", "Yemeni Rial1.00", "Yemeni dinar1.00", "Yemeni dinars1.00", "Yemeni rial1.00", "Yemeni rials1.00", "Yugoslavian Convertible Dinar (1990\\u20131992)1.00", "Yugoslavian Hard Dinar (1966\\u20131990)1.00", "Yugoslavian New Dinar (1994\\u20132002)1.00", "Yugoslavian convertible dinar (1990\\u20131992)1.00", "Yugoslavian convertible dinars (1990\\u20131992)1.00", "Yugoslavian hard dinar (1966\\u20131990)1.00", "Yugoslavian hard dinars (1966\\u20131990)1.00", "Yugoslavian new dinar (1994\\u20132002)1.00", "Yugoslavian new dinars (1994\\u20132002)1.00", "ZAL1.00", "ZAL1.00", "ZAR1.00", "ZMK1.00", "ZMK1.00", "ZRN1.00", "ZRN1.00", "ZRZ1.00", "ZRZ1.00", "ZWD1.00", "Zairean New Zaire (1993\\u20131998)1.00", "Zairean Zaire (1971\\u20131993)1.00", "Zairean new zaire (1993\\u20131998)1.00", "Zairean new zaires (1993\\u20131998)1.00", "Zairean zaire (1971\\u20131993)1.00", "Zairean zaires (1971\\u20131993)1.00", "Zambian Kwacha1.00", "Zambian kwacha1.00", "Zambian kwachas1.00", "Zimbabwean Dollar (1980\\u20132008)1.00", "Zimbabwean dollar (1980\\u20132008)1.00", "Zimbabwean dollars (1980\\u20132008)1.00", "euro1.00", "euros1.00", "Turkish lira (1922\\u20132005)1.00", "special drawing rights1.00", "Colombian real value unit1.00", "Colombian real value units1.00", "unknown currency1.00", "\\u00a31.00", "\\u00a51.00", "\\u20ab1.00", "\\u20aa1.00", "\\u20ac1.00", "\\u20b91.00", // // Following has extra text, should be parsed correctly too "$1.00 random", "USD1.00 random", "1.00 US dollar random", "1.00 US dollars random", "1.00 Afghan Afghani random", "1.00 Afghan Afghani random", "1.00 Afghan Afghanis (1927\\u20131992) random", "1.00 Afghan Afghanis random", "1.00 Albanian Lek random", "1.00 Albanian lek random", "1.00 Albanian lek\\u00eb random", "1.00 Algerian Dinar random", "1.00 Algerian dinar random", "1.00 Algerian dinars random", "1.00 Andorran Peseta random", "1.00 Andorran peseta random", "1.00 Andorran pesetas random", "1.00 Angolan Kwanza (1977\\u20131990) random", "1.00 Angolan Readjusted Kwanza (1995\\u20131999) random", "1.00 Angolan Kwanza random", "1.00 Angolan New Kwanza (1990\\u20132000) random", "1.00 Angolan kwanza (1977\\u20131991) random", "1.00 Angolan readjusted kwanza (1995\\u20131999) random", "1.00 Angolan kwanza random", "1.00 Angolan kwanzas (1977\\u20131991) random", "1.00 Angolan readjusted kwanzas (1995\\u20131999) random", "1.00 Angolan kwanzas random", "1.00 Angolan new kwanza (1990\\u20132000) random", "1.00 Angolan new kwanzas (1990\\u20132000) random", "1.00 Argentine Austral random", "1.00 Argentine Peso (1983\\u20131985) random", "1.00 Argentine Peso random", "1.00 Argentine austral random", "1.00 Argentine australs random", "1.00 Argentine peso (1983\\u20131985) random", "1.00 Argentine peso random", "1.00 Argentine pesos (1983\\u20131985) random", "1.00 Argentine pesos random", "1.00 Armenian Dram random", "1.00 Armenian dram random", "1.00 Armenian drams random", "1.00 Aruban Florin random", "1.00 Aruban florin random", "1.00 Australian Dollar random", "1.00 Australian dollar random", "1.00 Australian dollars random", "1.00 Austrian Schilling random", "1.00 Austrian schilling random", "1.00 Austrian schillings random", "1.00 Azerbaijani Manat (1993\\u20132006) random", "1.00 Azerbaijani Manat random", "1.00 Azerbaijani manat (1993\\u20132006) random", "1.00 Azerbaijani manat random", "1.00 Azerbaijani manats (1993\\u20132006) random", "1.00 Azerbaijani manats random", "1.00 Bahamian Dollar random", "1.00 Bahamian dollar random", "1.00 Bahamian dollars random", "1.00 Bahraini Dinar random", "1.00 Bahraini dinar random", "1.00 Bahraini dinars random", "1.00 Bangladeshi Taka random", "1.00 Bangladeshi taka random", "1.00 Bangladeshi takas random", "1.00 Barbadian Dollar random", "1.00 Barbadian dollar random", "1.00 Barbadian dollars random", "1.00 Belarusian Ruble (1994\\u20131999) random", "1.00 Belarusian Ruble random", "1.00 Belarusian ruble (1994\\u20131999) random", "1.00 Belarusian rubles (1994\\u20131999) random", "1.00 Belarusian ruble random", "1.00 Belarusian rubles random", "1.00 Belgian Franc (convertible) random", "1.00 Belgian Franc (financial) random", "1.00 Belgian Franc random", "1.00 Belgian franc (convertible) random", "1.00 Belgian franc (financial) random", "1.00 Belgian franc random", "1.00 Belgian francs (convertible) random", "1.00 Belgian francs (financial) random", "1.00 Belgian francs random", "1.00 Belize Dollar random", "1.00 Belize dollar random", "1.00 Belize dollars random", "1.00 Bermudan Dollar random", "1.00 Bermudan dollar random", "1.00 Bermudan dollars random", "1.00 Bhutanese Ngultrum random", "1.00 Bhutanese ngultrum random", "1.00 Bhutanese ngultrums random", "1.00 Bolivian Mvdol random", "1.00 Bolivian Peso random", "1.00 Bolivian mvdol random", "1.00 Bolivian mvdols random", "1.00 Bolivian peso random", "1.00 Bolivian pesos random", "1.00 Bolivian Boliviano random", "1.00 Bolivian Boliviano random", "1.00 Bolivian Bolivianos random", "1.00 Bosnia-Herzegovina Convertible Mark random", "1.00 Bosnia-Herzegovina Dinar (1992\\u20131994) random", "1.00 Bosnia-Herzegovina convertible mark random", "1.00 Bosnia-Herzegovina convertible marks random", "1.00 Bosnia-Herzegovina dinar (1992\\u20131994) random", "1.00 Bosnia-Herzegovina dinars (1992\\u20131994) random", "1.00 Botswanan Pula random", "1.00 Botswanan pula random", "1.00 Botswanan pulas random", "1.00 Brazilian New Cruzado (1989\\u20131990) random", "1.00 Brazilian Cruzado (1986\\u20131989) random", "1.00 Brazilian Cruzeiro (1990\\u20131993) random", "1.00 Brazilian New Cruzeiro (1967\\u20131986) random", "1.00 Brazilian Cruzeiro (1993\\u20131994) random", "1.00 Brazilian Real random", "1.00 Brazilian new cruzado (1989\\u20131990) random", "1.00 Brazilian new cruzados (1989\\u20131990) random", "1.00 Brazilian cruzado (1986\\u20131989) random", "1.00 Brazilian cruzados (1986\\u20131989) random", "1.00 Brazilian cruzeiro (1990\\u20131993) random", "1.00 Brazilian new cruzeiro (1967\\u20131986) random", "1.00 Brazilian cruzeiro (1993\\u20131994) random", "1.00 Brazilian cruzeiros (1990\\u20131993) random", "1.00 Brazilian new cruzeiros (1967\\u20131986) random", "1.00 Brazilian cruzeiros (1993\\u20131994) random", "1.00 Brazilian real random", "1.00 Brazilian reals random", "1.00 British Pound random", "1.00 British pound random", "1.00 British pounds random", "1.00 Brunei Dollar random", "1.00 Brunei dollar random", "1.00 Brunei dollars random", "1.00 Bulgarian Hard Lev random", "1.00 Bulgarian Lev random", "1.00 Bulgarian Leva random", "1.00 Bulgarian hard lev random", "1.00 Bulgarian hard leva random", "1.00 Bulgarian lev random", "1.00 Burmese Kyat random", "1.00 Burmese kyat random", "1.00 Burmese kyats random", "1.00 Burundian Franc random", "1.00 Burundian franc random", "1.00 Burundian francs random", "1.00 Cambodian Riel random", "1.00 Cambodian riel random", "1.00 Cambodian riels random", "1.00 Canadian Dollar random", "1.00 Canadian dollar random", "1.00 Canadian dollars random", "1.00 Cape Verdean Escudo random", "1.00 Cape Verdean escudo random", "1.00 Cape Verdean escudos random", "1.00 Cayman Islands Dollar random", "1.00 Cayman Islands dollar random", "1.00 Cayman Islands dollars random", "1.00 Chilean Peso random", "1.00 Chilean Unit of Account (UF) random", "1.00 Chilean peso random", "1.00 Chilean pesos random", "1.00 Chilean unit of account (UF) random", "1.00 Chilean units of account (UF) random", "1.00 Chinese Yuan random", "1.00 Chinese yuan random", "1.00 Colombian Peso random", "1.00 Colombian peso random", "1.00 Colombian pesos random", "1.00 Comorian Franc random", "1.00 Comorian franc random", "1.00 Comorian francs random", "1.00 Congolese Franc Congolais random", "1.00 Congolese franc Congolais random", "1.00 Congolese francs Congolais random", "1.00 Costa Rican Col\\u00f3n random", "1.00 Costa Rican col\\u00f3n random", "1.00 Costa Rican col\\u00f3ns random", "1.00 Croatian Dinar random", "1.00 Croatian Kuna random", "1.00 Croatian dinar random", "1.00 Croatian dinars random", "1.00 Croatian kuna random", "1.00 Croatian kunas random", "1.00 Cuban Peso random", "1.00 Cuban peso random", "1.00 Cuban pesos random", "1.00 Cypriot Pound random", "1.00 Cypriot pound random", "1.00 Cypriot pounds random", "1.00 Czech Koruna random", "1.00 Czech koruna random", "1.00 Czech korunas random", "1.00 Czechoslovak Hard Koruna random", "1.00 Czechoslovak hard koruna random", "1.00 Czechoslovak hard korunas random", "1.00 Danish Krone random", "1.00 Danish krone random", "1.00 Danish kroner random", "1.00 German Mark random", "1.00 German mark random", "1.00 German marks random", "1.00 Djiboutian Franc random", "1.00 Djiboutian franc random", "1.00 Djiboutian francs random", "1.00 Dominican Peso random", "1.00 Dominican peso random", "1.00 Dominican pesos random", "1.00 East Caribbean Dollar random", "1.00 East Caribbean dollar random", "1.00 East Caribbean dollars random", "1.00 East German Mark random", "1.00 East German mark random", "1.00 East German marks random", "1.00 Ecuadorian Sucre random", "1.00 Ecuadorian Unit of Constant Value random", "1.00 Ecuadorian sucre random", "1.00 Ecuadorian sucres random", "1.00 Ecuadorian unit of constant value random", "1.00 Ecuadorian units of constant value random", "1.00 Egyptian Pound random", "1.00 Egyptian pound random", "1.00 Egyptian pounds random", "1.00 Salvadoran Col\\u00f3n random", "1.00 Salvadoran col\\u00f3n random", "1.00 Salvadoran colones random", "1.00 Equatorial Guinean Ekwele random", "1.00 Equatorial Guinean ekwele random", "1.00 Eritrean Nakfa random", "1.00 Eritrean nakfa random", "1.00 Eritrean nakfas random", "1.00 Estonian Kroon random", "1.00 Estonian kroon random", "1.00 Estonian kroons random", "1.00 Ethiopian Birr random", "1.00 Ethiopian birr random", "1.00 Ethiopian birrs random", "1.00 European Composite Unit random", "1.00 European Currency Unit random", "1.00 European Monetary Unit random", "1.00 European Unit of Account (XBC) random", "1.00 European Unit of Account (XBD) random", "1.00 European composite unit random", "1.00 European composite units random", "1.00 European currency unit random", "1.00 European currency units random", "1.00 European monetary unit random", "1.00 European monetary units random", "1.00 European unit of account (XBC) random", "1.00 European unit of account (XBD) random", "1.00 European units of account (XBC) random", "1.00 European units of account (XBD) random", "1.00 Falkland Islands Pound random", "1.00 Falkland Islands pound random", "1.00 Falkland Islands pounds random", "1.00 Fijian Dollar random", "1.00 Fijian dollar random", "1.00 Fijian dollars random", "1.00 Finnish Markka random", "1.00 Finnish markka random", "1.00 Finnish markkas random", "1.00 French Franc random", "1.00 French Gold Franc random", "1.00 French UIC-Franc random", "1.00 French UIC-franc random", "1.00 French UIC-francs random", "1.00 French franc random", "1.00 French francs random", "1.00 French gold franc random", "1.00 French gold francs random", "1.00 Gambian Dalasi random", "1.00 Gambian dalasi random", "1.00 Gambian dalasis random", "1.00 Georgian Kupon Larit random", "1.00 Georgian Lari random", "1.00 Georgian kupon larit random", "1.00 Georgian kupon larits random", "1.00 Georgian lari random", "1.00 Georgian laris random", "1.00 Ghanaian Cedi (1979\\u20132007) random", "1.00 Ghanaian Cedi random", "1.00 Ghanaian cedi (1979\\u20132007) random", "1.00 Ghanaian cedi random", "1.00 Ghanaian cedis (1979\\u20132007) random", "1.00 Ghanaian cedis random", "1.00 Gibraltar Pound random", "1.00 Gibraltar pound random", "1.00 Gibraltar pounds random", "1.00 Gold random", "1.00 Gold random", "1.00 Greek Drachma random", "1.00 Greek drachma random", "1.00 Greek drachmas random", "1.00 Guatemalan Quetzal random", "1.00 Guatemalan quetzal random", "1.00 Guatemalan quetzals random", "1.00 Guinean Franc random", "1.00 Guinean Syli random", "1.00 Guinean franc random", "1.00 Guinean francs random", "1.00 Guinean syli random", "1.00 Guinean sylis random", "1.00 Guinea-Bissau Peso random", "1.00 Guinea-Bissau peso random", "1.00 Guinea-Bissau pesos random", "1.00 Guyanaese Dollar random", "1.00 Guyanaese dollar random", "1.00 Guyanaese dollars random", "1.00 Haitian Gourde random", "1.00 Haitian gourde random", "1.00 Haitian gourdes random", "1.00 Honduran Lempira random", "1.00 Honduran lempira random", "1.00 Honduran lempiras random", "1.00 Hong Kong Dollar random", "1.00 Hong Kong dollar random", "1.00 Hong Kong dollars random", "1.00 Hungarian Forint random", "1.00 Hungarian forint random", "1.00 Hungarian forints random", "1.00 Icelandic Kr\\u00f3na random", "1.00 Icelandic kr\\u00f3na random", "1.00 Icelandic kr\\u00f3nur random", "1.00 Indian Rupee random", "1.00 Indian rupee random", "1.00 Indian rupees random", "1.00 Indonesian Rupiah random", "1.00 Indonesian rupiah random", "1.00 Indonesian rupiahs random", "1.00 Iranian Rial random", "1.00 Iranian rial random", "1.00 Iranian rials random", "1.00 Iraqi Dinar random", "1.00 Iraqi dinar random", "1.00 Iraqi dinars random", "1.00 Irish Pound random", "1.00 Irish pound random", "1.00 Irish pounds random", "1.00 Israeli Pound random", "1.00 Israeli new shekel random", "1.00 Israeli pound random", "1.00 Israeli pounds random", "1.00 Italian Lira random", "1.00 Italian lira random", "1.00 Italian liras random", "1.00 Jamaican Dollar random", "1.00 Jamaican dollar random", "1.00 Jamaican dollars random", "1.00 Japanese Yen random", "1.00 Japanese yen random", "1.00 Jordanian Dinar random", "1.00 Jordanian dinar random", "1.00 Jordanian dinars random", "1.00 Kazakhstani Tenge random", "1.00 Kazakhstani tenge random", "1.00 Kazakhstani tenges random", "1.00 Kenyan Shilling random", "1.00 Kenyan shilling random", "1.00 Kenyan shillings random", "1.00 Kuwaiti Dinar random", "1.00 Kuwaiti dinar random", "1.00 Kuwaiti dinars random", "1.00 Kyrgystani Som random", "1.00 Kyrgystani som random", "1.00 Kyrgystani soms random", "1.00 Laotian Kip random", "1.00 Laotian kip random", "1.00 Laotian kips random", "1.00 Latvian Lats random", "1.00 Latvian Ruble random", "1.00 Latvian lats random", "1.00 Latvian lati random", "1.00 Latvian ruble random", "1.00 Latvian rubles random", "1.00 Lebanese Pound random", "1.00 Lebanese pound random", "1.00 Lebanese pounds random", "1.00 Lesotho Loti random", "1.00 Lesotho loti random", "1.00 Lesotho lotis random", "1.00 Liberian Dollar random", "1.00 Liberian dollar random", "1.00 Liberian dollars random", "1.00 Libyan Dinar random", "1.00 Libyan dinar random", "1.00 Libyan dinars random", "1.00 Lithuanian Litas random", "1.00 Lithuanian Talonas random", "1.00 Lithuanian litas random", "1.00 Lithuanian litai random", "1.00 Lithuanian talonas random", "1.00 Lithuanian talonases random", "1.00 Luxembourgian Convertible Franc random", "1.00 Luxembourg Financial Franc random", "1.00 Luxembourgian Franc random", "1.00 Luxembourgian convertible franc random", "1.00 Luxembourgian convertible francs random", "1.00 Luxembourg financial franc random", "1.00 Luxembourg financial francs random", "1.00 Luxembourgian franc random", "1.00 Luxembourgian francs random", "1.00 Macanese Pataca random", "1.00 Macanese pataca random", "1.00 Macanese patacas random", "1.00 Macedonian Denar random", "1.00 Macedonian denar random", "1.00 Macedonian denari random", "1.00 Malagasy Ariaries random", "1.00 Malagasy Ariary random", "1.00 Malagasy Ariary random", "1.00 Malagasy Franc random", "1.00 Malagasy franc random", "1.00 Malagasy francs random", "1.00 Malawian Kwacha random", "1.00 Malawian Kwacha random", "1.00 Malawian Kwachas random", "1.00 Malaysian Ringgit random", "1.00 Malaysian ringgit random", "1.00 Malaysian ringgits random", "1.00 Maldivian Rufiyaa random", "1.00 Maldivian rufiyaa random", "1.00 Maldivian rufiyaas random", "1.00 Malian Franc random", "1.00 Malian franc random", "1.00 Malian francs random", "1.00 Maltese Lira random", "1.00 Maltese Pound random", "1.00 Maltese lira random", "1.00 Maltese liras random", "1.00 Maltese pound random", "1.00 Maltese pounds random", "1.00 Mauritanian Ouguiya random", "1.00 Mauritanian ouguiya random", "1.00 Mauritanian ouguiyas random", "1.00 Mauritian Rupee random", "1.00 Mauritian rupee random", "1.00 Mauritian rupees random", "1.00 Mexican Peso random", "1.00 Mexican Silver Peso (1861\\u20131992) random", "1.00 Mexican Investment Unit random", "1.00 Mexican peso random", "1.00 Mexican pesos random", "1.00 Mexican silver peso (1861\\u20131992) random", "1.00 Mexican silver pesos (1861\\u20131992) random", "1.00 Mexican investment unit random", "1.00 Mexican investment units random", "1.00 Moldovan Leu random", "1.00 Moldovan leu random", "1.00 Moldovan lei random", "1.00 Mongolian Tugrik random", "1.00 Mongolian tugrik random", "1.00 Mongolian tugriks random", "1.00 Moroccan Dirham random", "1.00 Moroccan Franc random", "1.00 Moroccan dirham random", "1.00 Moroccan dirhams random", "1.00 Moroccan franc random", "1.00 Moroccan francs random", "1.00 Mozambican Escudo random", "1.00 Mozambican Metical random", "1.00 Mozambican escudo random", "1.00 Mozambican escudos random", "1.00 Mozambican metical random", "1.00 Mozambican meticals random", "1.00 Myanmar Kyat random", "1.00 Myanmar kyat random", "1.00 Myanmar kyats random", "1.00 Namibian Dollar random", "1.00 Namibian dollar random", "1.00 Namibian dollars random", "1.00 Nepalese Rupee random", "1.00 Nepalese rupee random", "1.00 Nepalese rupees random", "1.00 Netherlands Antillean Guilder random", "1.00 Netherlands Antillean guilder random", "1.00 Netherlands Antillean guilders random", "1.00 Dutch Guilder random", "1.00 Dutch guilder random", "1.00 Dutch guilders random", "1.00 Israeli New Shekel random", "1.00 Israeli new shekels random", "1.00 New Zealand Dollar random", "1.00 New Zealand dollar random", "1.00 New Zealand dollars random", "1.00 Nicaraguan C\\u00f3rdoba random", "1.00 Nicaraguan C\\u00f3rdoba (1988\\u20131991) random", "1.00 Nicaraguan c\\u00f3rdoba random", "1.00 Nicaraguan c\\u00f3rdoba random", "1.00 Nicaraguan c\\u00f3rdoba (1988\\u20131991) random", "1.00 Nicaraguan c\\u00f3rdobas (1988\\u20131991) random", "1.00 Nigerian Naira random", "1.00 Nigerian naira random", "1.00 Nigerian nairas random", "1.00 North Korean Won random", "1.00 North Korean won random", "1.00 North Korean won random", "1.00 Norwegian Krone random", "1.00 Norwegian krone random", "1.00 Norwegian kroner random", "1.00 Mozambican Metical (1980\\u20132006) random", "1.00 Mozambican metical (1980\\u20132006) random", "1.00 Mozambican meticals (1980\\u20132006) random", "1.00 Romanian Lei (1952\\u20132006) random", "1.00 Romanian Leu (1952\\u20132006) random", "1.00 Romanian leu (1952\\u20132006) random", "1.00 Serbian Dinar (2002\\u20132006) random", "1.00 Serbian dinar (2002\\u20132006) random", "1.00 Serbian dinars (2002\\u20132006) random", "1.00 Sudanese Dinar (1992\\u20132007) random", "1.00 Sudanese Pound (1957\\u20131998) random", "1.00 Sudanese dinar (1992\\u20132007) random", "1.00 Sudanese dinars (1992\\u20132007) random", "1.00 Sudanese pound (1957\\u20131998) random", "1.00 Sudanese pounds (1957\\u20131998) random", "1.00 Turkish Lira (1922\\u20132005) random", "1.00 Turkish Lira (1922\\u20132005) random", "1.00 Omani Rial random", "1.00 Omani rial random", "1.00 Omani rials random", "1.00 Pakistani Rupee random", "1.00 Pakistani rupee random", "1.00 Pakistani rupees random", "1.00 Palladium random", "1.00 Palladium random", "1.00 Panamanian Balboa random", "1.00 Panamanian balboa random", "1.00 Panamanian balboas random", "1.00 Papua New Guinean Kina random", "1.00 Papua New Guinean kina random", "1.00 Papua New Guinean kina random", "1.00 Paraguayan Guarani random", "1.00 Paraguayan guarani random", "1.00 Paraguayan guaranis random", "1.00 Peruvian Inti random", "1.00 Peruvian Sol random", "1.00 Peruvian Sol (1863\\u20131965) random", "1.00 Peruvian inti random", "1.00 Peruvian intis random", "1.00 Peruvian sol random", "1.00 Peruvian soles random", "1.00 Peruvian sol (1863\\u20131965) random", "1.00 Peruvian soles (1863\\u20131965) random", "1.00 Philippine Piso random", "1.00 Philippine piso random", "1.00 Philippine pisos random", "1.00 Platinum random", "1.00 Platinum random", "1.00 Polish Zloty (1950\\u20131995) random", "1.00 Polish Zloty random", "1.00 Polish zlotys random", "1.00 Polish zloty (PLZ) random", "1.00 Polish zloty random", "1.00 Polish zlotys (PLZ) random", "1.00 Portuguese Escudo random", "1.00 Portuguese Guinea Escudo random", "1.00 Portuguese Guinea escudo random", "1.00 Portuguese Guinea escudos random", "1.00 Portuguese escudo random", "1.00 Portuguese escudos random", "1.00 Qatari Rial random", "1.00 Qatari rial random", "1.00 Qatari rials random", "1.00 RINET Funds random", "1.00 RINET Funds random", "1.00 Rhodesian Dollar random", "1.00 Rhodesian dollar random", "1.00 Rhodesian dollars random", "1.00 Romanian Leu random", "1.00 Romanian lei random", "1.00 Romanian leu random", "1.00 Russian Ruble (1991\\u20131998) random", "1.00 Russian Ruble random", "1.00 Russian ruble (1991\\u20131998) random", "1.00 Russian ruble random", "1.00 Russian rubles (1991\\u20131998) random", "1.00 Russian rubles random", "1.00 Rwandan Franc random", "1.00 Rwandan franc random", "1.00 Rwandan francs random", "1.00 St. Helena Pound random", "1.00 St. Helena pound random", "1.00 St. Helena pounds random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobra random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobra random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobras random", "1.00 Saudi Riyal random", "1.00 Saudi riyal random", "1.00 Saudi riyals random", "1.00 Serbian Dinar random", "1.00 Serbian dinar random", "1.00 Serbian dinars random", "1.00 Seychellois Rupee random", "1.00 Seychellois rupee random", "1.00 Seychellois rupees random", "1.00 Sierra Leonean Leone random", "1.00 Sierra Leonean leone random", "1.00 Sierra Leonean leones random", "1.00 Singapore Dollar random", "1.00 Singapore dollar random", "1.00 Singapore dollars random", "1.00 Slovak Koruna random", "1.00 Slovak koruna random", "1.00 Slovak korunas random", "1.00 Slovenian Tolar random", "1.00 Slovenian tolar random", "1.00 Slovenian tolars random", "1.00 Solomon Islands Dollar random", "1.00 Solomon Islands dollar random", "1.00 Solomon Islands dollars random", "1.00 Somali Shilling random", "1.00 Somali shilling random", "1.00 Somali shillings random", "1.00 South African Rand (financial) random", "1.00 South African Rand random", "1.00 South African rand (financial) random", "1.00 South African rand random", "1.00 South African rands (financial) random", "1.00 South African rand random", "1.00 South Korean Won random", "1.00 South Korean won random", "1.00 South Korean won random", "1.00 Soviet Rouble random", "1.00 Soviet rouble random", "1.00 Soviet roubles random", "1.00 Spanish Peseta (A account) random", "1.00 Spanish Peseta (convertible account) random", "1.00 Spanish Peseta random", "1.00 Spanish peseta (A account) random", "1.00 Spanish peseta (convertible account) random", "1.00 Spanish peseta random", "1.00 Spanish pesetas (A account) random", "1.00 Spanish pesetas (convertible account) random", "1.00 Spanish pesetas random", "1.00 Special Drawing Rights random", "1.00 Sri Lankan Rupee random", "1.00 Sri Lankan rupee random", "1.00 Sri Lankan rupees random", "1.00 Sudanese Pound random", "1.00 Sudanese pound random", "1.00 Sudanese pounds random", "1.00 Surinamese Dollar random", "1.00 Surinamese dollar random", "1.00 Surinamese dollars random", "1.00 Surinamese Guilder random", "1.00 Surinamese guilder random", "1.00 Surinamese guilders random", "1.00 Swazi Lilangeni random", "1.00 Swazi lilangeni random", "1.00 Swazi emalangeni random", "1.00 Swedish Krona random", "1.00 Swedish krona random", "1.00 Swedish kronor random", "1.00 Swiss Franc random", "1.00 Swiss franc random", "1.00 Swiss francs random", "1.00 Syrian Pound random", "1.00 Syrian pound random", "1.00 Syrian pounds random", "1.00 New Taiwan Dollar random", "1.00 New Taiwan dollar random", "1.00 New Taiwan dollars random", "1.00 Tajikistani Ruble random", "1.00 Tajikistani Somoni random", "1.00 Tajikistani ruble random", "1.00 Tajikistani rubles random", "1.00 Tajikistani somoni random", "1.00 Tajikistani somonis random", "1.00 Tanzanian Shilling random", "1.00 Tanzanian shilling random", "1.00 Tanzanian shillings random", "1.00 Testing Currency Code random", "1.00 Testing Currency Code random", "1.00 Thai Baht random", "1.00 Thai baht random", "1.00 Thai baht random", "1.00 Timorese Escudo random", "1.00 Timorese escudo random", "1.00 Timorese escudos random", "1.00 Trinidad & Tobago Dollar random", "1.00 Trinidad & Tobago dollar random", "1.00 Trinidad & Tobago dollars random", "1.00 Tunisian Dinar random", "1.00 Tunisian dinar random", "1.00 Tunisian dinars random", "1.00 Turkish Lira random", "1.00 Turkish Lira random", "1.00 Turkish lira random", "1.00 Turkmenistani Manat random", "1.00 Turkmenistani manat random", "1.00 Turkmenistani manat random", "1.00 US Dollar (Next day) random", "1.00 US Dollar (Same day) random", "1.00 US Dollar random", "1.00 US dollar (next day) random", "1.00 US dollar (same day) random", "1.00 US dollar random", "1.00 US dollars (next day) random", "1.00 US dollars (same day) random", "1.00 US dollars random", "1.00 Ugandan Shilling (1966\\u20131987) random", "1.00 Ugandan Shilling random", "1.00 Ugandan shilling (1966\\u20131987) random", "1.00 Ugandan shilling random", "1.00 Ugandan shillings (1966\\u20131987) random", "1.00 Ugandan shillings random", "1.00 Ukrainian Hryvnia random", "1.00 Ukrainian Karbovanets random", "1.00 Ukrainian hryvnia random", "1.00 Ukrainian hryvnias random", "1.00 Ukrainian karbovanets random", "1.00 Ukrainian karbovantsiv random", "1.00 Colombian Real Value Unit random", "1.00 United Arab Emirates Dirham random", "1.00 Unknown Currency random", "1.00 Uruguayan Peso (1975\\u20131993) random", "1.00 Uruguayan Peso random", "1.00 Uruguayan Peso (Indexed Units) random", "1.00 Uruguayan peso (1975\\u20131993) random", "1.00 Uruguayan peso (indexed units) random", "1.00 Uruguayan peso random", "1.00 Uruguayan pesos (1975\\u20131993) random", "1.00 Uruguayan pesos (indexed units) random", "1.00 Uzbekistani Som random", "1.00 Uzbekistani som random", "1.00 Uzbekistani som random", "1.00 Vanuatu Vatu random", "1.00 Vanuatu vatu random", "1.00 Vanuatu vatus random", "1.00 Venezuelan Bol\\u00edvar random", "1.00 Venezuelan Bol\\u00edvar (1871\\u20132008) random", "1.00 Venezuelan bol\\u00edvar random", "1.00 Venezuelan bol\\u00edvars random", "1.00 Venezuelan bol\\u00edvar (1871\\u20132008) random", "1.00 Venezuelan bol\\u00edvars (1871\\u20132008) random", "1.00 Vietnamese Dong random", "1.00 Vietnamese dong random", "1.00 Vietnamese dong random", "1.00 WIR Euro random", "1.00 WIR Franc random", "1.00 WIR euro random", "1.00 WIR euros random", "1.00 WIR franc random", "1.00 WIR francs random", "1.00 Samoan Tala random", "1.00 Samoan tala random", "1.00 Samoan tala random", "1.00 Yemeni Dinar random", "1.00 Yemeni Rial random", "1.00 Yemeni dinar random", "1.00 Yemeni dinars random", "1.00 Yemeni rial random", "1.00 Yemeni rials random", "1.00 Yugoslavian Convertible Dinar (1990\\u20131992) random", "1.00 Yugoslavian Hard Dinar (1966\\u20131990) random", "1.00 Yugoslavian New Dinar (1994\\u20132002) random", "1.00 Yugoslavian convertible dinar (1990\\u20131992) random", "1.00 Yugoslavian convertible dinars (1990\\u20131992) random", "1.00 Yugoslavian hard dinar (1966\\u20131990) random", "1.00 Yugoslavian hard dinars (1966\\u20131990) random", "1.00 Yugoslavian new dinar (1994\\u20132002) random", "1.00 Yugoslavian new dinars (1994\\u20132002) random", "1.00 Zairean New Zaire (1993\\u20131998) random", "1.00 Zairean Zaire (1971\\u20131993) random", "1.00 Zairean new zaire (1993\\u20131998) random", "1.00 Zairean new zaires (1993\\u20131998) random", "1.00 Zairean zaire (1971\\u20131993) random", "1.00 Zairean zaires (1971\\u20131993) random", "1.00 Zambian Kwacha random", "1.00 Zambian kwacha random", "1.00 Zambian kwachas random", "1.00 Zimbabwean Dollar (1980\\u20132008) random", "1.00 Zimbabwean dollar (1980\\u20132008) random", "1.00 Zimbabwean dollars (1980\\u20132008) random", "1.00 euro random", "1.00 euros random", "1.00 Turkish lira (1922\\u20132005) random", "1.00 special drawing rights random", "1.00 Colombian real value unit random", "1.00 Colombian real value units random", "1.00 unknown currency random", }; const char* WRONG_DATA[] = { // Following are missing one last char in the currency name "1.00 Nicaraguan Cordob", "1.00 Namibian Dolla", "1.00 Namibian dolla", "1.00 Nepalese Rupe", "1.00 Nepalese rupe", "1.00 Netherlands Antillean Guilde", "1.00 Netherlands Antillean guilde", "1.00 Dutch Guilde", "1.00 Dutch guilde", "1.00 Israeli New Sheqe", "1.00 New Zealand Dolla", "1.00 New Zealand dolla", "1.00 Nicaraguan cordob", "1.00 Nigerian Nair", "1.00 Nigerian nair", "1.00 North Korean Wo", "1.00 North Korean wo", "1.00 Norwegian Kron", "1.00 Norwegian kron", "1.00 US dolla", "1.00", "A1.00", "AD1.00", "AE1.00", "AF1.00", "AL1.00", "AM1.00", "AN1.00", "AO1.00", "AR1.00", "AT1.00", "AU1.00", "AW1.00", "AZ1.00", "Afghan Afghan1.00", "Afghan Afghani (1927\\u201320021.00", "Afl1.00", "Albanian Le1.00", "Algerian Dina1.00", "Andorran Peset1.00", "Angolan Kwanz1.00", "Angolan Kwanza (1977\\u201319901.00", "Angolan Readjusted Kwanza (1995\\u201319991.00", "Angolan New Kwanza (1990\\u201320001.00", "Argentine Austra1.00", "Argentine Pes1.00", "Argentine Peso (1983\\u201319851.00", "Armenian Dra1.00", "Aruban Flori1.00", "Australian Dolla1.00", "Austrian Schillin1.00", "Azerbaijani Mana1.00", "Azerbaijani Manat (1993\\u201320061.00", "B1.00", "BA1.00", "BB1.00", "BE1.00", "BG1.00", "BH1.00", "BI1.00", "BM1.00", "BN1.00", "BO1.00", "BR1.00", "BS1.00", "BT1.00", "BU1.00", "BW1.00", "BY1.00", "BZ1.00", "Bahamian Dolla1.00", "Bahraini Dina1.00", "Bangladeshi Tak1.00", "Barbadian Dolla1.00", "Bds1.00", "Belarusian Ruble (1994\\u201319991.00", "Belarusian Rubl1.00", "Belgian Fran1.00", "Belgian Franc (convertible1.00", "Belgian Franc (financial1.00", "Belize Dolla1.00", "Bermudan Dolla1.00", "Bhutanese Ngultru1.00", "Bolivian Mvdo1.00", "Bolivian Pes1.00", "Bolivian Bolivian1.00", "Bosnia-Herzegovina Convertible Mar1.00", "Bosnia-Herzegovina Dina1.00", "Botswanan Pul1.00", "Brazilian Cruzad1.00", "Brazilian Cruzado Nov1.00", "Brazilian Cruzeir1.00", "Brazilian Cruzeiro (1990\\u201319931.00", "Brazilian New Cruzeiro (1967\\u201319861.00", "Brazilian Rea1.00", "British Pound Sterlin1.00", "Brunei Dolla1.00", "Bulgarian Hard Le1.00", "Bulgarian Le1.00", "Burmese Kya1.00", "Burundian Fran1.00", "C1.00", "CA1.00", "CD1.00", "CFP Fran1.00", "CFP1.00", "CH1.00", "CL1.00", "CN1.00", "CO1.00", "CS1.00", "CU1.00", "CV1.00", "CY1.00", "CZ1.00", "Cambodian Rie1.00", "Canadian Dolla1.00", "Cape Verdean Escud1.00", "Cayman Islands Dolla1.00", "Chilean Pes1.00", "Chilean Unit of Accoun1.00", "Chinese Yua1.00", "Colombian Pes1.00", "Comoro Fran1.00", "Congolese Fran1.00", "Costa Rican Col\\u00f31.00", "Croatian Dina1.00", "Croatian Kun1.00", "Cuban Pes1.00", "Cypriot Poun1.00", "Czech Republic Korun1.00", "Czechoslovak Hard Korun1.00", "D1.00", "DD1.00", "DE1.00", "DJ1.00", "DK1.00", "DO1.00", "DZ1.00", "Danish Kron1.00", "German Mar1.00", "Djiboutian Fran1.00", "Dk1.00", "Dominican Pes1.00", "EC1.00", "EE1.00", "EG1.00", "EQ1.00", "ER1.00", "ES1.00", "ET1.00", "EU1.00", "East Caribbean Dolla1.00", "East German Ostmar1.00", "Ecuadorian Sucr1.00", "Ecuadorian Unit of Constant Valu1.00", "Egyptian Poun1.00", "Ekwel1.00", "Salvadoran Col\\u00f31.00", "Equatorial Guinean Ekwel1.00", "Eritrean Nakf1.00", "Es1.00", "Estonian Kroo1.00", "Ethiopian Bir1.00", "Eur1.00", "European Composite Uni1.00", "European Currency Uni1.00", "European Monetary Uni1.00", "European Unit of Account (XBC1.00", "European Unit of Account (XBD1.00", "F1.00", "FB1.00", "FI1.00", "FJ1.00", "FK1.00", "FR1.00", "Falkland Islands Poun1.00", "Fd1.00", "Fijian Dolla1.00", "Finnish Markk1.00", "Fr1.00", "French Fran1.00", "French Gold Fran1.00", "French UIC-Fran1.00", "G1.00", "GB1.00", "GE1.00", "GH1.00", "GI1.00", "GM1.00", "GN1.00", "GQ1.00", "GR1.00", "GT1.00", "GW1.00", "GY1.00", "Gambian Dalas1.00", "Georgian Kupon Lari1.00", "Georgian Lar1.00", "Ghanaian Ced1.00", "Ghanaian Cedi (1979\\u201320071.00", "Gibraltar Poun1.00", "Gol1.00", "Greek Drachm1.00", "Guatemalan Quetza1.00", "Guinean Fran1.00", "Guinean Syl1.00", "Guinea-Bissau Pes1.00", "Guyanaese Dolla1.00", "HK1.00", "HN1.00", "HR1.00", "HT1.00", "HU1.00", "Haitian Gourd1.00", "Honduran Lempir1.00", "Hong Kong Dolla1.00", "Hungarian Forin1.00", "I1.00", "IE1.00", "IL1.00", "IN1.00", "IQ1.00", "IR1.00", "IS1.00", "IT1.00", "Icelandic Kron1.00", "Indian Rupe1.00", "Indonesian Rupia1.00", "Iranian Ria1.00", "Iraqi Dina1.00", "Irish Poun1.00", "Israeli Poun1.00", "Italian Lir1.00", "J1.00", "JM1.00", "JO1.00", "JP1.00", "Jamaican Dolla1.00", "Japanese Ye1.00", "Jordanian Dina1.00", "K S1.00", "K1.00", "KE1.00", "KG1.00", "KH1.00", "KP1.00", "KR1.00", "KW1.00", "KY1.00", "KZ1.00", "Kazakhstani Teng1.00", "Kenyan Shillin1.00", "Kuwaiti Dina1.00", "Kyrgystani So1.00", "LA1.00", "LB1.00", "LK1.00", "LR1.00", "LT1.00", "LU1.00", "LV1.00", "LY1.00", "Laotian Ki1.00", "Latvian Lat1.00", "Latvian Rubl1.00", "Lebanese Poun1.00", "Lesotho Lot1.00", "Liberian Dolla1.00", "Libyan Dina1.00", "Lithuanian Lit1.00", "Lithuanian Talona1.00", "Luxembourgian Convertible Fran1.00", "Luxembourg Financial Fran1.00", "Luxembourgian Fran1.00", "MA1.00", "MD1.00", "MDe1.00", "MEX1.00", "MG1.00", "ML1.00", "MM1.00", "MN1.00", "MO1.00", "MR1.00", "MT1.00", "MU1.00", "MV1.00", "MW1.00", "MX1.00", "MY1.00", "MZ1.00", "Macanese Patac1.00", "Macedonian Dena1.00", "Malagasy Ariar1.00", "Malagasy Fran1.00", "Malawian Kwach1.00", "Malaysian Ringgi1.00", "Maldivian Rufiya1.00", "Malian Fran1.00", "Malot1.00", "Maltese Lir1.00", "Maltese Poun1.00", "Mauritanian Ouguiy1.00", "Mauritian Rupe1.00", "Mexican Pes1.00", "Mexican Silver Peso (1861\\u201319921.00", "Mexican Investment Uni1.00", "Moldovan Le1.00", "Mongolian Tugri1.00", "Moroccan Dirha1.00", "Moroccan Fran1.00", "Mozambican Escud1.00", "Mozambican Metica1.00", "Myanmar Kya1.00", "N1.00", "NA1.00", "NAf1.00", "NG1.00", "NI1.00", "NK1.00", "NL1.00", "NO1.00", "NP1.00", "NT1.00", "Namibian Dolla1.00", "Nepalese Rupe1.00", "Netherlands Antillean Guilde1.00", "Dutch Guilde1.00", "Israeli New Sheqe1.00", "New Zealand Dolla1.00", "Nicaraguan C\\u00f3rdoba (1988\\u201319911.00", "Nicaraguan C\\u00f3rdob1.00", "Nigerian Nair1.00", "North Korean Wo1.00", "Norwegian Kron1.00", "Nr1.00", "OM1.00", "Old Mozambican Metica1.00", "Romanian Leu (1952\\u201320061.00", "Serbian Dinar (2002\\u201320061.00", "Sudanese Dinar (1992\\u201320071.00", "Sudanese Pound (1957\\u201319981.00", "Turkish Lira (1922\\u201320051.00", "Omani Ria1.00", "PA1.00", "PE1.00", "PG1.00", "PH1.00", "PK1.00", "PL1.00", "PT1.00", "PY1.00", "Pakistani Rupe1.00", "Palladiu1.00", "Panamanian Balbo1.00", "Papua New Guinean Kin1.00", "Paraguayan Guaran1.00", "Peruvian Int1.00", "Peruvian Sol (1863\\u201319651.00", "Peruvian Sol Nuev1.00", "Philippine Pes1.00", "Platinu1.00", "Polish Zlot1.00", "Polish Zloty (1950\\u201319951.00", "Portuguese Escud1.00", "Portuguese Guinea Escud1.00", "Pr1.00", "QA1.00", "Qatari Ria1.00", "RD1.00", "RH1.00", "RINET Fund1.00", "RS1.00", "RU1.00", "RW1.00", "Rb1.00", "Rhodesian Dolla1.00", "Romanian Le1.00", "Russian Rubl1.00", "Russian Ruble (1991\\u201319981.00", "Rwandan Fran1.00", "S1.00", "SA1.00", "SB1.00", "SC1.00", "SD1.00", "SE1.00", "SG1.00", "SH1.00", "SI1.00", "SK1.00", "SL R1.00", "SL1.00", "SO1.00", "ST1.00", "SU1.00", "SV1.00", "SY1.00", "SZ1.00", "St. Helena Poun1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobr1.00", "Saudi Riya1.00", "Serbian Dina1.00", "Seychellois Rupe1.00", "Sh1.00", "Sierra Leonean Leon1.00", "Silve1.00", "Singapore Dolla1.00", "Slovak Korun1.00", "Slovenian Tola1.00", "Solomon Islands Dolla1.00", "Somali Shillin1.00", "South African Ran1.00", "South African Rand (financial1.00", "South Korean Wo1.00", "Soviet Roubl1.00", "Spanish Peset1.00", "Spanish Peseta (A account1.00", "Spanish Peseta (convertible account1.00", "Special Drawing Right1.00", "Sri Lankan Rupe1.00", "Sudanese Poun1.00", "Surinamese Dolla1.00", "Surinamese Guilde1.00", "Swazi Lilangen1.00", "Swedish Kron1.00", "Swiss Fran1.00", "Syrian Poun1.00", "T S1.00", "TH1.00", "TJ1.00", "TM1.00", "TN1.00", "TO1.00", "TP1.00", "TR1.00", "TT1.00", "TW1.00", "TZ1.00", "New Taiwan Dolla1.00", "Tajikistani Rubl1.00", "Tajikistani Somon1.00", "Tanzanian Shillin1.00", "Testing Currency Cod1.00", "Thai Bah1.00", "Timorese Escud1.00", "Tongan Pa\\u20bbang1.00", "Trinidad & Tobago Dolla1.00", "Tunisian Dina1.00", "Turkish Lir1.00", "Turkmenistani Mana1.00", "U S1.00", "U1.00", "UA1.00", "UG1.00", "US Dolla1.00", "US Dollar (Next day1.00", "US Dollar (Same day1.00", "US1.00", "UY1.00", "UZ1.00", "Ugandan Shillin1.00", "Ugandan Shilling (1966\\u201319871.00", "Ukrainian Hryvni1.00", "Ukrainian Karbovanet1.00", "Colombian Real Value Uni1.00", "United Arab Emirates Dirha1.00", "Unknown Currenc1.00", "Ur1.00", "Uruguay Peso (1975\\u201319931.00", "Uruguay Peso Uruguay1.00", "Uruguay Peso (Indexed Units1.00", "Uzbekistani So1.00", "V1.00", "VE1.00", "VN1.00", "VU1.00", "Vanuatu Vat1.00", "Venezuelan Bol\\u00edva1.00", "Venezuelan Bol\\u00edvar Fuert1.00", "Vietnamese Don1.00", "West African CFA Fran1.00", "Central African CFA Fran1.00", "WIR Eur1.00", "WIR Fran1.00", "WS1.00", "Samoa Tal1.00", "XA1.00", "XB1.00", "XC1.00", "XD1.00", "XE1.00", "XF1.00", "XO1.00", "XP1.00", "XR1.00", "XT1.00", "XX1.00", "YD1.00", "YE1.00", "YU1.00", "Yemeni Dina1.00", "Yemeni Ria1.00", "Yugoslavian Convertible Dina1.00", "Yugoslavian Hard Dinar (1966\\u201319901.00", "Yugoslavian New Dina1.00", "Z1.00", "ZA1.00", "ZM1.00", "ZR1.00", "ZW1.00", "Zairean New Zaire (1993\\u201319981.00", "Zairean Zair1.00", "Zambian Kwach1.00", "Zimbabwean Dollar (1980\\u201320081.00", "dra1.00", "lar1.00", "le1.00", "man1.00", "so1.00", }; Locale locale("en_US"); for (uint32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { UnicodeString formatted = ctou(DATA[i]); UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> numFmt(NumberFormat::createInstance(locale, UNUM_CURRENCY, status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); ParsePosition parsePos; LocalPointer<CurrencyAmount> currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); if ( doubleVal != 1.0 ) { errln("Parsed as currency value other than 1.0: " + formatted + " -> " + doubleVal); } } else { errln("Failed to parse as currency: " + formatted); } } for (uint32_t i=0; i<UPRV_LENGTHOF(WRONG_DATA); ++i) { UnicodeString formatted = ctou(WRONG_DATA[i]); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, UNUM_CURRENCY, status); if (numFmt != NULL && U_SUCCESS(status)) { ParsePosition parsePos; LocalPointer<CurrencyAmount> currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); errln("Parsed as currency, should not have: " + formatted + " -> " + doubleVal); } } else { dataerrln("Unable to create NumberFormat. - %s", u_errorName(status)); delete numFmt; break; } delete numFmt; } } const char* attrString(int32_t); // UnicodeString s; // std::string ss; // std::cout << s.toUTF8String(ss) void NumberFormatTest::expectPositions(FieldPositionIterator& iter, int32_t *values, int32_t tupleCount, const UnicodeString& str) { UBool found[10]; FieldPosition fp; if (tupleCount > 10) { assertTrue("internal error, tupleCount too large", FALSE); } else { for (int i = 0; i < tupleCount; ++i) { found[i] = FALSE; } } logln(str); while (iter.next(fp)) { UBool ok = FALSE; int32_t id = fp.getField(); int32_t start = fp.getBeginIndex(); int32_t limit = fp.getEndIndex(); // is there a logln using printf? char buf[128]; sprintf(buf, "%24s %3d %3d %3d", attrString(id), id, start, limit); logln(buf); for (int i = 0; i < tupleCount; ++i) { if (found[i]) { continue; } if (values[i*3] == id && values[i*3+1] == start && values[i*3+2] == limit) { found[i] = ok = TRUE; break; } } assertTrue((UnicodeString)"found [" + id + "," + start + "," + limit + "]", ok); } // check that all were found UBool ok = TRUE; for (int i = 0; i < tupleCount; ++i) { if (!found[i]) { ok = FALSE; assertTrue((UnicodeString) "missing [" + values[i*3] + "," + values[i*3+1] + "," + values[i*3+2] + "]", found[i]); } } assertTrue("no expected values were missing", ok); } void NumberFormatTest::expectPosition(FieldPosition& pos, int32_t id, int32_t start, int32_t limit, const UnicodeString& str) { logln(str); assertTrue((UnicodeString)"id " + id + " == " + pos.getField(), id == pos.getField()); assertTrue((UnicodeString)"begin " + start + " == " + pos.getBeginIndex(), start == pos.getBeginIndex()); assertTrue((UnicodeString)"end " + limit + " == " + pos.getEndIndex(), limit == pos.getEndIndex()); } void NumberFormatTest::TestFieldPositionIterator() { // bug 7372 UErrorCode status = U_ZERO_ERROR; FieldPositionIterator iter1; FieldPositionIterator iter2; FieldPosition pos; DecimalFormat *decFmt = (DecimalFormat *) NumberFormat::createInstance(status); if (failure(status, "NumberFormat::createInstance", TRUE)) return; double num = 1234.56; UnicodeString str1; UnicodeString str2; assertTrue((UnicodeString)"self==", iter1 == iter1); assertTrue((UnicodeString)"iter1==iter2", iter1 == iter2); decFmt->format(num, str1, &iter1, status); assertTrue((UnicodeString)"iter1 != iter2", iter1 != iter2); decFmt->format(num, str2, &iter2, status); assertTrue((UnicodeString)"iter1 == iter2 (2)", iter1 == iter2); iter1.next(pos); assertTrue((UnicodeString)"iter1 != iter2 (2)", iter1 != iter2); iter2.next(pos); assertTrue((UnicodeString)"iter1 == iter2 (3)", iter1 == iter2); // should format ok with no iterator str2.remove(); decFmt->format(num, str2, NULL, status); assertEquals("null fpiter", str1, str2); delete decFmt; } void NumberFormatTest::TestFormatAttributes() { Locale locale("en_US"); UErrorCode status = U_ZERO_ERROR; DecimalFormat *decFmt = (DecimalFormat *) NumberFormat::createInstance(locale, UNUM_CURRENCY, status); if (failure(status, "NumberFormat::createInstance", TRUE)) return; double val = 12345.67; { int32_t expected[] = { UNUM_CURRENCY_FIELD, 0, 1, UNUM_GROUPING_SEPARATOR_FIELD, 3, 4, UNUM_INTEGER_FIELD, 1, 7, UNUM_DECIMAL_SEPARATOR_FIELD, 7, 8, UNUM_FRACTION_FIELD, 8, 10, }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; FieldPositionIterator posIter; UnicodeString result; decFmt->format(val, result, &posIter, status); expectPositions(posIter, expected, tupleCount, result); } { FieldPosition fp(UNUM_INTEGER_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_INTEGER_FIELD, 1, 7, result); } { FieldPosition fp(UNUM_FRACTION_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_FRACTION_FIELD, 8, 10, result); } delete decFmt; decFmt = (DecimalFormat *) NumberFormat::createInstance(locale, UNUM_SCIENTIFIC, status); val = -0.0000123; { int32_t expected[] = { UNUM_SIGN_FIELD, 0, 1, UNUM_INTEGER_FIELD, 1, 2, UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3, UNUM_FRACTION_FIELD, 3, 5, UNUM_EXPONENT_SYMBOL_FIELD, 5, 6, UNUM_EXPONENT_SIGN_FIELD, 6, 7, UNUM_EXPONENT_FIELD, 7, 8 }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; FieldPositionIterator posIter; UnicodeString result; decFmt->format(val, result, &posIter, status); expectPositions(posIter, expected, tupleCount, result); } { FieldPosition fp(UNUM_INTEGER_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_INTEGER_FIELD, 1, 2, result); } { FieldPosition fp(UNUM_FRACTION_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_FRACTION_FIELD, 3, 5, result); } delete decFmt; fflush(stderr); } const char* attrString(int32_t attrId) { switch (attrId) { case UNUM_INTEGER_FIELD: return "integer"; case UNUM_FRACTION_FIELD: return "fraction"; case UNUM_DECIMAL_SEPARATOR_FIELD: return "decimal separator"; case UNUM_EXPONENT_SYMBOL_FIELD: return "exponent symbol"; case UNUM_EXPONENT_SIGN_FIELD: return "exponent sign"; case UNUM_EXPONENT_FIELD: return "exponent"; case UNUM_GROUPING_SEPARATOR_FIELD: return "grouping separator"; case UNUM_CURRENCY_FIELD: return "currency"; case UNUM_PERCENT_FIELD: return "percent"; case UNUM_PERMILL_FIELD: return "permille"; case UNUM_SIGN_FIELD: return "sign"; default: return ""; } } // // Test formatting & parsing of big decimals. // API test, not a comprehensive test. // See DecimalFormatTest/DataDrivenTests // #define ASSERT_SUCCESS(status) { \ assertSuccess(UnicodeString("file ") + __FILE__ + ", line " + __LINE__, (status)); \ } #define ASSERT_EQUALS(expected, actual) { \ assertEquals(UnicodeString("file ") + __FILE__ + ", line " + __LINE__, (expected), (actual)); \ } void NumberFormatTest::TestDecimal() { { UErrorCode status = U_ZERO_ERROR; Formattable f("12.345678999987654321E666", status); ASSERT_SUCCESS(status); StringPiece s = f.getDecimalNumber(status); ASSERT_SUCCESS(status); ASSERT_EQUALS("1.2345678999987654321E+667", s.data()); //printf("%s\n", s.data()); } { UErrorCode status = U_ZERO_ERROR; Formattable f1("this is not a number", status); ASSERT_EQUALS(U_DECIMAL_NUMBER_SYNTAX_ERROR, status); } { UErrorCode status = U_ZERO_ERROR; Formattable f; f.setDecimalNumber("123.45", status); ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kDouble, f.getType()); ASSERT_EQUALS(123.45, f.getDouble()); ASSERT_EQUALS(123.45, f.getDouble(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("123.45", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); f.setDecimalNumber("4.5678E7", status); int32_t n; n = f.getLong(); ASSERT_EQUALS(45678000, n); status = U_ZERO_ERROR; f.setDecimalNumber("-123", status); ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kLong, f.getType()); ASSERT_EQUALS(-123, f.getLong()); ASSERT_EQUALS(-123, f.getLong(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("-123", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); status = U_ZERO_ERROR; f.setDecimalNumber("1234567890123", status); // Number too big for 32 bits ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kInt64, f.getType()); ASSERT_EQUALS(1234567890123LL, f.getInt64()); ASSERT_EQUALS(1234567890123LL, f.getInt64(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("1.234567890123E+12", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); } { UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString formattedResult; StringPiece num("244444444444444444444444444444444444446.4"); fmtr->format(num, formattedResult, NULL, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("244,444,444,444,444,444,444,444,444,444,444,444,446.4", formattedResult); //std::string ss; std::cout << formattedResult.toUTF8String(ss); delete fmtr; } } { // Check formatting a DigitList. DigitList is internal, but this is // a critical interface that must work. UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString formattedResult; DecimalQuantity dl; StringPiece num("123.4566666666666666666666666666666666621E+40"); dl.setToDecNumber(num, status); ASSERT_SUCCESS(status); fmtr->format(dl, formattedResult, NULL, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("1,234,566,666,666,666,666,666,666,666,666,666,666,621,000", formattedResult); status = U_ZERO_ERROR; num.set("666.666"); dl.setToDecNumber(num, status); FieldPosition pos(NumberFormat::FRACTION_FIELD); ASSERT_SUCCESS(status); formattedResult.remove(); fmtr->format(dl, formattedResult, pos, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("666.666", formattedResult); ASSERT_EQUALS(4, pos.getBeginIndex()); ASSERT_EQUALS(7, pos.getEndIndex()); delete fmtr; } } { // Check a parse with a formatter with a multiplier. UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_PERCENT, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString input = "1.84%"; Formattable result; fmtr->parse(input, result, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("0.0184", result.getDecimalNumber(status).data()); //std::cout << result.getDecimalNumber(status).data(); delete fmtr; } } #if U_PLATFORM != U_PF_CYGWIN || defined(CYGWINMSVC) /* * This test fails on Cygwin (1.7.16) using GCC because of a rounding issue with strtod(). * See #9463 */ { // Check that a parse returns a decimal number with full accuracy UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString input = "1.002200044400088880000070000"; Formattable result; fmtr->parse(input, result, status); ASSERT_SUCCESS(status); ASSERT_EQUALS(0, strcmp("1.00220004440008888000007", result.getDecimalNumber(status).data())); ASSERT_EQUALS(1.00220004440008888, result.getDouble()); //std::cout << result.getDecimalNumber(status).data(); delete fmtr; } } #endif } void NumberFormatTest::TestCurrencyFractionDigits() { UErrorCode status = U_ZERO_ERROR; UnicodeString text1, text2; double value = 99.12345; // Create currenct instance NumberFormat* fmt = NumberFormat::createCurrencyInstance("ja_JP", status); if (U_FAILURE(status) || fmt == NULL) { dataerrln("Unable to create NumberFormat"); } else { fmt->format(value, text1); // Reset the same currency and format the test value again fmt->setCurrency(fmt->getCurrency(), status); ASSERT_SUCCESS(status); fmt->format(value, text2); if (text1 != text2) { errln((UnicodeString)"NumberFormat::format() should return the same result - text1=" + text1 + " text2=" + text2); } } delete fmt; } void NumberFormatTest::TestExponentParse() { UErrorCode status = U_ZERO_ERROR; Formattable result; ParsePosition parsePos(0); // set the exponent symbol status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getDefault(), status); if(U_FAILURE(status)) { dataerrln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (Default)"); return; } // create format instance status = U_ZERO_ERROR; DecimalFormat fmt(u"#####", symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); } // parse the text fmt.parse("5.06e-27", result, parsePos); if(result.getType() != Formattable::kDouble && result.getDouble() != 5.06E-27 && parsePos.getIndex() != 8 ) { errln("ERROR: parse failed - expected 5.06E-27, 8 - returned %d, %i", result.getDouble(), parsePos.getIndex()); } } void NumberFormatTest::TestExplicitParents() { /* Test that number formats are properly inherited from es_419 */ /* These could be subject to change if the CLDR data changes */ static const char* parentLocaleTests[][2]= { /* locale ID */ /* expected */ {"es_CO", "1.250,75" }, {"es_ES", "1.250,75" }, {"es_GQ", "1.250,75" }, {"es_MX", "1,250.75" }, {"es_US", "1,250.75" }, {"es_VE", "1.250,75" }, }; UnicodeString s; for(int i=0; i < UPRV_LENGTHOF(parentLocaleTests); i++){ UErrorCode status = U_ZERO_ERROR; const char *localeID = parentLocaleTests[i][0]; UnicodeString expected(parentLocaleTests[i][1], -1, US_INV); expected = expected.unescape(); char loc[256]={0}; uloc_canonicalize(localeID, loc, 256, &status); NumberFormat *fmt= NumberFormat::createInstance(Locale(loc), status); if(U_FAILURE(status)){ dataerrln("Could not create number formatter for locale %s - %s",localeID, u_errorName(status)); continue; } s.remove(); fmt->format(1250.75, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln((UnicodeString)"FAIL: Status " + (int32_t)status); } delete fmt; } } /** * Test available numbering systems API. */ void NumberFormatTest::TestAvailableNumberingSystems() { UErrorCode status = U_ZERO_ERROR; StringEnumeration *availableNumberingSystems = NumberingSystem::getAvailableNames(status); CHECK_DATA(status, "NumberingSystem::getAvailableNames()") int32_t nsCount = availableNumberingSystems->count(status); if ( nsCount < 74 ) { errln("FAIL: Didn't get as many numbering systems as we had hoped for. Need at least 74, got %d",nsCount); } /* A relatively simple test of the API. We call getAvailableNames() and cycle through */ /* each name returned, attempting to create a numbering system based on that name and */ /* verifying that the name returned from the resulting numbering system is the same */ /* one that we initially thought. */ int32_t len; for ( int32_t i = 0 ; i < nsCount ; i++ ) { const char *nsname = availableNumberingSystems->next(&len,status); NumberingSystem* ns = NumberingSystem::createInstanceByName(nsname,status); logln("OK for ns = %s",nsname); if ( uprv_strcmp(nsname,ns->getName()) ) { errln("FAIL: Numbering system name didn't match for name = %s\n",nsname); } delete ns; } delete availableNumberingSystems; } void NumberFormatTest::Test9087(void) { U_STRING_DECL(pattern,"#",1); U_STRING_INIT(pattern,"#",1); U_STRING_DECL(infstr,"INF",3); U_STRING_INIT(infstr,"INF",3); U_STRING_DECL(nanstr,"NAN",3); U_STRING_INIT(nanstr,"NAN",3); UChar outputbuf[50] = {0}; UErrorCode status = U_ZERO_ERROR; UNumberFormat* fmt = unum_open(UNUM_PATTERN_DECIMAL,pattern,1,NULL,NULL,&status); if ( U_FAILURE(status) ) { dataerrln("FAIL: error in unum_open() - %s", u_errorName(status)); return; } unum_setSymbol(fmt,UNUM_INFINITY_SYMBOL,infstr,3,&status); unum_setSymbol(fmt,UNUM_NAN_SYMBOL,nanstr,3,&status); if ( U_FAILURE(status) ) { errln("FAIL: error setting symbols"); } double inf = uprv_getInfinity(); unum_setAttribute(fmt,UNUM_ROUNDING_MODE,UNUM_ROUND_HALFEVEN); unum_setDoubleAttribute(fmt,UNUM_ROUNDING_INCREMENT,0); UFieldPosition position = { 0, 0, 0}; unum_formatDouble(fmt,inf,outputbuf,50,&position,&status); if ( u_strcmp(infstr, outputbuf)) { errln((UnicodeString)"FAIL: unexpected result for infinity - expected " + infstr + " got " + outputbuf); } unum_close(fmt); } void NumberFormatTest::TestFormatFastpaths() { // get some additional case { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = 1; UnicodeString expect = "0001"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000000000000000000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MIN; // -9223372036854775808L; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "-9223372036854775808"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on -9223372036854775808", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on -9223372036854775808"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000000000000000000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MAX; // -9223372036854775808L; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "9223372036854775807"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on U_INT64_MAX", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on U_INT64_MAX"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString("0000000000000000000",""),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = 0; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "0000000000000000000"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on 0", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on 0"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString("0000000000000000000",""),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MIN + 1; UnicodeString expect = "-9223372036854775807"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on -9223372036854775807", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on -9223372036854775807"); } } } } void NumberFormatTest::TestFormattableSize(void) { if(sizeof(Formattable) > 112) { errln("Error: sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } else if(sizeof(Formattable) < 112) { logln("Warning: sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } else { logln("sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } } UBool NumberFormatTest::testFormattableAsUFormattable(const char *file, int line, Formattable &f) { UnicodeString fileLine = UnicodeString(file)+UnicodeString(":")+line+UnicodeString(": "); UFormattable *u = f.toUFormattable(); logln(); if (u == NULL) { errln("%s:%d: Error: f.toUFormattable() retuned NULL."); return FALSE; } logln("%s:%d: comparing Formattable with UFormattable", file, line); logln(fileLine + toString(f)); UErrorCode status = U_ZERO_ERROR; UErrorCode valueStatus = U_ZERO_ERROR; UFormattableType expectUType = UFMT_COUNT; // invalid UBool triedExact = FALSE; // did we attempt an exact comparison? UBool exactMatch = FALSE; // was the exact comparison true? switch( f.getType() ) { case Formattable::kDate: expectUType = UFMT_DATE; exactMatch = (f.getDate()==ufmt_getDate(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kDouble: expectUType = UFMT_DOUBLE; exactMatch = (f.getDouble()==ufmt_getDouble(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kLong: expectUType = UFMT_LONG; exactMatch = (f.getLong()==ufmt_getLong(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kString: expectUType = UFMT_STRING; { UnicodeString str; f.getString(str); int32_t len; const UChar* uch = ufmt_getUChars(u, &len, &valueStatus); if(U_SUCCESS(valueStatus)) { UnicodeString str2(uch, len); assertTrue("UChar* NULL-terminated", uch[len]==0); exactMatch = (str == str2); } triedExact = TRUE; } break; case Formattable::kArray: expectUType = UFMT_ARRAY; triedExact = TRUE; { int32_t count = ufmt_getArrayLength(u, &valueStatus); int32_t count2; const Formattable *array2 = f.getArray(count2); exactMatch = assertEquals(fileLine + " array count", count, count2); if(exactMatch) { for(int i=0;U_SUCCESS(valueStatus) && i<count;i++) { UFormattable *uu = ufmt_getArrayItemByIndex(u, i, &valueStatus); if(*Formattable::fromUFormattable(uu) != (array2[i])) { errln("%s:%d: operator== did not match at index[%d] - %p vs %p", file, line, i, (const void*)Formattable::fromUFormattable(uu), (const void*)&(array2[i])); exactMatch = FALSE; } else { if(!testFormattableAsUFormattable("(sub item)",i,*Formattable::fromUFormattable(uu))) { exactMatch = FALSE; } } } } } break; case Formattable::kInt64: expectUType = UFMT_INT64; exactMatch = (f.getInt64()==ufmt_getInt64(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kObject: expectUType = UFMT_OBJECT; exactMatch = (f.getObject()==ufmt_getObject(u, &valueStatus)); triedExact = TRUE; break; } UFormattableType uType = ufmt_getType(u, &status); if(U_FAILURE(status)) { errln("%s:%d: Error calling ufmt_getType - %s", file, line, u_errorName(status)); return FALSE; } if(uType != expectUType) { errln("%s:%d: got type (%d) expected (%d) from ufmt_getType", file, line, (int) uType, (int) expectUType); } if(triedExact) { if(U_FAILURE(valueStatus)) { errln("%s:%d: got err %s trying to ufmt_get...() for exact match check", file, line, u_errorName(valueStatus)); } else if(!exactMatch) { errln("%s:%d: failed exact match for the Formattable type", file, line); } else { logln("%s:%d: exact match OK", file, line); } } else { logln("%s:%d: note, did not attempt exact match for this formattable type", file, line); } if( assertEquals(fileLine + " isNumeric()", f.isNumeric(), ufmt_isNumeric(u)) && f.isNumeric()) { UErrorCode convStatus = U_ZERO_ERROR; if(uType != UFMT_INT64) { // may fail to compare assertTrue(fileLine + " as doubles ==", f.getDouble(convStatus)==ufmt_getDouble(u, &convStatus)); } if( assertSuccess(fileLine + " (numeric conversion status)", convStatus) ) { StringPiece fDecNum = f.getDecimalNumber(convStatus); #if 1 int32_t len; const char *decNumChars = ufmt_getDecNumChars(u, &len, &convStatus); #else // copy version char decNumChars[200]; int32_t len = ufmt_getDecNumChars(u, decNumChars, 200, &convStatus); #endif if( assertSuccess(fileLine + " (decNumbers conversion)", convStatus) ) { logln(fileLine + decNumChars); assertEquals(fileLine + " decNumChars length==", len, fDecNum.length()); assertEquals(fileLine + " decNumChars digits", decNumChars, fDecNum.data()); } UErrorCode int64ConversionF = U_ZERO_ERROR; int64_t l = f.getInt64(int64ConversionF); UErrorCode int64ConversionU = U_ZERO_ERROR; int64_t r = ufmt_getInt64(u, &int64ConversionU); if( (l==r) && ( uType != UFMT_INT64 ) // int64 better not overflow && (U_INVALID_FORMAT_ERROR==int64ConversionU) && (U_INVALID_FORMAT_ERROR==int64ConversionF) ) { logln("%s:%d: OK: 64 bit overflow", file, line); } else { assertEquals(fileLine + " as int64 ==", l, r); assertSuccess(fileLine + " Formattable.getnt64()", int64ConversionF); assertSuccess(fileLine + " ufmt_getInt64()", int64ConversionU); } } } return exactMatch || !triedExact; } void NumberFormatTest::TestUFormattable(void) { { // test that a default formattable is equal to Formattable() UErrorCode status = U_ZERO_ERROR; LocalUFormattablePointer defaultUFormattable(ufmt_open(&status)); assertSuccess("calling umt_open", status); Formattable defaultFormattable; assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); assertTrue((UnicodeString)"comparing Formattable() round tripped through UFormattable", (defaultFormattable == *(Formattable::fromUFormattable(defaultFormattable.toUFormattable())))); assertTrue((UnicodeString)"comparing &Formattable() round tripped through UFormattable", ((&defaultFormattable) == Formattable::fromUFormattable(defaultFormattable.toUFormattable()))); assertFalse((UnicodeString)"comparing &Formattable() with ufmt_open()", ((&defaultFormattable) == Formattable::fromUFormattable(defaultUFormattable.getAlias()))); testFormattableAsUFormattable(__FILE__, __LINE__, defaultFormattable); } // test some random Formattables { Formattable f(ucal_getNow(), Formattable::kIsDate); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((double)1.61803398874989484820); // golden ratio testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((int64_t)80994231587905127LL); // weight of the moon, in kilotons http://solarsystem.nasa.gov/planets/profile.cfm?Display=Facts&Object=Moon testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((int32_t)4); // random number, source: http://www.xkcd.com/221/ testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f("Hello world."); // should be invariant? testFormattableAsUFormattable(__FILE__, __LINE__, f); } { UErrorCode status2 = U_ZERO_ERROR; Formattable f(StringPiece("73476730924573500000000.0"), status2); // weight of the moon, kg assertSuccess("Constructing a StringPiece", status2); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { UErrorCode status2 = U_ZERO_ERROR; UObject *obj = new Locale(); Formattable f(obj); assertSuccess("Constructing a Formattable from a default constructed Locale()", status2); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { const Formattable array[] = { Formattable(ucal_getNow(), Formattable::kIsDate), Formattable((int32_t)4), Formattable((double)1.234), }; Formattable fa(array, 3); testFormattableAsUFormattable(__FILE__, __LINE__, fa); } } void NumberFormatTest::TestSignificantDigits(void) { double input[] = { 0, 0, 0.1, -0.1, 123, -123, 12345, -12345, 123.45, -123.45, 123.44501, -123.44501, 0.001234, -0.001234, 0.00000000123, -0.00000000123, 0.0000000000000000000123, -0.0000000000000000000123, 1.2, -1.2, 0.0000000012344501, -0.0000000012344501, 123445.01, -123445.01, 12344501000000000000000000000000000.0, -12344501000000000000000000000000000.0, }; const char* expected[] = { "0.00", "0.00", "0.100", "-0.100", "123", "-123", "12345", "-12345", "123.45", "-123.45", "123.45", "-123.45", "0.001234", "-0.001234", "0.00000000123", "-0.00000000123", "0.0000000000000000000123", "-0.0000000000000000000123", "1.20", "-1.20", "0.0000000012345", "-0.0000000012345", "123450", "-123450", "12345000000000000000000000000000000", "-12345000000000000000000000000000000", }; UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); CHECK_DATA(status,"NumberFormat::createInstance") numberFormat->setSignificantDigitsUsed(TRUE); numberFormat->setMinimumSignificantDigits(3); numberFormat->setMaximumSignificantDigits(5); numberFormat->setGroupingUsed(false); UnicodeString result; UnicodeString expectedResult; for (unsigned int i = 0; i < UPRV_LENGTHOF(input); ++i) { numberFormat->format(input[i], result); UnicodeString expectedResult(expected[i]); if (result != expectedResult) { errln((UnicodeString)"Expected: '" + expectedResult + "' got '" + result); } result.remove(); } // Test for ICU-20063 { DecimalFormat df({"en-us", status}, status); df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.87654"); df.setMaximumSignificantDigits(3); expect(df, 9.87654321, u"9.88"); // setSignificantDigitsUsed with maxSig only df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.88"); df.setMinimumSignificantDigits(2); expect(df, 9, u"9.0"); // setSignificantDigitsUsed with both minSig and maxSig df.setSignificantDigitsUsed(TRUE); expect(df, 9, u"9.0"); // setSignificantDigitsUsed to false: should revert to fraction rounding df.setSignificantDigitsUsed(FALSE); expect(df, 9.87654321, u"9.876543"); expect(df, 9, u"9"); df.setSignificantDigitsUsed(TRUE); df.setMinimumSignificantDigits(2); expect(df, 9.87654321, u"9.87654"); expect(df, 9, u"9.0"); // setSignificantDigitsUsed with minSig only df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.87654"); expect(df, 9, u"9.0"); } } void NumberFormatTest::TestShowZero() { UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); CHECK_DATA(status, "NumberFormat::createInstance") numberFormat->setSignificantDigitsUsed(TRUE); numberFormat->setMaximumSignificantDigits(3); UnicodeString result; numberFormat->format(0.0, result); if (result != "0") { errln((UnicodeString)"Expected: 0, got " + result); } } void NumberFormatTest::TestBug9936() { UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); if (U_FAILURE(status)) { dataerrln("File %s, Line %d: status = %s.\n", __FILE__, __LINE__, u_errorName(status)); return; } if (numberFormat->areSignificantDigitsUsed() == TRUE) { errln("File %s, Line %d: areSignificantDigitsUsed() was TRUE, expected FALSE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(TRUE); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(FALSE); if (numberFormat->areSignificantDigitsUsed() == TRUE) { errln("File %s, Line %d: areSignificantDigitsUsed() was TRUE, expected FALSE.\n", __FILE__, __LINE__); } numberFormat->setMinimumSignificantDigits(3); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(FALSE); numberFormat->setMaximumSignificantDigits(6); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } } void NumberFormatTest::TestParseNegativeWithFaLocale() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *test = (DecimalFormat *) NumberFormat::createInstance("fa", status); CHECK_DATA(status, "NumberFormat::createInstance") test->setLenient(TRUE); Formattable af; ParsePosition ppos; UnicodeString value("\\u200e-0,5"); value = value.unescape(); test->parse(value, af, ppos); if (ppos.getIndex() == 0) { errln("Expected -0,5 to parse for Farsi."); } delete test; } void NumberFormatTest::TestParseNegativeWithAlternateMinusSign() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *test = (DecimalFormat *) NumberFormat::createInstance("en", status); CHECK_DATA(status, "NumberFormat::createInstance") test->setLenient(TRUE); Formattable af; ParsePosition ppos; UnicodeString value("\\u208B0.5"); value = value.unescape(); test->parse(value, af, ppos); if (ppos.getIndex() == 0) { errln(UnicodeString("Expected ") + value + UnicodeString(" to parse.")); } delete test; } void NumberFormatTest::TestCustomCurrencySignAndSeparator() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols custom(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); custom.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "*"); custom.setSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol, "^"); custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, ":"); UnicodeString pat(" #,##0.00"); pat.insert(0, (UChar)0x00A4); DecimalFormat fmt(pat, custom, status); CHECK(status, "DecimalFormat constructor"); UnicodeString numstr("* 1^234:56"); expect2(fmt, (Formattable)((double)1234.56), numstr); } typedef struct { const char * locale; UBool lenient; UnicodeString numString; double value; } SignsAndMarksItem; void NumberFormatTest::TestParseSignsAndMarks() { const SignsAndMarksItem items[] = { // locale lenient numString value { "en", FALSE, CharsToUnicodeString("12"), 12 }, { "en", TRUE, CharsToUnicodeString("12"), 12 }, { "en", FALSE, CharsToUnicodeString("-23"), -23 }, { "en", TRUE, CharsToUnicodeString("-23"), -23 }, { "en", TRUE, CharsToUnicodeString("- 23"), -23 }, { "en", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "en", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "en", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("- \\u0664\\u0665"), -45 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u200F- \\u0664\\u0665"), -45 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("- \\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u200E-\\u200E \\u06F6\\u06F7"), -67 }, { "he", FALSE, CharsToUnicodeString("12"), 12 }, { "he", TRUE, CharsToUnicodeString("12"), 12 }, { "he", FALSE, CharsToUnicodeString("-23"), -23 }, { "he", TRUE, CharsToUnicodeString("-23"), -23 }, { "he", TRUE, CharsToUnicodeString("- 23"), -23 }, { "he", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "he", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "he", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "ar", FALSE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "ar", TRUE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "ar", FALSE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("- \\u0664\\u0665"), -45 }, { "ar", FALSE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("\\u200F- \\u0664\\u0665"), -45 }, { "ar_MA", FALSE, CharsToUnicodeString("12"), 12 }, { "ar_MA", TRUE, CharsToUnicodeString("12"), 12 }, { "ar_MA", FALSE, CharsToUnicodeString("-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("- 23"), -23 }, { "ar_MA", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "fa", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "fa", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "fa", FALSE, CharsToUnicodeString("\\u2212\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u2212\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u2212 \\u06F6\\u06F7"), -67 }, { "fa", FALSE, CharsToUnicodeString("\\u200E\\u2212\\u200E\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u200E\\u2212\\u200E\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u200E\\u2212\\u200E \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "ps", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "ps", FALSE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("- \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("\\u200E-\\u200E \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u200E \\u06F6\\u06F7"), -67 }, // terminator { NULL, 0, UnicodeString(""), 0 }, }; const SignsAndMarksItem * itemPtr; for (itemPtr = items; itemPtr->locale != NULL; itemPtr++ ) { UErrorCode status = U_ZERO_ERROR; NumberFormat *numfmt = NumberFormat::createInstance(Locale(itemPtr->locale), status); if (U_SUCCESS(status)) { numfmt->setLenient(itemPtr->lenient); Formattable fmtobj; ParsePosition ppos; numfmt->parse(itemPtr->numString, fmtobj, ppos); if (ppos.getIndex() == itemPtr->numString.length()) { double parsedValue = fmtobj.getDouble(status); if (U_FAILURE(status) || parsedValue != itemPtr->value) { errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives value " + parsedValue); } } else { errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives position " + ppos.getIndex()); } } else { dataerrln("FAIL: NumberFormat::createInstance for locale % gives error %s", itemPtr->locale, u_errorName(status)); } delete numfmt; } } typedef struct { DecimalFormat::ERoundingMode mode; double value; UnicodeString expected; } Test10419Data; // Tests that rounding works right when fractional digits is set to 0. void NumberFormatTest::Test10419RoundingWith0FractionDigits() { const Test10419Data items[] = { { DecimalFormat::kRoundCeiling, 1.488, "2"}, { DecimalFormat::kRoundDown, 1.588, "1"}, { DecimalFormat::kRoundFloor, 1.888, "1"}, { DecimalFormat::kRoundHalfDown, 1.5, "1"}, { DecimalFormat::kRoundHalfEven, 2.5, "2"}, { DecimalFormat::kRoundHalfUp, 2.5, "3"}, { DecimalFormat::kRoundUp, 1.5, "2"}, }; UErrorCode status = U_ZERO_ERROR; LocalPointer<DecimalFormat> decfmt((DecimalFormat *) NumberFormat::createInstance(Locale("en_US"), status)); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } for (int32_t i = 0; i < UPRV_LENGTHOF(items); ++i) { decfmt->setRoundingMode(items[i].mode); decfmt->setMaximumFractionDigits(0); UnicodeString actual; if (items[i].expected != decfmt->format(items[i].value, actual)) { errln("Expected " + items[i].expected + ", got " + actual); } } } void NumberFormatTest::Test10468ApplyPattern() { // Padding char of fmt is now 'a' UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("'I''ll'*a###.##", status); if (U_FAILURE(status)) { errcheckln(status, "DecimalFormat constructor failed - %s", u_errorName(status)); return; } assertEquals("Padding character should be 'a'.", u"a", fmt.getPadCharacterString()); // Padding char of fmt ought to be '*' since that is the default and no // explicit padding char is specified in the new pattern. fmt.applyPattern("AA#,##0.00ZZ", status); // Oops this still prints 'a' even though we changed the pattern. assertEquals("applyPattern did not clear padding character.", u" ", fmt.getPadCharacterString()); } void NumberFormatTest::TestRoundingScientific10542() { UErrorCode status = U_ZERO_ERROR; DecimalFormat format("0.00E0", status); if (U_FAILURE(status)) { errcheckln(status, "DecimalFormat constructor failed - %s", u_errorName(status)); return; } DecimalFormat::ERoundingMode roundingModes[] = { DecimalFormat::kRoundCeiling, DecimalFormat::kRoundDown, DecimalFormat::kRoundFloor, DecimalFormat::kRoundHalfDown, DecimalFormat::kRoundHalfEven, DecimalFormat::kRoundHalfUp, DecimalFormat::kRoundUp}; const char *descriptions[] = { "Round Ceiling", "Round Down", "Round Floor", "Round half down", "Round half even", "Round half up", "Round up"}; { double values[] = {-0.003006, -0.003005, -0.003004, 0.003014, 0.003015, 0.003016}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-3.00E-3", "-3.00E-3", "-3.00E-3", "3.02E-3", "3.02E-3", "3.02E-3", "-3.00E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.01E-3", "-3.01E-3", "-3.01E-3", "-3.01E-3", "3.01E-3", "3.01E-3", "3.01E-3", "-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.02E-3", "-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3", "-3.01E-3", "-3.01E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3", "-3.01E-3", "-3.01E-3", "-3.01E-3", "3.02E-3", "3.02E-3", "3.02E-3"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-3006.0, -3005, -3004, 3014, 3015, 3016}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-3.00E3", "-3.00E3", "-3.00E3", "3.02E3", "3.02E3", "3.02E3", "-3.00E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.01E3", "-3.01E3", "-3.01E3", "-3.01E3", "3.01E3", "3.01E3", "3.01E3", "-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.02E3", "-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3", "-3.01E3", "-3.01E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3", "-3.01E3", "-3.01E3", "-3.01E3", "3.02E3", "3.02E3", "3.02E3"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } /* Commented out for now until we decide how rounding to zero should work, +0 vs. -0 { double values[] = {0.0, -0.0}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } */ { double values[] = {1e25, 1e25 + 1e15, 1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "1.00E25", "1.01E25", "1.00E25", "1.00E25", "1.00E25", "9.99E24", "1.00E25", "1.00E25", "9.99E24", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.01E25", "1.00E25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-1e25, -1e25 + 1e15, -1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-1.00E25", "-9.99E24", "-1.00E25", "-1.00E25", "-9.99E24", "-1.00E25", "-1.00E25", "-1.00E25", "-1.01E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.01E25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {1e-25, 1e-25 + 1e-35, 1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "1.00E-25", "1.01E-25", "1.00E-25", "1.00E-25", "1.00E-25", "9.99E-26", "1.00E-25", "1.00E-25", "9.99E-26", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.01E-25", "1.00E-25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-1e-25, -1e-25 + 1e-35, -1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-1.00E-25", "-9.99E-26", "-1.00E-25", "-1.00E-25", "-9.99E-26", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.01E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.01E-25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } } void NumberFormatTest::TestZeroScientific10547() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("0.00E0", status); if (!assertSuccess("Format creation", status)) { return; } UnicodeString out; fmt.format(-0.0, out); assertEquals("format", "-0.00E0", out, true); } void NumberFormatTest::verifyRounding( DecimalFormat& format, const double *values, const char * const *expected, const DecimalFormat::ERoundingMode *roundingModes, const char * const *descriptions, int32_t valueSize, int32_t roundingModeSize) { for (int32_t i = 0; i < roundingModeSize; ++i) { format.setRoundingMode(roundingModes[i]); for (int32_t j = 0; j < valueSize; j++) { UnicodeString currentExpected(expected[i * valueSize + j]); currentExpected = currentExpected.unescape(); UnicodeString actual; format.format(values[j], actual); if (currentExpected != actual) { dataerrln("For %s value %f, expected '%s', got '%s'", descriptions[i], values[j], CStr(currentExpected)(), CStr(actual)()); } } } } void NumberFormatTest::TestAccountingCurrency() { UErrorCode status = U_ZERO_ERROR; UNumberFormatStyle style = UNUM_CURRENCY_ACCOUNTING; expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)1234.5, "$1,234.50", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)-1234.5, "($1,234.50)", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)0, "$0.00", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)-0.2, "($0.20)", TRUE, status); expect(NumberFormat::createInstance("ja_JP", style, status), (Formattable)(double)10000, UnicodeString("\\uFFE510,000").unescape(), TRUE, status); expect(NumberFormat::createInstance("ja_JP", style, status), (Formattable)(double)-1000.5, UnicodeString("(\\uFFE51,000)").unescape(), FALSE, status); expect(NumberFormat::createInstance("de_DE", style, status), (Formattable)(double)-23456.7, UnicodeString("-23.456,70\\u00A0\\u20AC").unescape(), TRUE, status); } // for #5186 void NumberFormatTest::TestEquality() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale("root"), status); if (U_FAILURE(status)) { dataerrln("Fail: can't create DecimalFormatSymbols for root"); return; } UnicodeString pattern("#,##0.###"); DecimalFormat fmtBase(pattern, symbols, status); if (U_FAILURE(status)) { dataerrln("Fail: can't create DecimalFormat using root symbols"); return; } DecimalFormat* fmtClone = (DecimalFormat*)fmtBase.clone(); fmtClone->setFormatWidth(fmtBase.getFormatWidth() + 32); if (*fmtClone == fmtBase) { errln("Error: DecimalFormat == does not distinguish objects that differ only in FormatWidth"); } delete fmtClone; } void NumberFormatTest::TestCurrencyUsage() { double agent = 123.567; UErrorCode status; DecimalFormat *fmt; // compare the Currency and Currency Cash Digits // Note that as of CLDR 26: // * TWD and PKR switched from 0 decimals to 2; ISK still has 0, so change test to that // * CAD rounds to .05 in cash mode only // 1st time for getter/setter, 2nd time for factory method Locale enUS_ISK("en_US@currency=ISK"); for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_ISK, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=ISK/CURRENCY", status, TRUE) == FALSE) { continue; } UnicodeString original; fmt->format(agent,original); assertEquals("Test Currency Usage 1", u"ISK\u00A0124", original); // test the getter here UCurrencyUsage curUsage = fmt->getCurrencyUsage(); assertEquals("Test usage getter - standard", (int32_t)curUsage, (int32_t)UCURR_USAGE_STANDARD); fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_ISK, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=ISK/CASH", status, TRUE) == FALSE) { continue; } } // must be usage = cash UCurrencyUsage curUsage = fmt->getCurrencyUsage(); assertEquals("Test usage getter - cash", (int32_t)curUsage, (int32_t)UCURR_USAGE_CASH); UnicodeString cash_currency; fmt->format(agent,cash_currency); assertEquals("Test Currency Usage 2", u"ISK\u00A0124", cash_currency); delete fmt; } // compare the Currency and Currency Cash Rounding // 1st time for getter/setter, 2nd time for factory method Locale enUS_CAD("en_US@currency=CAD"); for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CURRENCY", status, TRUE) == FALSE) { continue; } UnicodeString original_rounding; fmt->format(agent, original_rounding); assertEquals("Test Currency Usage 3", u"CA$123.57", original_rounding); fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CASH", status, TRUE) == FALSE) { continue; } } UnicodeString cash_rounding_currency; fmt->format(agent, cash_rounding_currency); assertEquals("Test Currency Usage 4", u"CA$123.55", cash_rounding_currency); delete fmt; } // Test the currency change // 1st time for getter/setter, 2nd time for factory method const UChar CUR_PKR[] = {0x50, 0x4B, 0x52, 0}; for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CURRENCY", status, TRUE) == FALSE) { continue; } fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CASH", status, TRUE) == FALSE) { continue; } } UnicodeString cur_original; fmt->setCurrencyUsage(UCURR_USAGE_STANDARD, &status); fmt->format(agent, cur_original); assertEquals("Test Currency Usage 5", u"CA$123.57", cur_original); fmt->setCurrency(CUR_PKR, status); assertSuccess("Set currency to PKR", status); UnicodeString PKR_changed; fmt->format(agent, PKR_changed); assertEquals("Test Currency Usage 6", u"PKR\u00A0123.57", PKR_changed); delete fmt; } } // Check the constant MAX_INT64_IN_DOUBLE. // The value should convert to a double with no loss of precision. // A failure may indicate a platform with a different double format, requiring // a revision to the constant. // // Note that this is actually hard to test, because the language standard gives // compilers considerable flexibility to do unexpected things with rounding and // with overflow in simple int to/from float conversions. Some compilers will completely optimize // away a simple round-trip conversion from int64_t -> double -> int64_t. void NumberFormatTest::TestDoubleLimit11439() { char buf[50]; for (int64_t num = MAX_INT64_IN_DOUBLE-10; num<=MAX_INT64_IN_DOUBLE; num++) { sprintf(buf, "%lld", (long long)num); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast<int64_t>(fNum); if (num != rtNum) { errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); return; } } for (int64_t num = -MAX_INT64_IN_DOUBLE+10; num>=-MAX_INT64_IN_DOUBLE; num--) { sprintf(buf, "%lld", (long long)num); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast<int64_t>(fNum); if (num != rtNum) { errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); return; } } } void NumberFormatTest::TestGetAffixes() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en_US", status); UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00 %\\u00a4\\u00a4"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } UnicodeString affixStr; assertEquals("", "US dollars ", fmt.getPositivePrefix(affixStr)); assertEquals("", " %USD", fmt.getPositiveSuffix(affixStr)); assertEquals("", "-US dollars ", fmt.getNegativePrefix(affixStr)); assertEquals("", " %USD", fmt.getNegativeSuffix(affixStr)); // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix(someAffix)); assertTrue("", fmt != fmtCopy); } fmt.setPositivePrefix("Don't"); fmt.setPositiveSuffix("do"); UnicodeString someAffix("be''eet\\u00a4\\u00a4\\u00a4 it."); someAffix = someAffix.unescape(); fmt.setNegativePrefix(someAffix); fmt.setNegativeSuffix("%"); assertEquals("", "Don't", fmt.getPositivePrefix(affixStr)); assertEquals("", "do", fmt.getPositiveSuffix(affixStr)); assertEquals("", someAffix, fmt.getNegativePrefix(affixStr)); assertEquals("", "%", fmt.getNegativeSuffix(affixStr)); } void NumberFormatTest::TestToPatternScientific11648() { UErrorCode status = U_ZERO_ERROR; Locale en("en"); DecimalFormatSymbols sym(en, status); DecimalFormat fmt("0.00", sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } fmt.setScientificNotation(TRUE); UnicodeString pattern; assertEquals("", "0.00E0", fmt.toPattern(pattern)); DecimalFormat fmt2(pattern, sym, status); assertSuccess("", status); } void NumberFormatTest::TestBenchmark() { /* UErrorCode status = U_ZERO_ERROR; Locale en("en"); DecimalFormatSymbols sym(en, status); DecimalFormat fmt("0.0000000", new DecimalFormatSymbols(sym), status); // DecimalFormat fmt("0.00000E0", new DecimalFormatSymbols(sym), status); // DecimalFormat fmt("0", new DecimalFormatSymbols(sym), status); FieldPosition fpos(FieldPosition::DONT_CARE); clock_t start = clock(); for (int32_t i = 0; i < 1000000; ++i) { UnicodeString append; fmt.format(3.0, append, fpos, status); // fmt.format(4.6692016, append, fpos, status); // fmt.format(1234567.8901, append, fpos, status); // fmt.format(2.99792458E8, append, fpos, status); // fmt.format(31, append); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); UErrorCode status = U_ZERO_ERROR; MessageFormat fmt("{0, plural, one {I have # friend.} other {I have # friends.}}", status); FieldPosition fpos(FieldPosition::DONT_CARE); Formattable one(1.0); Formattable three(3.0); clock_t start = clock(); for (int32_t i = 0; i < 500000; ++i) { UnicodeString append; fmt.format(&one, 1, append, fpos, status); UnicodeString append2; fmt.format(&three, 1, append2, fpos, status); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); UErrorCode status = U_ZERO_ERROR; Locale en("en"); Measure measureC(23, MeasureUnit::createCelsius(status), status); MeasureFormat fmt(en, UMEASFMT_WIDTH_WIDE, status); FieldPosition fpos(FieldPosition::DONT_CARE); clock_t start = clock(); for (int32_t i = 0; i < 1000000; ++i) { UnicodeString appendTo; fmt.formatMeasures( &measureC, 1, appendTo, fpos, status); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); */ } void NumberFormatTest::TestFractionalDigitsForCurrency() { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt(NumberFormat::createCurrencyInstance("en", status)); if (U_FAILURE(status)) { dataerrln("Error creating NumberFormat - %s", u_errorName(status)); return; } UChar JPY[] = {0x4A, 0x50, 0x59, 0x0}; fmt->setCurrency(JPY, status); if (!assertSuccess("", status)) { return; } assertEquals("", 0, fmt->getMaximumFractionDigits()); } void NumberFormatTest::TestFormatCurrencyPlural() { UErrorCode status = U_ZERO_ERROR; Locale locale = Locale::createCanonical("en_US"); NumberFormat *fmt = NumberFormat::createInstance(locale, UNUM_CURRENCY_PLURAL, status); if (U_FAILURE(status)) { dataerrln("Error creating NumberFormat - %s", u_errorName(status)); return; } UnicodeString formattedNum; fmt->format(11234.567, formattedNum, NULL, status); assertEquals("", "11,234.57 US dollars", formattedNum); delete fmt; } void NumberFormatTest::TestCtorApplyPatternDifference() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en_US", status); UnicodeString pattern("\\u00a40"); DecimalFormat fmt(pattern.unescape(), sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } UnicodeString result; assertEquals( "ctor favors precision of currency", "$5.00", fmt.format((double)5, result)); result.remove(); fmt.applyPattern(pattern.unescape(), status); assertEquals( "applyPattern favors precision of pattern", "$5", fmt.format((double)5, result)); } void NumberFormatTest::Test11868() { double posAmt = 34.567; double negAmt = -9876.543; Locale selectedLocale("en_US"); UErrorCode status = U_ZERO_ERROR; UnicodeString result; FieldPosition fpCurr(UNUM_CURRENCY_FIELD); LocalPointer<NumberFormat> fmt( NumberFormat::createInstance( selectedLocale, UNUM_CURRENCY_PLURAL, status)); if (!assertSuccess("Format creation", status)) { return; } fmt->format(posAmt, result, fpCurr, status); assertEquals("", "34.57 US dollars", result); assertEquals("begin index", 6, fpCurr.getBeginIndex()); assertEquals("end index", 16, fpCurr.getEndIndex()); // Test field position iterator { NumberFormatTest_Attributes attributes[] = { {UNUM_INTEGER_FIELD, 0, 2}, {UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3}, {UNUM_FRACTION_FIELD, 3, 5}, {UNUM_CURRENCY_FIELD, 6, 16}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt->format(posAmt, result, &iter, status); assertEquals("", "34.57 US dollars", result); verifyFieldPositionIterator(attributes, iter); } result.remove(); fmt->format(negAmt, result, fpCurr, status); assertEquals("", "-9,876.54 US dollars", result); assertEquals("begin index", 10, fpCurr.getBeginIndex()); assertEquals("end index", 20, fpCurr.getEndIndex()); // Test field position iterator { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_GROUPING_SEPARATOR_FIELD, 2, 3}, {UNUM_INTEGER_FIELD, 1, 6}, {UNUM_DECIMAL_SEPARATOR_FIELD, 6, 7}, {UNUM_FRACTION_FIELD, 7, 9}, {UNUM_CURRENCY_FIELD, 10, 20}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt->format(negAmt, result, &iter, status); assertEquals("", "-9,876.54 US dollars", result); verifyFieldPositionIterator(attributes, iter); } } void NumberFormatTest::Test10727_RoundingZero() { IcuTestErrorCode status(*this, "Test10727_RoundingZero"); DecimalQuantity dq; dq.setToDouble(-0.0); assertTrue("", dq.isNegative()); dq.roundToMagnitude(0, UNUM_ROUND_HALFEVEN, status); assertTrue("", dq.isNegative()); } void NumberFormatTest::Test11739_ParseLongCurrency() { IcuTestErrorCode status(*this, "Test11739_ParseLongCurrency"); LocalPointer<NumberFormat> nf(NumberFormat::createCurrencyInstance("sr_BA", status)); if (status.errDataIfFailureAndReset()) { return; } ((DecimalFormat*) nf.getAlias())->applyPattern(u"#,##0.0 ¤¤¤", status); ParsePosition ppos(0); LocalPointer<CurrencyAmount> result(nf->parseCurrency(u"1.500 амерички долар", ppos)); assertEquals("Should parse to 1500 USD", -1, ppos.getErrorIndex()); assertEquals("Should parse to 1500 USD", 1500LL, result->getNumber().getInt64(status)); assertEquals("Should parse to 1500 USD", u"USD", result->getISOCurrency()); } void NumberFormatTest::Test13035_MultiCodePointPaddingInPattern() { IcuTestErrorCode status(*this, "Test13035_MultiCodePointPaddingInPattern"); DecimalFormat df(u"a*'நி'###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } UnicodeString result; df.format(12, result.remove()); // TODO(13034): Re-enable this test when support is added in ICU4C. //assertEquals("Multi-codepoint padding should not be split", u"aநிநி12b", result); df = DecimalFormat(u"a*\U0001F601###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } result = df.format(12, result.remove()); assertEquals("Single-codepoint padding should not be split", u"a\U0001F601\U0001F60112b", result, true); df = DecimalFormat(u"a*''###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } result = df.format(12, result.remove()); assertEquals("Quote should be escapable in padding syntax", "a''12b", result, true); } void NumberFormatTest::Test13737_ParseScientificStrict() { IcuTestErrorCode status(*this, "Test13737_ParseScientificStrict"); LocalPointer<NumberFormat> df(NumberFormat::createScientificInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) {return;} df->setLenient(FALSE); // Parse Test expect(*df, u"1.2", 1.2); } void NumberFormatTest::Test11376_getAndSetPositivePrefix() { { const UChar USD[] = {0x55, 0x53, 0x44, 0x0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createCurrencyInstance("en", status)); if (!assertSuccess("", status)) { return; } DecimalFormat *dfmt = (DecimalFormat *) fmt.getAlias(); dfmt->setCurrency(USD); UnicodeString result; // This line should be a no-op. I am setting the positive prefix // to be the same thing it was before. dfmt->setPositivePrefix(dfmt->getPositivePrefix(result)); UnicodeString appendTo; assertEquals("", "$3.78", dfmt->format(3.78, appendTo, status)); assertSuccess("", status); } { const UChar USD[] = {0x55, 0x53, 0x44, 0x0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createInstance("en", UNUM_CURRENCY_PLURAL, status)); if (!assertSuccess("", status)) { return; } DecimalFormat *dfmt = (DecimalFormat *) fmt.getAlias(); UnicodeString result; assertEquals("", u" (unknown currency)", dfmt->getPositiveSuffix(result)); dfmt->setCurrency(USD); // getPositiveSuffix() always returns the suffix for the // "other" plural category assertEquals("", " US dollars", dfmt->getPositiveSuffix(result)); UnicodeString appendTo; assertEquals("", "3.78 US dollars", dfmt->format(3.78, appendTo, status)); assertEquals("", " US dollars", dfmt->getPositiveSuffix(result)); dfmt->setPositiveSuffix("booya"); appendTo.remove(); assertEquals("", "3.78booya", dfmt->format(3.78, appendTo, status)); assertEquals("", "booya", dfmt->getPositiveSuffix(result)); } } void NumberFormatTest::Test11475_signRecognition() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en", status); UnicodeString result; { DecimalFormat fmt("+0.00", sym, status); if (!assertSuccess("", status)) { return; } NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_INTEGER_FIELD, 1, 2}, {UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3}, {UNUM_FRACTION_FIELD, 3, 5}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(2.3, result, &iter, status); assertEquals("", "+2.30", result); verifyFieldPositionIterator(attributes, iter); } { DecimalFormat fmt("++0.00+;-(#)--", sym, status); if (!assertSuccess("", status)) { return; } { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 2}, {UNUM_INTEGER_FIELD, 2, 3}, {UNUM_DECIMAL_SEPARATOR_FIELD, 3, 4}, {UNUM_FRACTION_FIELD, 4, 6}, {UNUM_SIGN_FIELD, 6, 7}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(2.3, result, &iter, status); assertEquals("", "++2.30+", result); verifyFieldPositionIterator(attributes, iter); } { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_INTEGER_FIELD, 2, 3}, {UNUM_DECIMAL_SEPARATOR_FIELD, 3, 4}, {UNUM_FRACTION_FIELD, 4, 6}, {UNUM_SIGN_FIELD, 7, 9}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(-2.3, result, &iter, status); assertEquals("", "-(2.30)--", result); verifyFieldPositionIterator(attributes, iter); } } } void NumberFormatTest::Test11640_getAffixes() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols("en_US", status); if (!assertSuccess("", status)) { return; } UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00 %\\u00a4\\u00a4"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, symbols, status); if (!assertSuccess("", status)) { return; } UnicodeString affixStr; assertEquals("", "US dollars ", fmt.getPositivePrefix(affixStr)); assertEquals("", " %USD", fmt.getPositiveSuffix(affixStr)); assertEquals("", "-US dollars ", fmt.getNegativePrefix(affixStr)); assertEquals("", " %USD", fmt.getNegativeSuffix(affixStr)); } void NumberFormatTest::Test11649_toPatternWithMultiCurrency() { UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00"); pattern = pattern.unescape(); UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt(pattern, status); if (!assertSuccess("", status)) { return; } static UChar USD[] = {0x55, 0x53, 0x44, 0x0}; fmt.setCurrency(USD); UnicodeString appendTo; assertEquals("", "US dollars 12.34", fmt.format(12.34, appendTo)); UnicodeString topattern; fmt.toPattern(topattern); DecimalFormat fmt2(topattern, status); if (!assertSuccess("", status)) { return; } fmt2.setCurrency(USD); appendTo.remove(); assertEquals("", "US dollars 12.34", fmt2.format(12.34, appendTo)); } void NumberFormatTest::Test13327_numberingSystemBufferOverflow() { UErrorCode status = U_ZERO_ERROR; for (int runId = 0; runId < 2; runId++) { // Construct a locale string with a very long "numbers" value. // The first time, make the value length exactly equal to ULOC_KEYWORDS_CAPACITY. // The second time, make it exceed ULOC_KEYWORDS_CAPACITY. int extraLength = (runId == 0) ? 0 : 5; CharString localeId("en@numbers=", status); for (int i = 0; i < ULOC_KEYWORDS_CAPACITY + extraLength; i++) { localeId.append('x', status); } assertSuccess("Constructing locale string", status); Locale locale(localeId.data()); LocalPointer<NumberingSystem> ns(NumberingSystem::createInstance(locale, status)); assertFalse("Should not be null", ns.getAlias() == nullptr); assertSuccess("Should create with no error", status); } } void NumberFormatTest::Test13391_chakmaParsing() { UErrorCode status = U_ZERO_ERROR; LocalPointer<DecimalFormat> df(dynamic_cast<DecimalFormat*>( NumberFormat::createInstance(Locale("ccp"), status))); if (df == nullptr) { dataerrln("%s %d Chakma df is null", __FILE__, __LINE__); return; } const UChar* expected = u"\U00011137\U00011138,\U00011139\U0001113A\U0001113B"; UnicodeString actual; df->format(12345, actual, status); assertSuccess("Should not fail when formatting in ccp", status); assertEquals("Should produce expected output in ccp", expected, actual); Formattable result; df->parse(expected, result, status); assertSuccess("Should not fail when parsing in ccp", status); assertEquals("Should parse to 12345 in ccp", 12345, result); const UChar* expectedScientific = u"\U00011137.\U00011139E\U00011138"; UnicodeString actualScientific; df.adoptInstead(static_cast<DecimalFormat*>( NumberFormat::createScientificInstance(Locale("ccp"), status))); df->format(130, actualScientific, status); assertSuccess("Should not fail when formatting scientific in ccp", status); assertEquals("Should produce expected scientific output in ccp", expectedScientific, actualScientific); Formattable resultScientific; df->parse(expectedScientific, resultScientific, status); assertSuccess("Should not fail when parsing scientific in ccp", status); assertEquals("Should parse scientific to 130 in ccp", 130, resultScientific); } void NumberFormatTest::verifyFieldPositionIterator( NumberFormatTest_Attributes *expected, FieldPositionIterator &iter) { int32_t idx = 0; FieldPosition fp; while (iter.next(fp)) { if (expected[idx].spos == -1) { errln("Iterator should have ended. got %d", fp.getField()); return; } assertEquals("id", expected[idx].id, fp.getField()); assertEquals("start", expected[idx].spos, fp.getBeginIndex()); assertEquals("end", expected[idx].epos, fp.getEndIndex()); ++idx; } if (expected[idx].spos != -1) { errln("Premature end of iterator. expected %d", expected[idx].id); } } void NumberFormatTest::Test11735_ExceptionIssue() { IcuTestErrorCode status(*this, "Test11735_ExceptionIssue"); Locale enLocale("en"); DecimalFormatSymbols symbols(enLocale, status); if (status.isSuccess()) { DecimalFormat fmt("0", symbols, status); assertSuccess("Fail: Construct DecimalFormat formatter", status, true, __FILE__, __LINE__); ParsePosition ppos(0); fmt.parseCurrency("53.45", ppos); // NPE thrown here in ICU4J. assertEquals("Issue11735 ppos", 0, ppos.getIndex()); } } void NumberFormatTest::Test11035_FormatCurrencyAmount() { UErrorCode status = U_ZERO_ERROR; double amount = 12345.67; const char16_t* expected = u"12,345$67 ​"; // Test two ways to set a currency via API Locale loc1 = Locale("pt_PT"); LocalPointer<NumberFormat> fmt1(NumberFormat::createCurrencyInstance("loc1", status), status); if (U_FAILURE(status)) { dataerrln("%s %d NumberFormat instance fmt1 is null", __FILE__, __LINE__); return; } fmt1->setCurrency(u"PTE", status); assertSuccess("Setting currency on fmt1", status); UnicodeString actualSetCurrency; fmt1->format(amount, actualSetCurrency); Locale loc2 = Locale("pt_PT@currency=PTE"); LocalPointer<NumberFormat> fmt2(NumberFormat::createCurrencyInstance(loc2, status)); assertSuccess("Creating fmt2", status); UnicodeString actualLocaleString; fmt2->format(amount, actualLocaleString); // TODO: The following test will fail until DecimalFormat wraps NumberFormatter. if (!logKnownIssue("13574")) { assertEquals("Custom Currency Pattern, Set Currency", expected, actualSetCurrency); } } void NumberFormatTest::Test11318_DoubleConversion() { IcuTestErrorCode status(*this, "Test11318_DoubleConversion"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (U_FAILURE(status)) { dataerrln("%s %d Error in NumberFormat instance creation", __FILE__, __LINE__); return; } nf->setMaximumFractionDigits(40); nf->setMaximumIntegerDigits(40); UnicodeString appendTo; nf->format(999999999999999.9, appendTo); assertEquals("Should render all digits", u"999,999,999,999,999.9", appendTo); } void NumberFormatTest::TestParsePercentRegression() { IcuTestErrorCode status(*this, "TestParsePercentRegression"); LocalPointer<DecimalFormat> df1((DecimalFormat*) NumberFormat::createInstance("en", status), status); LocalPointer<DecimalFormat> df2((DecimalFormat*) NumberFormat::createPercentInstance("en", status), status); if (status.isFailure()) {return; } df1->setLenient(TRUE); df2->setLenient(TRUE); { ParsePosition ppos; Formattable result; df1->parse("50%", result, ppos); assertEquals("df1 should accept a number but not the percent sign", 2, ppos.getIndex()); assertEquals("df1 should return the number as 50", 50.0, result.getDouble(status)); } { ParsePosition ppos; Formattable result; df2->parse("50%", result, ppos); assertEquals("df2 should accept the percent sign", 3, ppos.getIndex()); assertEquals("df2 should return the number as 0.5", 0.5, result.getDouble(status)); } { ParsePosition ppos; Formattable result; df2->parse("50", result, ppos); assertEquals("df2 should return the number as 0.5 even though the percent sign is missing", 0.5, result.getDouble(status)); } } void NumberFormatTest::TestMultiplierWithScale() { IcuTestErrorCode status(*this, "TestMultiplierWithScale"); // Test magnitude combined with multiplier, as shown in API docs DecimalFormat df("0", {"en", status}, status); if (status.isSuccess()) { df.setMultiplier(5); df.setMultiplierScale(-1); expect2(df, 100, u"50"); // round-trip test } } void NumberFormatTest::TestFastFormatInt32() { IcuTestErrorCode status(*this, "TestFastFormatInt32"); // The two simplest formatters, old API and new API. // Old API should use the fastpath for ints. LocalizedNumberFormatter lnf = NumberFormatter::withLocale("en"); LocalPointer<NumberFormat> df(NumberFormat::createInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) {return;} double nums[] = { 0.0, -0.0, NAN, INFINITY, 0.1, 1.0, 1.1, 2.0, 3.0, 9.0, 10.0, 99.0, 100.0, 999.0, 1000.0, 9999.0, 10000.0, 99999.0, 100000.0, 999999.0, 1000000.0, static_cast<double>(INT32_MAX) - 1, static_cast<double>(INT32_MAX), static_cast<double>(INT32_MAX) + 1, static_cast<double>(INT32_MIN) - 1, static_cast<double>(INT32_MIN), static_cast<double>(INT32_MIN) + 1}; for (auto num : nums) { UnicodeString expected = lnf.formatDouble(num, status).toString(); UnicodeString actual; df->format(num, actual); assertEquals(UnicodeString("d = ") + num, expected, actual); } } void NumberFormatTest::Test11646_Equality() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getEnglish(), status); UnicodeString pattern(u"\u00a4\u00a4\u00a4 0.00 %\u00a4\u00a4"); DecimalFormat fmt(pattern, symbols, status); if (!assertSuccess("", status)) return; // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString positivePrefix; fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix(positivePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy = DecimalFormat(fmt); assertTrue("", fmt == fmtCopy); UnicodeString positivePrefix; fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix(positivePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString negativePrefix; fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix(negativePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString negativePrefix; fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix(negativePrefix)); assertFalse("", fmt == fmtCopy); } } void NumberFormatTest::TestParseNaN() { IcuTestErrorCode status(*this, "TestParseNaN"); DecimalFormat df("0", { "en", status }, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } Formattable parseResult; df.parse(u"NaN", parseResult, status); assertEquals("NaN should parse successfully", NAN, parseResult.getDouble()); assertFalse("Result NaN should be positive", std::signbit(parseResult.getDouble())); UnicodeString formatResult; df.format(parseResult.getDouble(), formatResult); assertEquals("NaN should round-trip", u"NaN", formatResult); } void NumberFormatTest::Test11897_LocalizedPatternSeparator() { IcuTestErrorCode status(*this, "Test11897_LocalizedPatternSeparator"); // In a locale with a different <list> symbol, like arabic, // kPatternSeparatorSymbol should still be ';' { DecimalFormatSymbols dfs("ar", status); assertEquals("pattern separator symbol should be ;", u";", dfs.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)); } // However, the custom symbol should be used in localized notation // when set manually via API { DecimalFormatSymbols dfs("en", status); dfs.setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, u"!", FALSE); DecimalFormat df(u"0", dfs, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } df.applyPattern("a0;b0", status); // should not throw UnicodeString result; assertEquals("should apply the normal pattern", df.getNegativePrefix(result.remove()), "b"); df.applyLocalizedPattern(u"c0!d0", status); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(result.remove()), "d"); } } void NumberFormatTest::Test13055_PercentageRounding() { IcuTestErrorCode status(*this, "PercentageRounding"); UnicodeString actual; LocalPointer<NumberFormat>pFormat(NumberFormat::createPercentInstance("en_US", status)); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } pFormat->setMaximumFractionDigits(0); pFormat->setRoundingMode(DecimalFormat::kRoundHalfEven); pFormat->format(2.155, actual); assertEquals("Should round percent toward even number", "216%", actual); } void NumberFormatTest::Test11839() { IcuTestErrorCode errorCode(*this, "Test11839"); // Ticket #11839: DecimalFormat does not respect custom plus sign LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(Locale::getEnglish(), errorCode), errorCode); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } dfs->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u"a∸"); dfs->setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u"b∔"); // ∔ U+2214 DOT PLUS DecimalFormat df(u"0.00+;0.00-", dfs.orphan(), errorCode); UnicodeString result; df.format(-1.234, result, errorCode); assertEquals("Locale-specific minus sign should be used", u"1.23a∸", result); df.format(1.234, result.remove(), errorCode); assertEquals("Locale-specific plus sign should be used", u"1.23b∔", result); // Test round-trip with parse expect2(df, -456, u"456.00a∸"); expect2(df, 456, u"456.00b∔"); } void NumberFormatTest::Test10354() { IcuTestErrorCode errorCode(*this, "Test10354"); // Ticket #10354: invalid FieldPositionIterator when formatting with empty NaN DecimalFormatSymbols dfs(errorCode); UnicodeString empty; dfs.setSymbol(DecimalFormatSymbols::kNaNSymbol, empty); DecimalFormat df(errorCode); df.setDecimalFormatSymbols(dfs); UnicodeString result; FieldPositionIterator positions; df.format(NAN, result, &positions, errorCode); errorCode.errIfFailureAndReset("DecimalFormat.format(NAN, FieldPositionIterator) failed"); FieldPosition fp; while (positions.next(fp)) { // Should not loop forever } } void NumberFormatTest::Test11645_ApplyPatternEquality() { IcuTestErrorCode status(*this, "Test11645_ApplyPatternEquality"); const char16_t* pattern = u"#,##0.0#"; LocalPointer<DecimalFormat> fmt((DecimalFormat*) NumberFormat::createInstance(status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } fmt->applyPattern(pattern, status); LocalPointer<DecimalFormat> fmtCopy; static const int32_t newMultiplier = 37; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getMultiplier() == newMultiplier); fmtCopy->setMultiplier(newMultiplier); assertEquals("Value after setter", fmtCopy->getMultiplier(), newMultiplier); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getMultiplier(), newMultiplier); assertFalse("multiplier", *fmt == *fmtCopy); static const NumberFormat::ERoundingMode newRoundingMode = NumberFormat::ERoundingMode::kRoundCeiling; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getRoundingMode() == newRoundingMode); fmtCopy->setRoundingMode(newRoundingMode); assertEquals("Value after setter", fmtCopy->getRoundingMode(), newRoundingMode); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getRoundingMode(), newRoundingMode); assertFalse("roundingMode", *fmt == *fmtCopy); static const char16_t *const newCurrency = u"EAT"; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getCurrency() == newCurrency); fmtCopy->setCurrency(newCurrency); assertEquals("Value after setter", fmtCopy->getCurrency(), newCurrency); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getCurrency(), newCurrency); assertFalse("currency", *fmt == *fmtCopy); static const UCurrencyUsage newCurrencyUsage = UCurrencyUsage::UCURR_USAGE_CASH; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getCurrencyUsage() == newCurrencyUsage); fmtCopy->setCurrencyUsage(newCurrencyUsage, status); assertEquals("Value after setter", fmtCopy->getCurrencyUsage(), newCurrencyUsage); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getCurrencyUsage(), newCurrencyUsage); assertFalse("currencyUsage", *fmt == *fmtCopy); } void NumberFormatTest::Test12567() { IcuTestErrorCode errorCode(*this, "Test12567"); // Ticket #12567: DecimalFormat.equals() may not be symmetric LocalPointer<DecimalFormat> df1((DecimalFormat *) NumberFormat::createInstance(Locale::getUS(), UNUM_CURRENCY, errorCode)); LocalPointer<DecimalFormat> df2((DecimalFormat *) NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, errorCode)); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } // NOTE: CurrencyPluralInfo equality not tested in C++ because its operator== is not defined. df1->applyPattern(u"0.00", errorCode); df2->applyPattern(u"0.00", errorCode); assertTrue("df1 == df2", *df1 == *df2); assertTrue("df2 == df1", *df2 == *df1); df2->setPositivePrefix(u"abc"); assertTrue("df1 != df2", *df1 != *df2); assertTrue("df2 != df1", *df2 != *df1); } void NumberFormatTest::Test11626_CustomizeCurrencyPluralInfo() { IcuTestErrorCode errorCode(*this, "Test11626_CustomizeCurrencyPluralInfo"); // Ticket #11626: No unit test demonstrating how to use CurrencyPluralInfo to // change formatting spelled out currencies // Use locale sr because it has interesting plural rules. Locale locale("sr"); LocalPointer<DecimalFormatSymbols> symbols(new DecimalFormatSymbols(locale, errorCode), errorCode); CurrencyPluralInfo info(locale, errorCode); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } info.setCurrencyPluralPattern(u"one", u"0 qwerty", errorCode); info.setCurrencyPluralPattern(u"few", u"0 dvorak", errorCode); DecimalFormat df(u"#", symbols.orphan(), UNUM_CURRENCY_PLURAL, errorCode); df.setCurrencyPluralInfo(info); df.setCurrency(u"USD"); df.setMaximumFractionDigits(0); UnicodeString result; assertEquals("Plural one", u"1 qwerty", df.format(1, result, errorCode)); assertEquals("Plural few", u"3 dvorak", df.format(3, result.remove(), errorCode)); assertEquals("Plural other", u"99 америчких долара", df.format(99, result.remove(), errorCode)); info.setPluralRules(u"few: n is 1; one: n in 2..4", errorCode); df.setCurrencyPluralInfo(info); assertEquals("Plural one", u"1 dvorak", df.format(1, result.remove(), errorCode)); assertEquals("Plural few", u"3 qwerty", df.format(3, result.remove(), errorCode)); assertEquals("Plural other", u"99 америчких долара", df.format(99, result.remove(), errorCode)); } void NumberFormatTest::Test20073_StrictPercentParseErrorIndex() { IcuTestErrorCode status(*this, "Test20073_StrictPercentParseErrorIndex"); ParsePosition parsePosition(0); DecimalFormat df(u"0%", {"en-us", status}, status); if (U_FAILURE(status)) { dataerrln("Unable to create DecimalFormat instance."); return; } df.setLenient(FALSE); Formattable result; df.parse(u"%2%", result, parsePosition); assertEquals("", 0, parsePosition.getIndex()); assertEquals("", 0, parsePosition.getErrorIndex()); } void NumberFormatTest::Test13056_GroupingSize() { UErrorCode status = U_ZERO_ERROR; DecimalFormat df(u"#,##0", status); if (!assertSuccess("", status)) return; assertEquals("Primary grouping should return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should return 0", 0, df.getSecondaryGroupingSize()); df.setSecondaryGroupingSize(3); assertEquals("Primary grouping should still return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should round-trip", 3, df.getSecondaryGroupingSize()); df.setGroupingSize(4); assertEquals("Primary grouping should return 4", 4, df.getGroupingSize()); assertEquals("Secondary should remember explicit setting and return 3", 3, df.getSecondaryGroupingSize()); } void NumberFormatTest::Test11025_CurrencyPadding() { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern(u"¤¤ **####0.00"); DecimalFormatSymbols sym(Locale::getFrance(), status); if (!assertSuccess("", status)) return; DecimalFormat fmt(pattern, sym, status); if (!assertSuccess("", status)) return; UnicodeString result; fmt.format(433.0, result); assertEquals("Number should be padded to 11 characters", "EUR *433,00", result); } void NumberFormatTest::Test11648_ExpDecFormatMalPattern() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("0.00", {"en", status}, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } fmt.setScientificNotation(TRUE); UnicodeString pattern; assertEquals("A valid scientific notation pattern should be produced", "0.00E0", fmt.toPattern(pattern)); DecimalFormat fmt2(pattern, status); assertSuccess("", status); } void NumberFormatTest::Test11649_DecFmtCurrencies() { IcuTestErrorCode status(*this, "Test11649_DecFmtCurrencies"); UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } static const UChar USD[] = u"USD"; fmt.setCurrency(USD); UnicodeString appendTo; assertEquals("", "US dollars 12.34", fmt.format(12.34, appendTo)); UnicodeString topattern; assertEquals("", pattern, fmt.toPattern(topattern)); DecimalFormat fmt2(topattern, status); fmt2.setCurrency(USD); appendTo.remove(); assertEquals("", "US dollars 12.34", fmt2.format(12.34, appendTo)); } void NumberFormatTest::Test13148_ParseGroupingSeparators() { IcuTestErrorCode status(*this, "Test13148"); LocalPointer<DecimalFormat> fmt( (DecimalFormat*)NumberFormat::createInstance("en-ZA", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } DecimalFormatSymbols symbols = *fmt->getDecimalFormatSymbols(); symbols.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u'.'); symbols.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u','); fmt->setDecimalFormatSymbols(symbols); Formattable number; fmt->parse(u"300,000", number, status); assertEquals("Should parse as 300000", 300000LL, number.getInt64(status)); } void NumberFormatTest::Test12753_PatternDecimalPoint() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getUS(), status); symbols.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u"*", false); DecimalFormat df(u"0.00", symbols, status); if (!assertSuccess("", status)) return; df.setDecimalPatternMatchRequired(true); Formattable result; df.parse(u"123",result, status); assertEquals("Parsing integer succeeded even though setDecimalPatternMatchRequired was set", U_INVALID_FORMAT_ERROR, status); } void NumberFormatTest::Test11647_PatternCurrencySymbols() { UErrorCode status = U_ZERO_ERROR; DecimalFormat df(status); df.applyPattern(u"¤¤¤¤#", status); if (!assertSuccess("", status)) return; UnicodeString actual; df.format(123, actual); assertEquals("Should replace 4 currency signs with U+FFFD", u"\uFFFD123", actual); } void NumberFormatTest::Test11913_BigDecimal() { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> df(NumberFormat::createInstance(Locale::getEnglish(), status), status); if (!assertSuccess("", status)) return; UnicodeString result; df->format(StringPiece("1.23456789E400"), result, nullptr, status); assertSuccess("", status); assertEquals("Should format more than 309 digits", u"12,345,678", UnicodeString(result, 0, 10)); assertEquals("Should format more than 309 digits", 534, result.length()); } void NumberFormatTest::Test11020_RoundingInScientificNotation() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getFrance(), status); DecimalFormat fmt(u"0.05E0", sym, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } assertSuccess("", status); UnicodeString result; fmt.format(12301.2, result); assertEquals("Rounding increment should be applied after magnitude scaling", u"1,25E4", result); } void NumberFormatTest::Test11640_TripleCurrencySymbol() { IcuTestErrorCode status(*this, "Test11640_TripleCurrencySymbol"); UnicodeString actual; DecimalFormat dFormat(u"¤¤¤ 0", status); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } dFormat.setCurrency(u"USD"); UnicodeString result; dFormat.getPositivePrefix(result); assertEquals("Triple-currency should give long name on getPositivePrefix", "US dollars ", result); } void NumberFormatTest::Test13763_FieldPositionIteratorOffset() { IcuTestErrorCode status(*this, "Test13763_FieldPositionIteratorOffset"); FieldPositionIterator fpi; UnicodeString result(u"foo\U0001F4FBbar"); // 8 code units LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } nf->format(5142.3, result, &fpi, status); int32_t expected[] = { UNUM_GROUPING_SEPARATOR_FIELD, 9, 10, UNUM_INTEGER_FIELD, 8, 13, UNUM_DECIMAL_SEPARATOR_FIELD, 13, 14, UNUM_FRACTION_FIELD, 14, 15, }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; expectPositions(fpi, expected, tupleCount, result); } void NumberFormatTest::Test13777_ParseLongNameNonCurrencyMode() { IcuTestErrorCode status(*this, "Test13777_ParseLongNameNonCurrencyMode"); LocalPointer<NumberFormat> df( NumberFormat::createInstance("en-us", UNumberFormatStyle::UNUM_CURRENCY_PLURAL, status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } expect2(*df, 1.5, u"1.50 US dollars"); } void NumberFormatTest::Test13804_EmptyStringsWhenParsing() { IcuTestErrorCode status(*this, "Test13804_EmptyStringsWhenParsing"); DecimalFormatSymbols dfs("en", status); if (status.errIfFailureAndReset()) { return; } dfs.setSymbol(DecimalFormatSymbols::kCurrencySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kOneDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kTwoDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kThreeDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kFourDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kFiveDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kSixDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kSevenDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kEightDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kNineDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kExponentMultiplicationSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kInfinitySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kNaNSymbol, u"", FALSE); dfs.setPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, FALSE, u""); dfs.setPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, TRUE, u""); dfs.setSymbol(DecimalFormatSymbols::kPercentSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kPerMillSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u"", FALSE); DecimalFormat df("0", dfs, status); if (status.errIfFailureAndReset()) { return; } df.setGroupingUsed(TRUE); df.setScientificNotation(TRUE); df.setLenient(TRUE); // enable all matchers { UnicodeString result; df.format(0, result); // should not crash or hit infinite loop } const char16_t* samples[] = { u"", u"123", u"$123", u"-", u"+", u"44%", u"1E+2.3" }; for (auto& sample : samples) { logln(UnicodeString(u"Attempting parse on: ") + sample); status.setScope(sample); // We don't care about the results, only that we don't crash and don't loop. Formattable result; ParsePosition ppos(0); df.parse(sample, result, ppos); ppos = ParsePosition(0); LocalPointer<CurrencyAmount> curramt(df.parseCurrency(sample, ppos)); status.errIfFailureAndReset(); } // Test with a nonempty exponent separator symbol to cover more code dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"E", FALSE); df.setDecimalFormatSymbols(dfs); { Formattable result; ParsePosition ppos(0); df.parse(u"1E+2.3", result, ppos); } } void NumberFormatTest::Test20037_ScientificIntegerOverflow() { IcuTestErrorCode status(*this, "Test20037_ScientificIntegerOverflow"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance(status)); if (U_FAILURE(status)) { dataerrln("Unable to create NumberFormat instance."); return; } Formattable result; // Test overflow of exponent nf->parse(u"1E-2147483648", result, status); StringPiece sp = result.getDecimalNumber(status); assertEquals(u"Should snap to zero", u"0", {sp.data(), sp.length(), US_INV}); // Test edge case overflow of exponent result = Formattable(); nf->parse(u"1E-2147483647E-1", result, status); sp = result.getDecimalNumber(status); assertEquals(u"Should not overflow and should parse only the first exponent", u"1E-2147483647", {sp.data(), sp.length(), US_INV}); // Test edge case overflow of exponent result = Formattable(); nf->parse(u".0003e-2147483644", result, status); sp = result.getDecimalNumber(status); assertEquals(u"Should not overflow", u"3E-2147483648", {sp.data(), sp.length(), US_INV}); } void NumberFormatTest::Test13840_ParseLongStringCrash() { IcuTestErrorCode status(*this, "Test13840_ParseLongStringCrash"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (status.errIfFailureAndReset()) { return; } Formattable result; static const char16_t* bigString = u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111"; nf->parse(bigString, result, status); // Normalize the input string: CharString expectedChars; expectedChars.appendInvariantChars(bigString, status); DecimalQuantity expectedDQ; expectedDQ.setToDecNumber(expectedChars.toStringPiece(), status); UnicodeString expectedUString = expectedDQ.toScientificString(); // Get the output string: StringPiece actualChars = result.getDecimalNumber(status); UnicodeString actualUString = UnicodeString(actualChars.data(), actualChars.length(), US_INV); assertEquals("Should round-trip without crashing", expectedUString, actualUString); } void NumberFormatTest::Test13850_EmptyStringCurrency() { IcuTestErrorCode status(*this, "Test13840_EmptyStringCurrency"); struct TestCase { const char16_t* currencyArg; UErrorCode expectedError; } cases[] = { {u"", U_ZERO_ERROR}, {u"U", U_ILLEGAL_ARGUMENT_ERROR}, {u"Us", U_ILLEGAL_ARGUMENT_ERROR}, {nullptr, U_ZERO_ERROR}, {u"U$D", U_INVARIANT_CONVERSION_ERROR}, {u"Xxx", U_ZERO_ERROR} }; for (const auto& cas : cases) { UnicodeString message(u"with currency arg: "); if (cas.currencyArg == nullptr) { message += u"nullptr"; } else { message += UnicodeString(cas.currencyArg); } status.setScope(message); LocalPointer<NumberFormat> nf(NumberFormat::createCurrencyInstance("en-US", status), status); if (status.errIfFailureAndReset()) { return; } UnicodeString actual; nf->format(1, actual, status); status.errIfFailureAndReset(); assertEquals(u"Should format with US currency " + message, u"$1.00", actual); nf->setCurrency(cas.currencyArg, status); if (status.expectErrorAndReset(cas.expectedError)) { // If an error occurred, do not check formatting. continue; } nf->format(1, actual.remove(), status); assertEquals(u"Should unset the currency " + message, u"\u00A41.00", actual); status.errIfFailureAndReset(); } } #endif /* #if !UCONFIG_NO_FORMATTING */
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_434_2
crossvul-cpp_data_good_5230_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/string-util.h" #include <algorithm> #include <vector> #include "hphp/zend/zend-html.h" #include "hphp/runtime/base/array-init.h" #include "hphp/util/bstring.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-url.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/array-iterator.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/container-functions.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // manipulations String StringUtil::Pad(const String& input, int final_length, const String& pad_string /* = " " */, PadType type /* = PadType::Right */) { int len = input.size(); return string_pad(input.data(), len, final_length, pad_string.data(), pad_string.size(), static_cast<int>(type)); } String StringUtil::StripHTMLTags(const String& input, const String& allowable_tags /* = "" */) { if (input.empty()) return input; return string_strip_tags(input.data(), input.size(), allowable_tags.data(), allowable_tags.size(), false); } /////////////////////////////////////////////////////////////////////////////// // splits/joins Variant StringUtil::Explode(const String& input, const String& delimiter, int limit /* = 0x7FFFFFFF */) { if (delimiter.empty()) { throw_invalid_argument("delimiter: (empty)"); return false; } Array ret(Array::Create()); if (input.empty()) { if (limit >= 0) { ret.append(""); } return ret; } if (limit > 1) { int pos = input.find(delimiter); if (pos < 0) { ret.append(input); } else { int len = delimiter.size(); int pos0 = 0; do { ret.append(input.substr(pos0, pos - pos0)); pos += len; pos0 = pos; } while ((pos = input.find(delimiter, pos)) >= 0 && --limit > 1); if (pos0 <= input.size()) { ret.append(input.substr(pos0)); } } } else if (limit < 0) { int pos = input.find(delimiter); if (pos >= 0) { std::vector<int> positions; int len = delimiter.size(); int pos0 = 0; int found = 0; do { positions.push_back(pos0); positions.push_back(pos - pos0); pos += len; pos0 = pos; found++; } while ((pos = input.find(delimiter, pos)) >= 0); if (pos0 <= input.size()) { positions.push_back(pos0); positions.push_back(input.size() - pos0); found++; } int iMax = (found + limit) << 1; for (int i = 0; i < iMax; i += 2) { ret.append(input.substr(positions[i], positions[i+1])); } } // else we have negative limit and delimiter not found } else { ret.append(input); } return ret; } String StringUtil::Implode(const Variant& items, const String& delim, const bool checkIsContainer /* = true */) { if (checkIsContainer && !isContainer(items)) { throw_param_is_not_container(); } int size = getContainerSize(items); if (size == 0) return empty_string(); req::vector<String> sitems; sitems.reserve(size); size_t len = 0; size_t lenDelim = delim.size(); for (ArrayIter iter(items); iter; ++iter) { sitems.emplace_back(iter.second().toString()); len += sitems.back().size() + lenDelim; } len -= lenDelim; // always one delimiter less than count of items assert(sitems.size() == size); String s = String(len, ReserveString); char *buffer = s.mutableData(); const char *sdelim = delim.data(); char *p = buffer; String &init_str = sitems[0]; int init_len = init_str.size(); memcpy(p, init_str.data(), init_len); p += init_len; for (int i = 1; i < size; i++) { String &item = sitems[i]; memcpy(p, sdelim, lenDelim); p += lenDelim; int lenItem = item.size(); memcpy(p, item.data(), lenItem); p += lenItem; } assert(p - buffer == len); s.setSize(len); return s; } Variant StringUtil::Split(const String& str, int64_t split_length /* = 1 */) { if (split_length <= 0) { throw_invalid_argument( "The length of each segment must be greater than zero" ); return false; } int len = str.size(); PackedArrayInit ret(len / split_length + 1, CheckAllocation{}); if (split_length >= len) { ret.append(str); } else { for (int i = 0; i < len; i += split_length) { ret.append(str.substr(i, split_length)); } } return ret.toArray(); } Variant StringUtil::ChunkSplit(const String& body, int chunklen /* = 76 */, const String& end /* = "\r\n" */) { if (chunklen <= 0) { throw_invalid_argument("chunklen: (non-positive)"); return false; } String ret; int len = body.size(); if (chunklen >= len) { ret = body; ret += end; } else { return string_chunk_split(body.data(), len, end.c_str(), end.size(), chunklen); } return ret; } /////////////////////////////////////////////////////////////////////////////// // encoding/decoding String StringUtil::HtmlEncode(const String& input, QuoteStyle quoteStyle, const char *charset, bool dEncode, bool htmlEnt) { return HtmlEncode(input, static_cast<int64_t>(quoteStyle), charset, dEncode, htmlEnt); } String StringUtil::HtmlEncode(const String& input, const int64_t qsBitmask, const char *charset, bool dEncode, bool htmlEnt) { if (input.empty()) return input; assert(charset); bool utf8 = true; if (strcasecmp(charset, "ISO-8859-1") == 0) { utf8 = false; } else if (strcasecmp(charset, "UTF-8")) { throw_not_implemented(charset); } int len = input.size(); char *ret = string_html_encode(input.data(), len, qsBitmask, utf8, dEncode, htmlEnt); if (!ret) { return empty_string(); } return String(ret, len, AttachString); } #define A1(v, ch) ((v)|((ch) & 64 ? 0 : 1uLL<<((ch)&63))) #define A2(v, ch) ((v)|((ch) & 64 ? 1uLL<<((ch)&63) : 0)) static const AsciiMap mapNoQuotes = { { A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@') } }; static const AsciiMap mapDoubleQuotes = { { A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"') } }; static const AsciiMap mapBothQuotes = { { A1(A1(A1(A1(A1(A1(A1(A1(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\''), A2(A2(A2(A2(A2(A2(A2(A2(0, '<'), '>'), '&'), '{'), '}'), '@'), '"'), '\'') } }; static const AsciiMap mapNothing = {}; String StringUtil::HtmlEncodeExtra(const String& input, QuoteStyle quoteStyle, const char *charset, bool nbsp, Array extra) { if (input.empty()) return input; assert(charset); int flags = STRING_HTML_ENCODE_UTF8; if (nbsp) { flags |= STRING_HTML_ENCODE_NBSP; } if (RuntimeOption::Utf8izeReplace) { flags |= STRING_HTML_ENCODE_UTF8IZE_REPLACE; } if (!*charset || strcasecmp(charset, "UTF-8") == 0) { } else if (strcasecmp(charset, "ISO-8859-1") == 0) { flags &= ~STRING_HTML_ENCODE_UTF8; } else { throw_not_implemented(charset); } const AsciiMap *am; AsciiMap tmp; switch (quoteStyle) { case QuoteStyle::FBUtf8Only: am = &mapNothing; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::FBUtf8: am = &mapBothQuotes; flags |= STRING_HTML_ENCODE_HIGH; break; case QuoteStyle::Both: am = &mapBothQuotes; break; case QuoteStyle::Double: am = &mapDoubleQuotes; break; case QuoteStyle::No: am = &mapNoQuotes; break; default: am = &mapNothing; raise_error("Unknown quote style: %d", (int)quoteStyle); } if (quoteStyle != QuoteStyle::FBUtf8Only && extra.toBoolean()) { tmp = *am; am = &tmp; for (ArrayIter iter(extra); iter; ++iter) { String item = iter.second().toString(); char c = item.data()[0]; tmp.map[c & 64 ? 1 : 0] |= 1uLL << (c & 63); } } int len = input.size(); char *ret = string_html_encode_extra(input.data(), len, (StringHtmlEncoding)flags, am); if (!ret) { raise_error("HtmlEncode called on too large input (%d)", len); } return String(ret, len, AttachString); } String StringUtil::HtmlDecode(const String& input, QuoteStyle quoteStyle, const char *charset, bool all) { if (input.empty()) return input; assert(charset); int len = input.size(); char *ret = string_html_decode(input.data(), len, quoteStyle != QuoteStyle::No, quoteStyle == QuoteStyle::Both, charset, all); if (!ret) { // null iff charset was not recognized throw_not_implemented(charset); // (charset is not null, see assertion above) } return String(ret, len, AttachString); } String StringUtil::QuotedPrintableEncode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_encode(input.data(), len); } String StringUtil::QuotedPrintableDecode(const String& input) { if (input.empty()) return input; int len = input.size(); return string_quoted_printable_decode(input.data(), len, false); } String StringUtil::UUEncode(const String& input) { if (input.empty()) return input; return string_uuencode(input.data(), input.size()); } String StringUtil::UUDecode(const String& input) { if (!input.empty()) { return string_uudecode(input.data(), input.size()); } return String(); } String StringUtil::Base64Encode(const String& input) { int len = input.size(); return string_base64_encode(input.data(), len); } String StringUtil::Base64Decode(const String& input, bool strict /* = false */) { int len = input.size(); return string_base64_decode(input.data(), len, strict); } String StringUtil::UrlEncode(const String& input, bool encodePlus /* = true */) { return encodePlus ? url_encode(input.data(), input.size()) : url_raw_encode(input.data(), input.size()); } String StringUtil::UrlDecode(const String& input, bool decodePlus /* = true */) { return decodePlus ? url_decode(input.data(), input.size()) : url_raw_decode(input.data(), input.size()); } bool StringUtil::IsFileUrl(const String& input) { return string_strncasecmp( input.data(), input.size(), "file://", sizeof("file://") - 1, sizeof("file://") - 1) == 0; } String StringUtil::DecodeFileUrl(const String& input) { Url url; if (!url_parse(url, input.data(), input.size())) { return null_string; } if (bstrcasecmp(url.scheme.data(), url.scheme.size(), "file", sizeof("file")-1) != 0) { // Not file scheme return null_string; } if (url.host.size() > 0 && bstrcasecmp(url.host.data(), url.host.size(), "localhost", sizeof("localhost")-1) != 0) { // Not localhost or empty host return null_string; } return url_raw_decode(url.path.data(), url.path.size()); } /////////////////////////////////////////////////////////////////////////////// // formatting String StringUtil::MoneyFormat(const char *format, double value) { assert(format); return string_money_format(format, value); } /////////////////////////////////////////////////////////////////////////////// // hashing String StringUtil::Translate(const String& input, const String& from, const String& to) { if (input.empty()) return input; int len = input.size(); String retstr(len, ReserveString); char *ret = retstr.mutableData(); memcpy(ret, input.data(), len); auto trlen = std::min(from.size(), to.size()); string_translate(ret, len, from.data(), to.data(), trlen); retstr.setSize(len); return retstr; } String StringUtil::ROT13(const String& input) { if (input.empty()) return input; return String(string_rot13(input.data(), input.size()), input.size(), AttachString); } int64_t StringUtil::CRC32(const String& input) { return string_crc32(input.data(), input.size()); } String StringUtil::Crypt(const String& input, const char *salt /* = "" */) { if (salt && salt[0] == '\0') { raise_notice("crypt(): No salt parameter was specified." " You must use a randomly generated salt and a strong" " hash function to produce a secure hash."); } return String(string_crypt(input.c_str(), salt), AttachString); } String StringUtil::MD5(const char *data, uint32_t size, bool raw /* = false */) { Md5Digest md5(data, size); auto const rawLen = sizeof(md5.digest); if (raw) return String((char*)md5.digest, rawLen, CopyString); auto const hexLen = rawLen * 2; String hex(hexLen, ReserveString); string_bin2hex((char*)md5.digest, rawLen, hex.mutableData()); hex.setSize(hexLen); return hex; } String StringUtil::MD5(const String& input, bool raw /* = false */) { return MD5(input.data(), input.length(), raw); } String StringUtil::SHA1(const String& input, bool raw /* = false */) { int len; char *ret = string_sha1(input.data(), input.size(), raw, len); return String(ret, len, AttachString); } /////////////////////////////////////////////////////////////////////////////// // integer safety for string allocations size_t safe_address(size_t nmemb, size_t size, size_t offset) { uint64_t result = (uint64_t) nmemb * (uint64_t) size + (uint64_t) offset; if (UNLIKELY(result > StringData::MaxSize)) { throw FatalErrorException(0, "String length exceeded 2^31-2: %" PRIu64, result); } return result; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_5230_0
crossvul-cpp_data_good_582_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, unsigned count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD else if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF; for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if(width>768 || raw_width>768 || height > 512 || raw_height>512 ) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; if(col>=0) FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* extra room for data stored w/o predictor */ int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float libraw_powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * libraw_powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; #ifdef LIBRAW_LIBRARY_BUILD if(offset>ifp->size()-8) // At least 8 bytes for tag/len offset = ifp->size()-8; #endif while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); if(len < 0) return; // just ignore wrong len?? or raise bad file exception? switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64(2.0f, -int_to_float((get4(),get4()))); aperture = libraw_powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = libraw_powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 { ushort q = get2(); cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024; } if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; if ((int)size < 0) return; // 2+GB is too much if (save + size < save) return; // 32bit overflow fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // data length should be in range w*h..w*h*2 if(width*height < (LIBRAW_MAX_ALLOC_MB*1024*512L) && width*height>1 && i >= width * height && i <= width*height*2) { #endif switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD } else is_raw = 0; #endif } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ( (int)width + (int)left_margin > 65535) || ( (int)height + (int)top_margin > 65535) ) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_582_1
crossvul-cpp_data_bad_1010_0
// ***************************************************************** -*- C++ -*- /* * Copyright (C) 2004-2018 Exiv2 authors * This program is part of the Exiv2 distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA. */ /* File: webpimage.cpp */ /* Google's WEBP container spec can be found at the link below: https://developers.google.com/speed/webp/docs/riff_container */ // ***************************************************************************** // included header files #include "config.h" #include "webpimage.hpp" #include "image_int.hpp" #include "enforce.hpp" #include "futils.hpp" #include "basicio.hpp" #include "tags.hpp" #include "tags_int.hpp" #include "types.hpp" #include "tiffimage.hpp" #include "tiffimage_int.hpp" #include "convert.hpp" #include "safe_op.hpp" #include <cmath> #include <iomanip> #include <string> #include <cstring> #include <iostream> #include <sstream> #include <cassert> #include <cstdio> #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) // ***************************************************************************** // class member definitions namespace Exiv2 { namespace Internal { }} // namespace Internal, Exiv2 namespace Exiv2 { using namespace Exiv2::Internal; // This static function is a temporary fix in v0.27. In the next version, // it will be added as a method of BasicIo. static void readOrThrow(BasicIo& iIo, byte* buf, long rcount, ErrorCode err) { const long nread = iIo.read(buf, rcount); enforce(nread == rcount, err); enforce(!iIo.error(), err); } WebPImage::WebPImage(BasicIo::AutoPtr io) : Image(ImageType::webp, mdNone, io) { } // WebPImage::WebPImage std::string WebPImage::mimeType() const { return "image/webp"; } /* =========================================== */ /* Misc. */ const byte WebPImage::WEBP_PAD_ODD = 0; const int WebPImage::WEBP_TAG_SIZE = 0x4; /* VP8X feature flags */ const int WebPImage::WEBP_VP8X_ICC_BIT = 0x20; const int WebPImage::WEBP_VP8X_ALPHA_BIT = 0x10; const int WebPImage::WEBP_VP8X_EXIF_BIT = 0x8; const int WebPImage::WEBP_VP8X_XMP_BIT = 0x4; /* Chunk header names */ const char* WebPImage::WEBP_CHUNK_HEADER_VP8X = "VP8X"; const char* WebPImage::WEBP_CHUNK_HEADER_VP8L = "VP8L"; const char* WebPImage::WEBP_CHUNK_HEADER_VP8 = "VP8 "; const char* WebPImage::WEBP_CHUNK_HEADER_ANMF = "ANMF"; const char* WebPImage::WEBP_CHUNK_HEADER_ANIM = "ANIM"; const char* WebPImage::WEBP_CHUNK_HEADER_ICCP = "ICCP"; const char* WebPImage::WEBP_CHUNK_HEADER_EXIF = "EXIF"; const char* WebPImage::WEBP_CHUNK_HEADER_XMP = "XMP "; /* =========================================== */ void WebPImage::setIptcData(const IptcData& /*iptcData*/) { // not supported // just quietly ignore the request // throw(Error(kerInvalidSettingForImage, "IPTC metadata", "WebP")); } void WebPImage::setComment(const std::string& /*comment*/) { // not supported throw(Error(kerInvalidSettingForImage, "Image comment", "WebP")); } /* =========================================== */ void WebPImage::writeMetadata() { if (io_->open() != 0) { throw Error(kerDataSourceOpenFailed, io_->path(), strError()); } IoCloser closer(*io_); BasicIo::AutoPtr tempIo(new MemIo); assert (tempIo.get() != 0); doWriteMetadata(*tempIo); // may throw io_->close(); io_->transfer(*tempIo); // may throw } // WebPImage::writeMetadata void WebPImage::doWriteMetadata(BasicIo& outIo) { if (!io_->isopen()) throw Error(kerInputDataReadFailed); if (!outIo.isopen()) throw Error(kerImageWriteFailed); #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Writing metadata" << std::endl; #endif byte data [WEBP_TAG_SIZE*3]; DataBuf chunkId(WEBP_TAG_SIZE+1); chunkId.pData_ [WEBP_TAG_SIZE] = '\0'; io_->read(data, WEBP_TAG_SIZE * 3); uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian); /* Set up header */ if (outIo.write(data, WEBP_TAG_SIZE * 3) != WEBP_TAG_SIZE * 3) throw Error(kerImageWriteFailed); /* Parse Chunks */ bool has_size = false; bool has_xmp = false; bool has_exif = false; bool has_vp8x = false; bool has_alpha = false; bool has_icc = iccProfileDefined(); int width = 0; int height = 0; byte size_buff[WEBP_TAG_SIZE]; Blob blob; if (exifData_.count() > 0) { ExifParser::encode(blob, littleEndian, exifData_); if (blob.size() > 0) { has_exif = true; } } if (xmpData_.count() > 0 && !writeXmpFromPacket()) { XmpParser::encode(xmpPacket_, xmpData_, XmpParser::useCompactFormat | XmpParser::omitAllFormatting); } has_xmp = xmpPacket_.size() > 0; std::string xmp(xmpPacket_); /* Verify for a VP8X Chunk First before writing in case we have any exif or xmp data, also check for any chunks with alpha frame/layer set */ while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, WEBP_TAG_SIZE); io_->read(size_buff, WEBP_TAG_SIZE); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, payload.size_); byte c; if ( payload.size_ % 2 ) io_->read(&c,1); /* Chunk with information about features used in the file. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) { has_vp8x = true; } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[4], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[7], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with with animation control data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANIM) && !has_alpha) { has_alpha = true; } #endif /* Chunk with with lossy image data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_alpha) { has_alpha = true; } #endif if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) { has_size = true; byte size_buf[2]; /* Refer to this https://tools.ietf.org/html/rfc6386 for height and width reference for VP8 chunks */ // Fetch width - stored in 16bits memcpy(&size_buf, &payload.pData_[6], 2); width = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; // Fetch height - stored in 16bits memcpy(&size_buf, &payload.pData_[8], 2); height = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; } /* Chunk with with lossless image data. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) { if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) { has_size = true; byte size_buf_w[2]; byte size_buf_h[3]; /* For VP8L chunks width & height are stored in 28 bits of a 32 bit field requires bitshifting to get actual sizes. Width and height are split even into 14 bits each. Refer to this https://goo.gl/bpgMJf */ // Fetch width - 14 bits wide memcpy(&size_buf_w, &payload.pData_[1], 2); size_buf_w[1] &= 0x3F; width = Exiv2::getUShort(size_buf_w, littleEndian) + 1; // Fetch height - 14 bits wide memcpy(&size_buf_h, &payload.pData_[2], 3); size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2); size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2); height = Exiv2::getUShort(size_buf_h, littleEndian) + 1; } /* Chunk with animation frame. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) { if ((payload.pData_[5] & 0x2) == 0x2) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[6], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[9], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with alpha data. */ if (equalsWebPTag(chunkId, "ALPH") && !has_alpha) { has_alpha = true; } } /* Inject a VP8X chunk if one isn't available. */ if (!has_vp8x) { inject_VP8X(outIo, has_xmp, has_exif, has_alpha, has_icc, width, height); } io_->seek(12, BasicIo::beg); while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, 4); io_->read(size_buff, 4); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, size); if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) { if (has_icc){ payload.pData_[0] |= WEBP_VP8X_ICC_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_ICC_BIT; } if (has_xmp){ payload.pData_[0] |= WEBP_VP8X_XMP_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_XMP_BIT; } if (has_exif) { payload.pData_[0] |= WEBP_VP8X_EXIF_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_EXIF_BIT; } if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } if (has_icc) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_ICCP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) iccProfile_.size_, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) { throw Error(kerImageWriteFailed); } has_icc = false; } } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) { // Skip it altogether handle it prior to here :) } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) { // Skip and add new data afterwards } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) { // Skip and add new data afterwards } else { if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); } // Encoder required to pad odd sized data with a null byte if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_exif) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_EXIF, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); us2Data(data, (uint16_t) blob.size()+8, bigEndian); ul2Data(data, (uint32_t) blob.size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)&blob[0], static_cast<long>(blob.size())) != (long)blob.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_xmp) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_XMP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) xmpPacket().size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)xmp.data(), static_cast<long>(xmp.size())) != (long)xmp.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } // Fix File Size Payload Data outIo.seek(0, BasicIo::beg); filesize = outIo.size() - 8; outIo.seek(4, BasicIo::beg); ul2Data(data, (uint32_t) filesize, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); } // WebPImage::writeMetadata /* =========================================== */ void WebPImage::printStructure(std::ostream& out, PrintStructureOption option,int depth) { if (io_->open() != 0) { throw Error(kerDataSourceOpenFailed, io_->path(), strError()); } // Ensure this is the correct image type if (!isWebPType(*io_, true)) { if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData); throw Error(kerNotAnImage, "WEBP"); } bool bPrint = option==kpsBasic || option==kpsRecursive; if ( bPrint || option == kpsXMP || option == kpsIccProfile || option == kpsIptcErase ) { byte data [WEBP_TAG_SIZE * 2]; io_->read(data, WEBP_TAG_SIZE * 2); uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian); DataBuf chunkId(5) ; chunkId.pData_[4] = '\0' ; if ( bPrint ) { out << Internal::indent(depth) << "STRUCTURE OF WEBP FILE: " << io().path() << std::endl; out << Internal::indent(depth) << Internal::stringFormat(" Chunk | Length | Offset | Payload") << std::endl; } io_->seek(0,BasicIo::beg); // rewind while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { uint64_t offset = (uint64_t) io_->tell(); byte size_buff[WEBP_TAG_SIZE]; io_->read(chunkId.pData_, WEBP_TAG_SIZE); io_->read(size_buff, WEBP_TAG_SIZE); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(offset?size:WEBP_TAG_SIZE); // header is different from chunks io_->read(payload.pData_, payload.size_); if ( bPrint ) { out << Internal::indent(depth) << Internal::stringFormat(" %s | %8u | %8u | ", (const char*)chunkId.pData_,(uint32_t)size,(uint32_t)offset) << Internal::binaryToString(makeSlice(payload, 0, payload.size_ > 32 ? 32 : payload.size_)) << std::endl; } if ( equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF) && option==kpsRecursive ) { // create memio object with the payload, then print the structure BasicIo::AutoPtr p = BasicIo::AutoPtr(new MemIo(payload.pData_,payload.size_)); printTiffStructure(*p,out,option,depth); } bool bPrintPayload = (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP) && option==kpsXMP) || (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP) && option==kpsIccProfile) ; if ( bPrintPayload ) { out.write((const char*) payload.pData_,payload.size_); } if ( offset && io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); // skip padding byte on sub-chunks } } } /* =========================================== */ void WebPImage::readMetadata() { if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); // Ensure that this is the correct image type if (!isWebPType(*io_, true)) { if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData); throw Error(kerNotAJpeg); } clearMetadata(); byte data[12]; DataBuf chunkId(5); chunkId.pData_[4] = '\0' ; readOrThrow(*io_, data, WEBP_TAG_SIZE * 3, Exiv2::kerCorruptedMetadata); const uint32_t filesize_u32 = Safe::add(Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian), 8U); enforce(filesize_u32 <= io_->size(), Exiv2::kerCorruptedMetadata); // Check that `filesize_u32` is safe to cast to `long`. enforce(filesize_u32 <= static_cast<size_t>(std::numeric_limits<long>::max()), Exiv2::kerCorruptedMetadata); WebPImage::decodeChunks(static_cast<long>(filesize_u32)); } // WebPImage::readMetadata void WebPImage::decodeChunks(long filesize) { DataBuf chunkId(5); byte size_buff[WEBP_TAG_SIZE]; bool has_canvas_data = false; #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Reading metadata" << std::endl; #endif chunkId.pData_[4] = '\0' ; while (!io_->eof() && io_->tell() < filesize) { readOrThrow(*io_, chunkId.pData_, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata); readOrThrow(*io_, size_buff, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata); const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian); // Check that `size_u32` is safe to cast to `long`. enforce(size_u32 <= static_cast<size_t>(std::numeric_limits<long>::max()), Exiv2::kerCorruptedMetadata); const long size = static_cast<long>(size_u32); // Check that `size` is within bounds. enforce(io_->tell() <= filesize, Exiv2::kerCorruptedMetadata); enforce(size <= (filesize - io_->tell()), Exiv2::kerCorruptedMetadata); DataBuf payload(size); if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_canvas_data) { enforce(size >= 10, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf[WEBP_TAG_SIZE]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf, &payload.pData_[4], 3); size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height memcpy(&size_buf, &payload.pData_[7], 3); size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_canvas_data) { enforce(size >= 10, Exiv2::kerCorruptedMetadata); has_canvas_data = true; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); byte size_buf[WEBP_TAG_SIZE]; // Fetch width"" memcpy(&size_buf, &payload.pData_[6], 2); size_buf[2] = 0; size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff; // Fetch height memcpy(&size_buf, &payload.pData_[8], 2); size_buf[2] = 0; size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_canvas_data) { enforce(size >= 5, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf_w[2]; byte size_buf_h[3]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf_w, &payload.pData_[1], 2); size_buf_w[1] &= 0x3F; pixelWidth_ = Exiv2::getUShort(size_buf_w, littleEndian) + 1; // Fetch height memcpy(&size_buf_h, &payload.pData_[2], 3); size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2); size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2); pixelHeight_ = Exiv2::getUShort(size_buf_h, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_canvas_data) { enforce(size >= 12, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf[WEBP_TAG_SIZE]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf, &payload.pData_[6], 3); size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height memcpy(&size_buf, &payload.pData_[9], 3); size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); this->setIccProfile(payload); } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); byte size_buff[2]; // 4 meaningful bytes + 2 padding bytes byte exifLongHeader[] = { 0xFF, 0x01, 0xFF, 0xE1, 0x00, 0x00 }; byte exifShortHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 }; byte exifTiffLEHeader[] = { 0x49, 0x49, 0x2A }; // "MM*" byte exifTiffBEHeader[] = { 0x4D, 0x4D, 0x00, 0x2A }; // "II\0*" byte* rawExifData = NULL; long offset = 0; bool s_header = false; bool le_header = false; bool be_header = false; long pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 4); if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 6); if (pos != -1) { s_header = true; } } if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffLEHeader, 3); if (pos != -1) { le_header = true; } } if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffBEHeader, 4); if (pos != -1) { be_header = true; } } if (s_header) { offset += 6; } if (be_header || le_header) { offset += 12; } const long size = payload.size_ + offset; rawExifData = (byte*)malloc(size); if (s_header) { us2Data(size_buff, (uint16_t) (size - 6), bigEndian); memcpy(rawExifData, (char*)&exifLongHeader, 4); memcpy(rawExifData + 4, (char*)&size_buff, 2); } if (be_header || le_header) { us2Data(size_buff, (uint16_t) (size - 6), bigEndian); memcpy(rawExifData, (char*)&exifLongHeader, 4); memcpy(rawExifData + 4, (char*)&size_buff, 2); memcpy(rawExifData + 6, (char*)&exifShortHeader, 6); } memcpy(rawExifData + offset, payload.pData_, payload.size_); #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Display Hex Dump [size:" << (unsigned long)size << "]" << std::endl; std::cout << Internal::binaryToHex(rawExifData, size); #endif if (pos != -1) { XmpData xmpData; ByteOrder bo = ExifParser::decode(exifData_, payload.pData_ + pos, payload.size_ - pos); setByteOrder(bo); } else { #ifndef SUPPRESS_WARNINGS EXV_WARNING << "Failed to decode Exif metadata." << std::endl; #endif exifData_.clear(); } if (rawExifData) free(rawExifData); } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); xmpPacket_.assign(reinterpret_cast<char*>(payload.pData_), payload.size_); if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << "Failed to decode XMP metadata." << std::endl; #endif } else { #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Display Hex Dump [size:" << (unsigned long)payload.size_ << "]" << std::endl; std::cout << Internal::binaryToHex(payload.pData_, payload.size_); #endif } } else { io_->seek(size, BasicIo::cur); } if ( io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); } } /* =========================================== */ Image::AutoPtr newWebPInstance(BasicIo::AutoPtr io, bool /*create*/) { Image::AutoPtr image(new WebPImage(io)); if (!image->good()) { image.reset(); } return image; } bool isWebPType(BasicIo& iIo, bool /*advance*/) { if (iIo.size() < 12) { return false; } const int32_t len = 4; const unsigned char RiffImageId[4] = { 'R', 'I', 'F' ,'F'}; const unsigned char WebPImageId[4] = { 'W', 'E', 'B' ,'P'}; byte webp[len]; byte data[len]; byte riff[len]; iIo.read(riff, len); iIo.read(data, len); iIo.read(webp, len); bool matched_riff = (memcmp(riff, RiffImageId, len) == 0); bool matched_webp = (memcmp(webp, WebPImageId, len) == 0); iIo.seek(-12, BasicIo::cur); return matched_riff && matched_webp; } /*! @brief Function used to check equality of a Tags with a particular string (ignores case while comparing). @param buf Data buffer that will contain Tag to compare @param str char* Pointer to string @return Returns true if the buffer value is equal to string. */ bool WebPImage::equalsWebPTag(Exiv2::DataBuf& buf, const char* str) { for(int i = 0; i < 4; i++ ) if(toupper(buf.pData_[i]) != str[i]) return false; return true; } /*! @brief Function used to add missing EXIF & XMP flags to the feature section. @param iIo get BasicIo pointer to inject data @param has_xmp Verify if we have xmp data and set required flag @param has_exif Verify if we have exif data and set required flag @return Returns void */ void WebPImage::inject_VP8X(BasicIo& iIo, bool has_xmp, bool has_exif, bool has_alpha, bool has_icc, int width, int height) { byte size[4] = { 0x0A, 0x00, 0x00, 0x00 }; byte data[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE); iIo.write(size, WEBP_TAG_SIZE); if (has_alpha) { data[0] |= WEBP_VP8X_ALPHA_BIT; } if (has_icc) { data[0] |= WEBP_VP8X_ICC_BIT; } if (has_xmp) { data[0] |= WEBP_VP8X_XMP_BIT; } if (has_exif) { data[0] |= WEBP_VP8X_EXIF_BIT; } /* set width - stored in 24bits*/ int w = width - 1; data[4] = w & 0xFF; data[5] = (w >> 8) & 0xFF; data[6] = (w >> 16) & 0xFF; /* set height - stored in 24bits */ int h = height - 1; data[7] = h & 0xFF; data[8] = (h >> 8) & 0xFF; data[9] = (h >> 16) & 0xFF; iIo.write(data, 10); /* Handle inject an icc profile right after VP8X chunk */ if (has_icc) { byte size_buff[WEBP_TAG_SIZE]; ul2Data(size_buff, iccProfile_.size_, littleEndian); if (iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (iIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (iIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) throw Error(kerImageWriteFailed); if (iIo.tell() % 2) { if (iIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } has_icc = false; } } long WebPImage::getHeaderOffset(byte *data, long data_size, byte *header, long header_size) { long pos = -1; for (long i=0; i < data_size - header_size; i++) { if (memcmp(header, &data[i], header_size) == 0) { pos = i; break; } } return pos; } } // namespace Exiv2
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_1010_0
crossvul-cpp_data_good_3872_0
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1999-2016, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** * * File unistr.cpp * * Modification History: * * Date Name Description * 09/25/98 stephen Creation. * 04/20/99 stephen Overhauled per 4/16 code review. * 07/09/99 stephen Renamed {hi,lo},{byte,word} to icu_X for HP/UX * 11/18/99 aliu Added handleReplaceBetween() to make inherit from * Replaceable. * 06/25/01 grhoten Removed the dependency on iostream ****************************************************************************** */ #include "unicode/utypes.h" #include "unicode/appendable.h" #include "unicode/putil.h" #include "cstring.h" #include "cmemory.h" #include "unicode/ustring.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "unicode/utf16.h" #include "uelement.h" #include "ustr_imp.h" #include "umutex.h" #include "uassert.h" #if 0 #include <iostream> using namespace std; //DEBUGGING void print(const UnicodeString& s, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < s.length(); ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } void print(const UChar *s, int32_t len, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < len; ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } // END DEBUGGING #endif // Local function definitions for now // need to copy areas that may overlap static inline void us_arrayCopy(const UChar *src, int32_t srcStart, UChar *dst, int32_t dstStart, int32_t count) { if(count>0) { uprv_memmove(dst+dstStart, src+srcStart, (size_t)count*sizeof(*src)); } } // u_unescapeAt() callback to get a UChar from a UnicodeString U_CDECL_BEGIN static UChar U_CALLCONV UnicodeString_charAt(int32_t offset, void *context) { return ((icu::UnicodeString*) context)->charAt(offset); } U_CDECL_END U_NAMESPACE_BEGIN /* The Replaceable virtual destructor can't be defined in the header due to how AIX works with multiple definitions of virtual functions. */ Replaceable::~Replaceable() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString) UnicodeString U_EXPORT2 operator+ (const UnicodeString &s1, const UnicodeString &s2) { return UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0). append(s1). append(s2); } //======================================== // Reference Counting functions, put at top of file so that optimizing compilers // have a chance to automatically inline. //======================================== void UnicodeString::addRef() { umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::removeRef() { return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::refCount() const { return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1)); } void UnicodeString::releaseArray() { if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) { uprv_free((int32_t *)fUnion.fFields.fArray - 1); } } //======================================== // Constructors //======================================== // The default constructor is inline in unistr.h. UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { fUnion.fFields.fLengthAndFlags = 0; if(count <= 0 || (uint32_t)c > 0x10ffff) { // just allocate and do not do anything else allocate(capacity); } else if(c <= 0xffff) { int32_t length = count; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar unit = (UChar)c; for(int32_t i = 0; i < length; ++i) { array[i] = unit; } setLength(length); } } else { // supplementary code point, write surrogate pairs if(count > (INT32_MAX / 2)) { // We would get more than 2G UChars. allocate(capacity); return; } int32_t length = count * 2; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar lead = U16_LEAD(c); UChar trail = U16_TRAIL(c); for(int32_t i = 0; i < length; i += 2) { array[i] = lead; array[i + 1] = trail; } setLength(length); } } } UnicodeString::UnicodeString(UChar ch) { fUnion.fFields.fLengthAndFlags = kLength1 | kShortString; fUnion.fStackFields.fBuffer[0] = ch; } UnicodeString::UnicodeString(UChar32 ch) { fUnion.fFields.fLengthAndFlags = kShortString; int32_t i = 0; UBool isError = FALSE; U16_APPEND(fUnion.fStackFields.fBuffer, i, US_STACKBUF_SIZE, ch, isError); // We test isError so that the compiler does not complain that we don't. // If isError then i==0 which is what we want anyway. if(!isError) { setShortLength(i); } } UnicodeString::UnicodeString(const UChar *text) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, -1); } UnicodeString::UnicodeString(const UChar *text, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, textLength); } UnicodeString::UnicodeString(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kReadonlyAlias; const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); } else { if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } setArray(const_cast<UChar *>(text), textLength, isTerminated ? textLength + 1 : textLength); } } UnicodeString::UnicodeString(UChar *buff, int32_t buffLength, int32_t buffCapacity) { fUnion.fFields.fLengthAndFlags = kWritableAlias; if(buff == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); } else { if(buffLength == -1) { // fLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buff, *limit = buff + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buff); } setArray(buff, buffLength, buffCapacity); } } UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) { fUnion.fFields.fLengthAndFlags = kShortString; if(src==NULL) { // treat as an empty string } else { if(length<0) { length=(int32_t)uprv_strlen(src); } if(cloneArrayIfNeeded(length, length, FALSE)) { u_charsToUChars(src, getArrayStart(), length); setLength(length); } else { setToBogus(); } } } #if U_CHARSET_IS_UTF8 UnicodeString::UnicodeString(const char *codepageData) { fUnion.fFields.fLengthAndFlags = kShortString; if(codepageData != 0) { setToUTF8(codepageData); } } UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) { fUnion.fFields.fLengthAndFlags = kShortString; // if there's nothing to convert, do nothing if(codepageData == 0 || dataLength == 0 || dataLength < -1) { return; } if(dataLength == -1) { dataLength = (int32_t)uprv_strlen(codepageData); } setToUTF8(StringPiece(codepageData, dataLength)); } // else see unistr_cnv.cpp #endif UnicodeString::UnicodeString(const UnicodeString& that) { fUnion.fFields.fLengthAndFlags = kShortString; copyFrom(that); } UnicodeString::UnicodeString(UnicodeString &&src) U_NOEXCEPT { copyFieldsFrom(src, TRUE); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart, int32_t srcLength) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart, srcLength); } // Replaceable base class clone() default implementation, does not clone Replaceable * Replaceable::clone() const { return NULL; } // UnicodeString overrides clone() with a real implementation UnicodeString * UnicodeString::clone() const { return new UnicodeString(*this); } //======================================== // array allocation //======================================== namespace { const int32_t kGrowSize = 128; // The number of bytes for one int32_t reference counter and capacity UChars // must fit into a 32-bit size_t (at least when on a 32-bit platform). // We also add one for the NUL terminator, to avoid reallocation in getTerminatedBuffer(), // and round up to a multiple of 16 bytes. // This means that capacity must be at most (0xfffffff0 - 4) / 2 - 1 = 0x7ffffff5. // (With more complicated checks we could go up to 0x7ffffffd without rounding up, // but that does not seem worth it.) const int32_t kMaxCapacity = 0x7ffffff5; int32_t getGrowCapacity(int32_t newLength) { int32_t growSize = (newLength >> 2) + kGrowSize; if(growSize <= (kMaxCapacity - newLength)) { return newLength + growSize; } else { return kMaxCapacity; } } } // namespace UBool UnicodeString::allocate(int32_t capacity) { if(capacity <= US_STACKBUF_SIZE) { fUnion.fFields.fLengthAndFlags = kShortString; return TRUE; } if(capacity <= kMaxCapacity) { ++capacity; // for the NUL // Switch to size_t which is unsigned so that we can allocate up to 4GB. // Reference counter + UChars. size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR; // Round up to a multiple of 16. numBytes = (numBytes + 15) & ~15; int32_t *array = (int32_t *) uprv_malloc(numBytes); if(array != NULL) { // set initial refCount and point behind the refCount *array++ = 1; numBytes -= sizeof(int32_t); // have fArray point to the first UChar fUnion.fFields.fArray = (UChar *)array; fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR); fUnion.fFields.fLengthAndFlags = kLongString; return TRUE; } } fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; return FALSE; } //======================================== // Destructor //======================================== #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS static u_atomic_int32_t finalLengthCounts[0x400]; // UnicodeString::kMaxShortLength+1 static u_atomic_int32_t beyondCount(0); U_CAPI void unistr_printLengths() { int32_t i; for(i = 0; i <= 59; ++i) { printf("%2d, %9d\n", i, (int32_t)finalLengthCounts[i]); } int32_t beyond = beyondCount; for(; i < UPRV_LENGTHOF(finalLengthCounts); ++i) { beyond += finalLengthCounts[i]; } printf(">59, %9d\n", beyond); } #endif UnicodeString::~UnicodeString() { #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS // Count lengths of strings at the end of their lifetime. // Useful for discussion of a desirable stack buffer size. // Count the contents length, not the optional NUL terminator nor further capacity. // Ignore open-buffer strings and strings which alias external storage. if((fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kReadonlyAlias|kWritableAlias)) == 0) { if(hasShortLength()) { umtx_atomic_inc(finalLengthCounts + getShortLength()); } else { umtx_atomic_inc(&beyondCount); } } #endif releaseArray(); } //======================================== // Factory methods //======================================== UnicodeString UnicodeString::fromUTF8(StringPiece utf8) { UnicodeString result; result.setToUTF8(utf8); return result; } UnicodeString UnicodeString::fromUTF32(const UChar32 *utf32, int32_t length) { UnicodeString result; int32_t capacity; // Most UTF-32 strings will be BMP-only and result in a same-length // UTF-16 string. We overestimate the capacity just slightly, // just in case there are a few supplementary characters. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + (length >> 4) + 4; } do { UChar *utf16 = result.getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF32WithSub(utf16, result.getCapacity(), &length16, utf32, length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); result.releaseBuffer(length16); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { capacity = length16 + 1; // +1 for the terminating NUL. continue; } else if(U_FAILURE(errorCode)) { result.setToBogus(); } break; } while(TRUE); return result; } //======================================== // Assignment //======================================== UnicodeString & UnicodeString::operator=(const UnicodeString &src) { return copyFrom(src); } UnicodeString & UnicodeString::fastCopyFrom(const UnicodeString &src) { return copyFrom(src, TRUE); } UnicodeString & UnicodeString::copyFrom(const UnicodeString &src, UBool fastCopy) { // if assigning to ourselves, do nothing if(this == &src) { return *this; } // is the right side bogus? if(src.isBogus()) { setToBogus(); return *this; } // delete the current contents releaseArray(); if(src.isEmpty()) { // empty string - use the stack buffer setToEmpty(); return *this; } // fLength>0 and not an "open" src.getBuffer(minCapacity) fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; switch(src.fUnion.fFields.fLengthAndFlags & kAllStorageFlags) { case kShortString: // short string using the stack buffer, do the same uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); break; case kLongString: // src uses a refCounted string buffer, use that buffer with refCount // src is const, use a cast - we don't actually change it ((UnicodeString &)src).addRef(); // copy all fields, share the reference-counted buffer fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; case kReadonlyAlias: if(fastCopy) { // src is a readonly alias, do the same // -> maintain the readonly alias as such fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; } // else if(!fastCopy) fall through to case kWritableAlias // -> allocate a new buffer and copy the contents U_FALLTHROUGH; case kWritableAlias: { // src is a writable alias; we make a copy of that instead int32_t srcLength = src.length(); if(allocate(srcLength)) { u_memcpy(getArrayStart(), src.getArrayStart(), srcLength); setLength(srcLength); break; } // if there is not enough memory, then fall through to setting to bogus U_FALLTHROUGH; } default: // if src is bogus, set ourselves to bogus // do not call setToBogus() here because fArray and flags are not consistent here fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; break; } return *this; } UnicodeString &UnicodeString::operator=(UnicodeString &&src) U_NOEXCEPT { // No explicit check for self move assignment, consistent with standard library. // Self move assignment causes no crash nor leak but might make the object bogus. releaseArray(); copyFieldsFrom(src, TRUE); return *this; } // Same as move assignment except without memory management. void UnicodeString::copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) U_NOEXCEPT { int16_t lengthAndFlags = fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; if(lengthAndFlags & kUsingStackBuffer) { // Short string using the stack buffer, copy the contents. // Check for self assignment to prevent "overlap in memcpy" warnings, // although it should be harmless to copy a buffer to itself exactly. if(this != &src) { uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); } } else { // In all other cases, copy all fields. fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } if(setSrcToBogus) { // Set src to bogus without releasing any memory. src.fUnion.fFields.fLengthAndFlags = kIsBogus; src.fUnion.fFields.fArray = NULL; src.fUnion.fFields.fCapacity = 0; } } } void UnicodeString::swap(UnicodeString &other) U_NOEXCEPT { UnicodeString temp; // Empty short string: Known not to need releaseArray(). // Copy fields without resetting source values in between. temp.copyFieldsFrom(*this, FALSE); this->copyFieldsFrom(other, FALSE); other.copyFieldsFrom(temp, FALSE); // Set temp to an empty string so that other's memory is not released twice. temp.fUnion.fFields.fLengthAndFlags = kShortString; } //======================================== // Miscellaneous operations //======================================== UnicodeString UnicodeString::unescape() const { UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity if (result.isBogus()) { return result; } const UChar *array = getBuffer(); int32_t len = length(); int32_t prev = 0; for (int32_t i=0;;) { if (i == len) { result.append(array, prev, len - prev); break; } if (array[i++] == 0x5C /*'\\'*/) { result.append(array, prev, (i - 1) - prev); UChar32 c = unescapeAt(i); // advances i if (c < 0) { result.remove(); // return empty string break; // invalid escape sequence } result.append(c); prev = i; } } return result; } UChar32 UnicodeString::unescapeAt(int32_t &offset) const { return u_unescapeAt(UnicodeString_charAt, &offset, length(), (void*)this); } //======================================== // Read-only implementation //======================================== UBool UnicodeString::doEquals(const UnicodeString &text, int32_t len) const { // Requires: this & text not bogus and have same lengths. // Byte-wise comparison works for equality regardless of endianness. return uprv_memcmp(getArrayStart(), text.getArrayStart(), len * U_SIZEOF_UCHAR) == 0; } int8_t UnicodeString::doCompare( int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { // treat const UChar *srcChars==NULL as an empty string return length == 0 ? 0 : 1; } // get the correct pointer const UChar *chars = getArrayStart(); chars += start; srcChars += srcStart; int32_t minLength; int8_t lengthResult; // get the srcLength if necessary if(srcLength < 0) { srcLength = u_strlen(srcChars + srcStart); } // are we comparing different lengths? if(length != srcLength) { if(length < srcLength) { minLength = length; lengthResult = -1; } else { minLength = srcLength; lengthResult = 1; } } else { minLength = length; lengthResult = 0; } /* * note that uprv_memcmp() returns an int but we return an int8_t; * we need to take care not to truncate the result - * one way to do this is to right-shift the value to * move the sign bit into the lower 8 bits and making sure that this * does not become 0 itself */ if(minLength > 0 && chars != srcChars) { int32_t result; # if U_IS_BIG_ENDIAN // big-endian: byte comparison works result = uprv_memcmp(chars, srcChars, minLength * sizeof(UChar)); if(result != 0) { return (int8_t)(result >> 15 | 1); } # else // little-endian: compare UChar units do { result = ((int32_t)*(chars++) - (int32_t)*(srcChars++)); if(result != 0) { return (int8_t)(result >> 15 | 1); } } while(--minLength > 0); # endif } return lengthResult; } /* String compare in code point order - doCompare() compares in code unit order. */ int8_t UnicodeString::doCompareCodePointOrder(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values // treat const UChar *srcChars==NULL as an empty string if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { srcStart = srcLength = 0; } int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=NULL)?(srcChars + srcStart):NULL, srcLength, FALSE, TRUE); /* translate the 32-bit result into an 8-bit one */ if(diff!=0) { return (int8_t)(diff >> 15 | 1); } else { return 0; } } int32_t UnicodeString::getLength() const { return length(); } UChar UnicodeString::getCharAt(int32_t offset) const { return charAt(offset); } UChar32 UnicodeString::getChar32At(int32_t offset) const { return char32At(offset); } UChar32 UnicodeString::char32At(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); UChar32 c; U16_GET(array, 0, offset, len, c); return c; } else { return kInvalidUChar; } } int32_t UnicodeString::getChar32Start(int32_t offset) const { if((uint32_t)offset < (uint32_t)length()) { const UChar *array = getArrayStart(); U16_SET_CP_START(array, 0, offset); return offset; } else { return 0; } } int32_t UnicodeString::getChar32Limit(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); U16_SET_CP_LIMIT(array, 0, offset, len); return offset; } else { return len; } } int32_t UnicodeString::countChar32(int32_t start, int32_t length) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_countChar32() checks for NULL return u_countChar32(getArrayStart()+start, length); } UBool UnicodeString::hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_strHasMoreChar32Than() checks for NULL return u_strHasMoreChar32Than(getArrayStart()+start, length, number); } int32_t UnicodeString::moveIndex32(int32_t index, int32_t delta) const { // pin index int32_t len = length(); if(index<0) { index=0; } else if(index>len) { index=len; } const UChar *array = getArrayStart(); if(delta>0) { U16_FWD_N(array, index, len, delta); } else { U16_BACK_N(array, 0, index, -delta); } return index; } void UnicodeString::doExtract(int32_t start, int32_t length, UChar *dst, int32_t dstStart) const { // pin indices to legal values pinIndices(start, length); // do not copy anything if we alias dst itself const UChar *array = getArrayStart(); if(array + start != dst + dstStart) { us_arrayCopy(array, start, dst, dstStart, length); } } int32_t UnicodeString::extract(Char16Ptr dest, int32_t destCapacity, UErrorCode &errorCode) const { int32_t len = length(); if(U_SUCCESS(errorCode)) { if(isBogus() || destCapacity<0 || (destCapacity>0 && dest==0)) { errorCode=U_ILLEGAL_ARGUMENT_ERROR; } else { const UChar *array = getArrayStart(); if(len>0 && len<=destCapacity && array!=dest) { u_memcpy(dest, array, len); } return u_terminateUChars(dest, destCapacity, len, &errorCode); } } return len; } int32_t UnicodeString::extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant) const { // if the arguments are illegal, then do nothing if(targetCapacity < 0 || (targetCapacity > 0 && target == NULL)) { return 0; } // pin the indices to legal values pinIndices(start, length); if(length <= targetCapacity) { u_UCharsToChars(getArrayStart() + start, target, length); } UErrorCode status = U_ZERO_ERROR; return u_terminateChars(target, targetCapacity, length, &status); } UnicodeString UnicodeString::tempSubString(int32_t start, int32_t len) const { pinIndices(start, len); const UChar *array = getBuffer(); // not getArrayStart() to check kIsBogus & kOpenGetBuffer if(array==NULL) { array=fUnion.fStackFields.fBuffer; // anything not NULL because that would make an empty string len=-2; // bogus result string } return UnicodeString(FALSE, array + start, len); } int32_t UnicodeString::toUTF8(int32_t start, int32_t len, char *target, int32_t capacity) const { pinIndices(start, len); int32_t length8; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(target, capacity, &length8, getBuffer() + start, len, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); return length8; } #if U_CHARSET_IS_UTF8 int32_t UnicodeString::extract(int32_t start, int32_t len, char *target, uint32_t dstSize) const { // if the arguments are illegal, then do nothing if(/*dstSize < 0 || */(dstSize > 0 && target == 0)) { return 0; } return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff); } // else see unistr_cnv.cpp #endif void UnicodeString::extractBetween(int32_t start, int32_t limit, UnicodeString& target) const { pinIndex(start); pinIndex(limit); doExtract(start, limit - start, target); } // When converting from UTF-16 to UTF-8, the result will have at most 3 times // as many bytes as the source has UChars. // The "worst cases" are writing systems like Indic, Thai and CJK with // 3:1 bytes:UChars. void UnicodeString::toUTF8(ByteSink &sink) const { int32_t length16 = length(); if(length16 != 0) { char stackBuffer[1024]; int32_t capacity = (int32_t)sizeof(stackBuffer); UBool utf8IsOwned = FALSE; char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity, 3*length16, stackBuffer, capacity, &capacity); int32_t length8 = 0; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, capacity, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { utf8 = (char *)uprv_malloc(length8); if(utf8 != NULL) { utf8IsOwned = TRUE; errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, length8, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); } else { errorCode = U_MEMORY_ALLOCATION_ERROR; } } if(U_SUCCESS(errorCode)) { sink.Append(utf8, length8); sink.Flush(); } if(utf8IsOwned) { uprv_free(utf8); } } } int32_t UnicodeString::toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const { int32_t length32=0; if(U_SUCCESS(errorCode)) { // getBuffer() and u_strToUTF32WithSub() check for illegal arguments. u_strToUTF32WithSub(utf32, capacity, &length32, getBuffer(), length(), 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); } return length32; } int32_t UnicodeString::indexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the first occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindFirst(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::lastIndexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the last occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindLast(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar c, int32_t start, int32_t length) const { if(isBogus()) { return -1; } // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } //======================================== // Write implementation //======================================== UnicodeString& UnicodeString::findAndReplace(int32_t start, int32_t length, const UnicodeString& oldText, int32_t oldStart, int32_t oldLength, const UnicodeString& newText, int32_t newStart, int32_t newLength) { if(isBogus() || oldText.isBogus() || newText.isBogus()) { return *this; } pinIndices(start, length); oldText.pinIndices(oldStart, oldLength); newText.pinIndices(newStart, newLength); if(oldLength == 0) { return *this; } while(length > 0 && length >= oldLength) { int32_t pos = indexOf(oldText, oldStart, oldLength, start, length); if(pos < 0) { // no more oldText's here: done break; } else { // we found oldText, replace it by newText and go beyond it replace(pos, oldLength, newText, newStart, newLength); length -= pos + oldLength - start; start = pos + newLength; } } return *this; } void UnicodeString::setToBogus() { releaseArray(); fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; } // turn a bogus string into an empty one void UnicodeString::unBogus() { if(fUnion.fFields.fLengthAndFlags & kIsBogus) { setToEmpty(); } } const char16_t * UnicodeString::getTerminatedBuffer() { if(!isWritable()) { return nullptr; } UChar *array = getArrayStart(); int32_t len = length(); if(len < getCapacity()) { if(fUnion.fFields.fLengthAndFlags & kBufferIsReadonly) { // If len<capacity on a read-only alias, then array[len] is // either the original NUL (if constructed with (TRUE, s, length)) // or one of the original string contents characters (if later truncated), // therefore we can assume that array[len] is initialized memory. if(array[len] == 0) { return array; } } else if(((fUnion.fFields.fLengthAndFlags & kRefCounted) == 0 || refCount() == 1)) { // kRefCounted: Do not write the NUL if the buffer is shared. // That is mostly safe, except when the length of one copy was modified // without copy-on-write, e.g., via truncate(newLength) or remove(void). // Then the NUL would be written into the middle of another copy's string. // Otherwise, the buffer is fully writable and it is anyway safe to write the NUL. // Do not test if there is a NUL already because it might be uninitialized memory. // (That would be safe, but tools like valgrind & Purify would complain.) array[len] = 0; return array; } } if(len<INT32_MAX && cloneArrayIfNeeded(len+1)) { array = getArrayStart(); array[len] = 0; return array; } else { return nullptr; } } // setTo() analogous to the readonly-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if( textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); return *this; } releaseArray(); if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } fUnion.fFields.fLengthAndFlags = kReadonlyAlias; setArray((UChar *)text, textLength, isTerminated ? textLength + 1 : textLength); return *this; } // setTo() analogous to the writable-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UChar *buffer, int32_t buffLength, int32_t buffCapacity) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } if(buffer == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); return *this; } else if(buffLength == -1) { // buffLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buffer, *limit = buffer + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buffer); } releaseArray(); fUnion.fFields.fLengthAndFlags = kWritableAlias; setArray(buffer, buffLength, buffCapacity); return *this; } UnicodeString &UnicodeString::setToUTF8(StringPiece utf8) { unBogus(); int32_t length = utf8.length(); int32_t capacity; // The UTF-16 string will be at most as long as the UTF-8 string. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + 1; // +1 for the terminating NUL. } UChar *utf16 = getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF8WithSub(utf16, getCapacity(), &length16, utf8.data(), length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); releaseBuffer(length16); if(U_FAILURE(errorCode)) { setToBogus(); } return *this; } UnicodeString& UnicodeString::setCharAt(int32_t offset, UChar c) { int32_t len = length(); if(cloneArrayIfNeeded() && len > 0) { if(offset < 0) { offset = 0; } else if(offset >= len) { offset = len - 1; } getArrayStart()[offset] = c; } return *this; } UnicodeString& UnicodeString::replace(int32_t start, int32_t _length, UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t count = 0; UBool isError = FALSE; U16_APPEND(buffer, count, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError (srcChar is not a valid code point) then count==0 which means // we remove the source segment rather than replacing it with srcChar. return doReplace(start, _length, buffer, 0, isError ? 0 : count); } UnicodeString& UnicodeString::append(UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t _length = 0; UBool isError = FALSE; U16_APPEND(buffer, _length, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError then _length==0 which turns the doAppend() into a no-op anyway. return isError ? *this : doAppend(buffer, 0, _length); } UnicodeString& UnicodeString::doReplace( int32_t start, int32_t length, const UnicodeString& src, int32_t srcStart, int32_t srcLength) { // pin the indices to legal values src.pinIndices(srcStart, srcLength); // get the characters from src // and replace the range in ourselves with them return doReplace(start, length, src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doReplace(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable()) { return *this; } int32_t oldLength = this->length(); // optimize (read-only alias).remove(0, start) and .remove(start, end) if((fUnion.fFields.fLengthAndFlags&kBufferIsReadonly) && srcLength == 0) { if(start == 0) { // remove prefix by adjusting the array pointer pinIndex(length); fUnion.fFields.fArray += length; fUnion.fFields.fCapacity -= length; setLength(oldLength - length); return *this; } else { pinIndex(start); if(length >= (oldLength - start)) { // remove suffix by reducing the length (like truncate()) setLength(start); fUnion.fFields.fCapacity = start; // not NUL-terminated any more return *this; } } } if(start == oldLength) { return doAppend(srcChars, srcStart, srcLength); } if(srcChars == 0) { srcLength = 0; } else { // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if (srcLength < 0) { // get the srcLength if necessary srcLength = u_strlen(srcChars); } } // pin the indices to legal values pinIndices(start, length); // Calculate the size of the string after the replace. // Avoid int32_t overflow. int32_t newLength = oldLength - length; if(srcLength > (INT32_MAX - newLength)) { setToBogus(); return *this; } newLength += srcLength; // Check for insertion into ourself const UChar *oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doReplace(start, length, copy.getArrayStart(), 0, srcLength); } // cloneArrayIfNeeded(doCopyArray=FALSE) may change fArray but will not copy the current contents; // therefore we need to keep the current fArray UChar oldStackBuffer[US_STACKBUF_SIZE]; if((fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) && (newLength > US_STACKBUF_SIZE)) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values u_memcpy(oldStackBuffer, oldArray, oldLength); oldArray = oldStackBuffer; } // clone our array and allocate a bigger array if needed int32_t *bufferToDelete = 0; if(!cloneArrayIfNeeded(newLength, getGrowCapacity(newLength), FALSE, &bufferToDelete) ) { return *this; } // now do the replace UChar *newArray = getArrayStart(); if(newArray != oldArray) { // if fArray changed, then we need to copy everything except what will change us_arrayCopy(oldArray, 0, newArray, 0, start); us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } else if(length != srcLength) { // fArray did not change; copy only the portion that isn't changing, leaving a hole us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } // now fill in the hole with the new string us_arrayCopy(srcChars, 0, newArray, start, srcLength); setLength(newLength); // delayed delete in case srcChars == fArray when we started, and // to keep oldArray alive for the above operations if (bufferToDelete) { uprv_free(bufferToDelete); } return *this; } // Versions of doReplace() only for append() variants. // doReplace() and doAppend() optimize for different cases. UnicodeString& UnicodeString::doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength) { if(srcLength == 0) { return *this; } // pin the indices to legal values src.pinIndices(srcStart, srcLength); return doAppend(src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength; if (uprv_add32_overflow(oldLength, srcLength, &newLength)) { setToBogus(); return *this; } // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; } /** * Replaceable API */ void UnicodeString::handleReplaceBetween(int32_t start, int32_t limit, const UnicodeString& text) { replaceBetween(start, limit, text); } /** * Replaceable API */ void UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) { if (limit <= start) { return; // Nothing to do; avoid bogus malloc call } UChar* text = (UChar*) uprv_malloc( sizeof(UChar) * (limit - start) ); // Check to make sure text is not null. if (text != NULL) { extractBetween(start, limit, text, 0); insert(dest, text, 0, limit - start); uprv_free(text); } } /** * Replaceable API * * NOTE: This is for the Replaceable class. There is no rep.cpp, * so we implement this function here. */ UBool Replaceable::hasMetaData() const { return TRUE; } /** * Replaceable API */ UBool UnicodeString::hasMetaData() const { return FALSE; } UnicodeString& UnicodeString::doReverse(int32_t start, int32_t length) { if(length <= 1 || !cloneArrayIfNeeded()) { return *this; } // pin the indices to legal values pinIndices(start, length); if(length <= 1) { // pinIndices() might have shrunk the length return *this; } UChar *left = getArrayStart() + start; UChar *right = left + length - 1; // -1 for inclusive boundary (length>=2) UChar swap; UBool hasSupplementary = FALSE; // Before the loop we know left<right because length>=2. do { hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left); hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right); *right-- = swap; } while(left < right); // Make sure to test the middle code unit of an odd-length string. // Redundant if the length is even. hasSupplementary |= (UBool)U16_IS_LEAD(*left); /* if there are supplementary code points in the reversed range, then re-swap their surrogates */ if(hasSupplementary) { UChar swap2; left = getArrayStart() + start; right = left + length - 1; // -1 so that we can look at *(left+1) if left<right while(left < right) { if(U16_IS_TRAIL(swap = *left) && U16_IS_LEAD(swap2 = *(left + 1))) { *left++ = swap2; *left++ = swap; } else { ++left; } } } return *this; } UBool UnicodeString::padLeading(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // move contents up by padding width UChar *array = getArrayStart(); int32_t start = targetLength - oldLength; us_arrayCopy(array, 0, array, start, oldLength); // fill in padding character while(--start >= 0) { array[start] = padChar; } setLength(targetLength); return TRUE; } } UBool UnicodeString::padTrailing(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // fill in padding character UChar *array = getArrayStart(); int32_t length = targetLength; while(--length >= oldLength) { array[length] = padChar; } setLength(targetLength); return TRUE; } } //======================================== // Hashing //======================================== int32_t UnicodeString::doHashCode() const { /* Delegate hash computation to uhash. This makes UnicodeString * hashing consistent with UChar* hashing. */ int32_t hashCode = ustr_hashUCharsN(getArrayStart(), length()); if (hashCode == kInvalidHashCode) { hashCode = kEmptyHashCode; } return hashCode; } //======================================== // External Buffer //======================================== char16_t * UnicodeString::getBuffer(int32_t minCapacity) { if(minCapacity>=-1 && cloneArrayIfNeeded(minCapacity)) { fUnion.fFields.fLengthAndFlags|=kOpenGetBuffer; setZeroLength(); return getArrayStart(); } else { return nullptr; } } void UnicodeString::releaseBuffer(int32_t newLength) { if(fUnion.fFields.fLengthAndFlags&kOpenGetBuffer && newLength>=-1) { // set the new fLength int32_t capacity=getCapacity(); if(newLength==-1) { // the new length is the string length, capped by fCapacity const UChar *array=getArrayStart(), *p=array, *limit=array+capacity; while(p<limit && *p!=0) { ++p; } newLength=(int32_t)(p-array); } else if(newLength>capacity) { newLength=capacity; } setLength(newLength); fUnion.fFields.fLengthAndFlags&=~kOpenGetBuffer; } } //======================================== // Miscellaneous //======================================== UBool UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, int32_t growCapacity, UBool doCopyArray, int32_t **pBufferToDelete, UBool forceClone) { // default parameters need to be static, therefore // the defaults are -1 to have convenience defaults if(newCapacity == -1) { newCapacity = getCapacity(); } // while a getBuffer(minCapacity) is "open", // prevent any modifications of the string by returning FALSE here // if the string is bogus, then only an assignment or similar can revive it if(!isWritable()) { return FALSE; } /* * We need to make a copy of the array if * the buffer is read-only, or * the buffer is refCounted (shared), and refCount>1, or * the buffer is too small. * Return FALSE if memory could not be allocated. */ if(forceClone || fUnion.fFields.fLengthAndFlags & kBufferIsReadonly || (fUnion.fFields.fLengthAndFlags & kRefCounted && refCount() > 1) || newCapacity > getCapacity() ) { // check growCapacity for default value and use of the stack buffer if(growCapacity < 0) { growCapacity = newCapacity; } else if(newCapacity <= US_STACKBUF_SIZE && growCapacity > US_STACKBUF_SIZE) { growCapacity = US_STACKBUF_SIZE; } // save old values UChar oldStackBuffer[US_STACKBUF_SIZE]; UChar *oldArray; int32_t oldLength = length(); int16_t flags = fUnion.fFields.fLengthAndFlags; if(flags&kUsingStackBuffer) { U_ASSERT(!(flags&kRefCounted)); /* kRefCounted and kUsingStackBuffer are mutally exclusive */ if(doCopyArray && growCapacity > US_STACKBUF_SIZE) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values us_arrayCopy(fUnion.fStackFields.fBuffer, 0, oldStackBuffer, 0, oldLength); oldArray = oldStackBuffer; } else { oldArray = NULL; // no need to copy from the stack buffer to itself } } else { oldArray = fUnion.fFields.fArray; U_ASSERT(oldArray!=NULL); /* when stack buffer is not used, oldArray must have a non-NULL reference */ } // allocate a new array if(allocate(growCapacity) || (newCapacity < growCapacity && allocate(newCapacity)) ) { if(doCopyArray) { // copy the contents // do not copy more than what fits - it may be smaller than before int32_t minLength = oldLength; newCapacity = getCapacity(); if(newCapacity < minLength) { minLength = newCapacity; } if(oldArray != NULL) { us_arrayCopy(oldArray, 0, getArrayStart(), 0, minLength); } setLength(minLength); } else { setZeroLength(); } // release the old array if(flags & kRefCounted) { // the array is refCounted; decrement and release if 0 u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1); if(umtx_atomic_dec(pRefCount) == 0) { if(pBufferToDelete == 0) { // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t // is defined as volatile. (Volatile has useful non-standard behavior // with this compiler.) uprv_free((void *)pRefCount); } else { // the caller requested to delete it himself *pBufferToDelete = (int32_t *)pRefCount; } } } } else { // not enough memory for growCapacity and not even for the smaller newCapacity // reset the old values for setToBogus() to release the array if(!(flags&kUsingStackBuffer)) { fUnion.fFields.fArray = oldArray; } fUnion.fFields.fLengthAndFlags = flags; setToBogus(); return FALSE; } } return TRUE; } // UnicodeStringAppendable ------------------------------------------------- *** UnicodeStringAppendable::~UnicodeStringAppendable() {} UBool UnicodeStringAppendable::appendCodeUnit(UChar c) { return str.doAppend(&c, 0, 1).isWritable(); } UBool UnicodeStringAppendable::appendCodePoint(UChar32 c) { UChar buffer[U16_MAX_LENGTH]; int32_t cLength = 0; UBool isError = FALSE; U16_APPEND(buffer, cLength, U16_MAX_LENGTH, c, isError); return !isError && str.doAppend(buffer, 0, cLength).isWritable(); } UBool UnicodeStringAppendable::appendString(const UChar *s, int32_t length) { return str.doAppend(s, 0, length).isWritable(); } UBool UnicodeStringAppendable::reserveAppendCapacity(int32_t appendCapacity) { return str.cloneArrayIfNeeded(str.length() + appendCapacity); } UChar * UnicodeStringAppendable::getAppendBuffer(int32_t minCapacity, int32_t desiredCapacityHint, UChar *scratch, int32_t scratchCapacity, int32_t *resultCapacity) { if(minCapacity < 1 || scratchCapacity < minCapacity) { *resultCapacity = 0; return NULL; } int32_t oldLength = str.length(); if(minCapacity <= (kMaxCapacity - oldLength) && desiredCapacityHint <= (kMaxCapacity - oldLength) && str.cloneArrayIfNeeded(oldLength + minCapacity, oldLength + desiredCapacityHint)) { *resultCapacity = str.getCapacity() - oldLength; return str.getArrayStart() + oldLength; } *resultCapacity = scratchCapacity; return scratch; } U_NAMESPACE_END U_NAMESPACE_USE U_CAPI int32_t U_EXPORT2 uhash_hashUnicodeString(const UElement key) { const UnicodeString *str = (const UnicodeString*) key.pointer; return (str == NULL) ? 0 : str->hashCode(); } // Moved here from uhash_us.cpp so that using a UVector of UnicodeString* // does not depend on hashtable code. U_CAPI UBool U_EXPORT2 uhash_compareUnicodeString(const UElement key1, const UElement key2) { const UnicodeString *str1 = (const UnicodeString*) key1.pointer; const UnicodeString *str2 = (const UnicodeString*) key2.pointer; if (str1 == str2) { return TRUE; } if (str1 == NULL || str2 == NULL) { return FALSE; } return *str1 == *str2; } #ifdef U_STATIC_IMPLEMENTATION /* This should never be called. It is defined here to make sure that the virtual vector deleting destructor is defined within unistr.cpp. The vector deleting destructor is already a part of UObject, but defining it here makes sure that it is included with this object file. This makes sure that static library dependencies are kept to a minimum. */ static void uprv_UnicodeStringDummy(void) { delete [] (new UnicodeString[2]); } #endif
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_3872_0
crossvul-cpp_data_bad_3872_0
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1999-2016, International Business Machines Corporation and * others. All Rights Reserved. ****************************************************************************** * * File unistr.cpp * * Modification History: * * Date Name Description * 09/25/98 stephen Creation. * 04/20/99 stephen Overhauled per 4/16 code review. * 07/09/99 stephen Renamed {hi,lo},{byte,word} to icu_X for HP/UX * 11/18/99 aliu Added handleReplaceBetween() to make inherit from * Replaceable. * 06/25/01 grhoten Removed the dependency on iostream ****************************************************************************** */ #include "unicode/utypes.h" #include "unicode/appendable.h" #include "unicode/putil.h" #include "cstring.h" #include "cmemory.h" #include "unicode/ustring.h" #include "unicode/unistr.h" #include "unicode/utf.h" #include "unicode/utf16.h" #include "uelement.h" #include "ustr_imp.h" #include "umutex.h" #include "uassert.h" #if 0 #include <iostream> using namespace std; //DEBUGGING void print(const UnicodeString& s, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < s.length(); ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } void print(const UChar *s, int32_t len, const char *name) { UChar c; cout << name << ":|"; for(int i = 0; i < len; ++i) { c = s[i]; if(c>= 0x007E || c < 0x0020) cout << "[0x" << hex << s[i] << "]"; else cout << (char) s[i]; } cout << '|' << endl; } // END DEBUGGING #endif // Local function definitions for now // need to copy areas that may overlap static inline void us_arrayCopy(const UChar *src, int32_t srcStart, UChar *dst, int32_t dstStart, int32_t count) { if(count>0) { uprv_memmove(dst+dstStart, src+srcStart, (size_t)count*sizeof(*src)); } } // u_unescapeAt() callback to get a UChar from a UnicodeString U_CDECL_BEGIN static UChar U_CALLCONV UnicodeString_charAt(int32_t offset, void *context) { return ((icu::UnicodeString*) context)->charAt(offset); } U_CDECL_END U_NAMESPACE_BEGIN /* The Replaceable virtual destructor can't be defined in the header due to how AIX works with multiple definitions of virtual functions. */ Replaceable::~Replaceable() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UnicodeString) UnicodeString U_EXPORT2 operator+ (const UnicodeString &s1, const UnicodeString &s2) { return UnicodeString(s1.length()+s2.length()+1, (UChar32)0, 0). append(s1). append(s2); } //======================================== // Reference Counting functions, put at top of file so that optimizing compilers // have a chance to automatically inline. //======================================== void UnicodeString::addRef() { umtx_atomic_inc((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::removeRef() { return umtx_atomic_dec((u_atomic_int32_t *)fUnion.fFields.fArray - 1); } int32_t UnicodeString::refCount() const { return umtx_loadAcquire(*((u_atomic_int32_t *)fUnion.fFields.fArray - 1)); } void UnicodeString::releaseArray() { if((fUnion.fFields.fLengthAndFlags & kRefCounted) && removeRef() == 0) { uprv_free((int32_t *)fUnion.fFields.fArray - 1); } } //======================================== // Constructors //======================================== // The default constructor is inline in unistr.h. UnicodeString::UnicodeString(int32_t capacity, UChar32 c, int32_t count) { fUnion.fFields.fLengthAndFlags = 0; if(count <= 0 || (uint32_t)c > 0x10ffff) { // just allocate and do not do anything else allocate(capacity); } else if(c <= 0xffff) { int32_t length = count; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar unit = (UChar)c; for(int32_t i = 0; i < length; ++i) { array[i] = unit; } setLength(length); } } else { // supplementary code point, write surrogate pairs if(count > (INT32_MAX / 2)) { // We would get more than 2G UChars. allocate(capacity); return; } int32_t length = count * 2; if(capacity < length) { capacity = length; } if(allocate(capacity)) { UChar *array = getArrayStart(); UChar lead = U16_LEAD(c); UChar trail = U16_TRAIL(c); for(int32_t i = 0; i < length; i += 2) { array[i] = lead; array[i + 1] = trail; } setLength(length); } } } UnicodeString::UnicodeString(UChar ch) { fUnion.fFields.fLengthAndFlags = kLength1 | kShortString; fUnion.fStackFields.fBuffer[0] = ch; } UnicodeString::UnicodeString(UChar32 ch) { fUnion.fFields.fLengthAndFlags = kShortString; int32_t i = 0; UBool isError = FALSE; U16_APPEND(fUnion.fStackFields.fBuffer, i, US_STACKBUF_SIZE, ch, isError); // We test isError so that the compiler does not complain that we don't. // If isError then i==0 which is what we want anyway. if(!isError) { setShortLength(i); } } UnicodeString::UnicodeString(const UChar *text) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, -1); } UnicodeString::UnicodeString(const UChar *text, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kShortString; doAppend(text, 0, textLength); } UnicodeString::UnicodeString(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { fUnion.fFields.fLengthAndFlags = kReadonlyAlias; const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); } else { if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } setArray(const_cast<UChar *>(text), textLength, isTerminated ? textLength + 1 : textLength); } } UnicodeString::UnicodeString(UChar *buff, int32_t buffLength, int32_t buffCapacity) { fUnion.fFields.fLengthAndFlags = kWritableAlias; if(buff == NULL) { // treat as an empty string, do not alias setToEmpty(); } else if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); } else { if(buffLength == -1) { // fLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buff, *limit = buff + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buff); } setArray(buff, buffLength, buffCapacity); } } UnicodeString::UnicodeString(const char *src, int32_t length, EInvariant) { fUnion.fFields.fLengthAndFlags = kShortString; if(src==NULL) { // treat as an empty string } else { if(length<0) { length=(int32_t)uprv_strlen(src); } if(cloneArrayIfNeeded(length, length, FALSE)) { u_charsToUChars(src, getArrayStart(), length); setLength(length); } else { setToBogus(); } } } #if U_CHARSET_IS_UTF8 UnicodeString::UnicodeString(const char *codepageData) { fUnion.fFields.fLengthAndFlags = kShortString; if(codepageData != 0) { setToUTF8(codepageData); } } UnicodeString::UnicodeString(const char *codepageData, int32_t dataLength) { fUnion.fFields.fLengthAndFlags = kShortString; // if there's nothing to convert, do nothing if(codepageData == 0 || dataLength == 0 || dataLength < -1) { return; } if(dataLength == -1) { dataLength = (int32_t)uprv_strlen(codepageData); } setToUTF8(StringPiece(codepageData, dataLength)); } // else see unistr_cnv.cpp #endif UnicodeString::UnicodeString(const UnicodeString& that) { fUnion.fFields.fLengthAndFlags = kShortString; copyFrom(that); } UnicodeString::UnicodeString(UnicodeString &&src) U_NOEXCEPT { copyFieldsFrom(src, TRUE); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart); } UnicodeString::UnicodeString(const UnicodeString& that, int32_t srcStart, int32_t srcLength) { fUnion.fFields.fLengthAndFlags = kShortString; setTo(that, srcStart, srcLength); } // Replaceable base class clone() default implementation, does not clone Replaceable * Replaceable::clone() const { return NULL; } // UnicodeString overrides clone() with a real implementation UnicodeString * UnicodeString::clone() const { return new UnicodeString(*this); } //======================================== // array allocation //======================================== namespace { const int32_t kGrowSize = 128; // The number of bytes for one int32_t reference counter and capacity UChars // must fit into a 32-bit size_t (at least when on a 32-bit platform). // We also add one for the NUL terminator, to avoid reallocation in getTerminatedBuffer(), // and round up to a multiple of 16 bytes. // This means that capacity must be at most (0xfffffff0 - 4) / 2 - 1 = 0x7ffffff5. // (With more complicated checks we could go up to 0x7ffffffd without rounding up, // but that does not seem worth it.) const int32_t kMaxCapacity = 0x7ffffff5; int32_t getGrowCapacity(int32_t newLength) { int32_t growSize = (newLength >> 2) + kGrowSize; if(growSize <= (kMaxCapacity - newLength)) { return newLength + growSize; } else { return kMaxCapacity; } } } // namespace UBool UnicodeString::allocate(int32_t capacity) { if(capacity <= US_STACKBUF_SIZE) { fUnion.fFields.fLengthAndFlags = kShortString; return TRUE; } if(capacity <= kMaxCapacity) { ++capacity; // for the NUL // Switch to size_t which is unsigned so that we can allocate up to 4GB. // Reference counter + UChars. size_t numBytes = sizeof(int32_t) + (size_t)capacity * U_SIZEOF_UCHAR; // Round up to a multiple of 16. numBytes = (numBytes + 15) & ~15; int32_t *array = (int32_t *) uprv_malloc(numBytes); if(array != NULL) { // set initial refCount and point behind the refCount *array++ = 1; numBytes -= sizeof(int32_t); // have fArray point to the first UChar fUnion.fFields.fArray = (UChar *)array; fUnion.fFields.fCapacity = (int32_t)(numBytes / U_SIZEOF_UCHAR); fUnion.fFields.fLengthAndFlags = kLongString; return TRUE; } } fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; return FALSE; } //======================================== // Destructor //======================================== #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS static u_atomic_int32_t finalLengthCounts[0x400]; // UnicodeString::kMaxShortLength+1 static u_atomic_int32_t beyondCount(0); U_CAPI void unistr_printLengths() { int32_t i; for(i = 0; i <= 59; ++i) { printf("%2d, %9d\n", i, (int32_t)finalLengthCounts[i]); } int32_t beyond = beyondCount; for(; i < UPRV_LENGTHOF(finalLengthCounts); ++i) { beyond += finalLengthCounts[i]; } printf(">59, %9d\n", beyond); } #endif UnicodeString::~UnicodeString() { #ifdef UNISTR_COUNT_FINAL_STRING_LENGTHS // Count lengths of strings at the end of their lifetime. // Useful for discussion of a desirable stack buffer size. // Count the contents length, not the optional NUL terminator nor further capacity. // Ignore open-buffer strings and strings which alias external storage. if((fUnion.fFields.fLengthAndFlags&(kOpenGetBuffer|kReadonlyAlias|kWritableAlias)) == 0) { if(hasShortLength()) { umtx_atomic_inc(finalLengthCounts + getShortLength()); } else { umtx_atomic_inc(&beyondCount); } } #endif releaseArray(); } //======================================== // Factory methods //======================================== UnicodeString UnicodeString::fromUTF8(StringPiece utf8) { UnicodeString result; result.setToUTF8(utf8); return result; } UnicodeString UnicodeString::fromUTF32(const UChar32 *utf32, int32_t length) { UnicodeString result; int32_t capacity; // Most UTF-32 strings will be BMP-only and result in a same-length // UTF-16 string. We overestimate the capacity just slightly, // just in case there are a few supplementary characters. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + (length >> 4) + 4; } do { UChar *utf16 = result.getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF32WithSub(utf16, result.getCapacity(), &length16, utf32, length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); result.releaseBuffer(length16); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { capacity = length16 + 1; // +1 for the terminating NUL. continue; } else if(U_FAILURE(errorCode)) { result.setToBogus(); } break; } while(TRUE); return result; } //======================================== // Assignment //======================================== UnicodeString & UnicodeString::operator=(const UnicodeString &src) { return copyFrom(src); } UnicodeString & UnicodeString::fastCopyFrom(const UnicodeString &src) { return copyFrom(src, TRUE); } UnicodeString & UnicodeString::copyFrom(const UnicodeString &src, UBool fastCopy) { // if assigning to ourselves, do nothing if(this == &src) { return *this; } // is the right side bogus? if(src.isBogus()) { setToBogus(); return *this; } // delete the current contents releaseArray(); if(src.isEmpty()) { // empty string - use the stack buffer setToEmpty(); return *this; } // fLength>0 and not an "open" src.getBuffer(minCapacity) fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; switch(src.fUnion.fFields.fLengthAndFlags & kAllStorageFlags) { case kShortString: // short string using the stack buffer, do the same uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); break; case kLongString: // src uses a refCounted string buffer, use that buffer with refCount // src is const, use a cast - we don't actually change it ((UnicodeString &)src).addRef(); // copy all fields, share the reference-counted buffer fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; case kReadonlyAlias: if(fastCopy) { // src is a readonly alias, do the same // -> maintain the readonly alias as such fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } break; } // else if(!fastCopy) fall through to case kWritableAlias // -> allocate a new buffer and copy the contents U_FALLTHROUGH; case kWritableAlias: { // src is a writable alias; we make a copy of that instead int32_t srcLength = src.length(); if(allocate(srcLength)) { u_memcpy(getArrayStart(), src.getArrayStart(), srcLength); setLength(srcLength); break; } // if there is not enough memory, then fall through to setting to bogus U_FALLTHROUGH; } default: // if src is bogus, set ourselves to bogus // do not call setToBogus() here because fArray and flags are not consistent here fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; break; } return *this; } UnicodeString &UnicodeString::operator=(UnicodeString &&src) U_NOEXCEPT { // No explicit check for self move assignment, consistent with standard library. // Self move assignment causes no crash nor leak but might make the object bogus. releaseArray(); copyFieldsFrom(src, TRUE); return *this; } // Same as move assignment except without memory management. void UnicodeString::copyFieldsFrom(UnicodeString &src, UBool setSrcToBogus) U_NOEXCEPT { int16_t lengthAndFlags = fUnion.fFields.fLengthAndFlags = src.fUnion.fFields.fLengthAndFlags; if(lengthAndFlags & kUsingStackBuffer) { // Short string using the stack buffer, copy the contents. // Check for self assignment to prevent "overlap in memcpy" warnings, // although it should be harmless to copy a buffer to itself exactly. if(this != &src) { uprv_memcpy(fUnion.fStackFields.fBuffer, src.fUnion.fStackFields.fBuffer, getShortLength() * U_SIZEOF_UCHAR); } } else { // In all other cases, copy all fields. fUnion.fFields.fArray = src.fUnion.fFields.fArray; fUnion.fFields.fCapacity = src.fUnion.fFields.fCapacity; if(!hasShortLength()) { fUnion.fFields.fLength = src.fUnion.fFields.fLength; } if(setSrcToBogus) { // Set src to bogus without releasing any memory. src.fUnion.fFields.fLengthAndFlags = kIsBogus; src.fUnion.fFields.fArray = NULL; src.fUnion.fFields.fCapacity = 0; } } } void UnicodeString::swap(UnicodeString &other) U_NOEXCEPT { UnicodeString temp; // Empty short string: Known not to need releaseArray(). // Copy fields without resetting source values in between. temp.copyFieldsFrom(*this, FALSE); this->copyFieldsFrom(other, FALSE); other.copyFieldsFrom(temp, FALSE); // Set temp to an empty string so that other's memory is not released twice. temp.fUnion.fFields.fLengthAndFlags = kShortString; } //======================================== // Miscellaneous operations //======================================== UnicodeString UnicodeString::unescape() const { UnicodeString result(length(), (UChar32)0, (int32_t)0); // construct with capacity if (result.isBogus()) { return result; } const UChar *array = getBuffer(); int32_t len = length(); int32_t prev = 0; for (int32_t i=0;;) { if (i == len) { result.append(array, prev, len - prev); break; } if (array[i++] == 0x5C /*'\\'*/) { result.append(array, prev, (i - 1) - prev); UChar32 c = unescapeAt(i); // advances i if (c < 0) { result.remove(); // return empty string break; // invalid escape sequence } result.append(c); prev = i; } } return result; } UChar32 UnicodeString::unescapeAt(int32_t &offset) const { return u_unescapeAt(UnicodeString_charAt, &offset, length(), (void*)this); } //======================================== // Read-only implementation //======================================== UBool UnicodeString::doEquals(const UnicodeString &text, int32_t len) const { // Requires: this & text not bogus and have same lengths. // Byte-wise comparison works for equality regardless of endianness. return uprv_memcmp(getArrayStart(), text.getArrayStart(), len * U_SIZEOF_UCHAR) == 0; } int8_t UnicodeString::doCompare( int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { // treat const UChar *srcChars==NULL as an empty string return length == 0 ? 0 : 1; } // get the correct pointer const UChar *chars = getArrayStart(); chars += start; srcChars += srcStart; int32_t minLength; int8_t lengthResult; // get the srcLength if necessary if(srcLength < 0) { srcLength = u_strlen(srcChars + srcStart); } // are we comparing different lengths? if(length != srcLength) { if(length < srcLength) { minLength = length; lengthResult = -1; } else { minLength = srcLength; lengthResult = 1; } } else { minLength = length; lengthResult = 0; } /* * note that uprv_memcmp() returns an int but we return an int8_t; * we need to take care not to truncate the result - * one way to do this is to right-shift the value to * move the sign bit into the lower 8 bits and making sure that this * does not become 0 itself */ if(minLength > 0 && chars != srcChars) { int32_t result; # if U_IS_BIG_ENDIAN // big-endian: byte comparison works result = uprv_memcmp(chars, srcChars, minLength * sizeof(UChar)); if(result != 0) { return (int8_t)(result >> 15 | 1); } # else // little-endian: compare UChar units do { result = ((int32_t)*(chars++) - (int32_t)*(srcChars++)); if(result != 0) { return (int8_t)(result >> 15 | 1); } } while(--minLength > 0); # endif } return lengthResult; } /* String compare in code point order - doCompare() compares in code unit order. */ int8_t UnicodeString::doCompareCodePointOrder(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) const { // compare illegal string values // treat const UChar *srcChars==NULL as an empty string if(isBogus()) { return -1; } // pin indices to legal values pinIndices(start, length); if(srcChars == NULL) { srcStart = srcLength = 0; } int32_t diff = uprv_strCompare(getArrayStart() + start, length, (srcChars!=NULL)?(srcChars + srcStart):NULL, srcLength, FALSE, TRUE); /* translate the 32-bit result into an 8-bit one */ if(diff!=0) { return (int8_t)(diff >> 15 | 1); } else { return 0; } } int32_t UnicodeString::getLength() const { return length(); } UChar UnicodeString::getCharAt(int32_t offset) const { return charAt(offset); } UChar32 UnicodeString::getChar32At(int32_t offset) const { return char32At(offset); } UChar32 UnicodeString::char32At(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); UChar32 c; U16_GET(array, 0, offset, len, c); return c; } else { return kInvalidUChar; } } int32_t UnicodeString::getChar32Start(int32_t offset) const { if((uint32_t)offset < (uint32_t)length()) { const UChar *array = getArrayStart(); U16_SET_CP_START(array, 0, offset); return offset; } else { return 0; } } int32_t UnicodeString::getChar32Limit(int32_t offset) const { int32_t len = length(); if((uint32_t)offset < (uint32_t)len) { const UChar *array = getArrayStart(); U16_SET_CP_LIMIT(array, 0, offset, len); return offset; } else { return len; } } int32_t UnicodeString::countChar32(int32_t start, int32_t length) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_countChar32() checks for NULL return u_countChar32(getArrayStart()+start, length); } UBool UnicodeString::hasMoreChar32Than(int32_t start, int32_t length, int32_t number) const { pinIndices(start, length); // if(isBogus()) then fArray==0 and start==0 - u_strHasMoreChar32Than() checks for NULL return u_strHasMoreChar32Than(getArrayStart()+start, length, number); } int32_t UnicodeString::moveIndex32(int32_t index, int32_t delta) const { // pin index int32_t len = length(); if(index<0) { index=0; } else if(index>len) { index=len; } const UChar *array = getArrayStart(); if(delta>0) { U16_FWD_N(array, index, len, delta); } else { U16_BACK_N(array, 0, index, -delta); } return index; } void UnicodeString::doExtract(int32_t start, int32_t length, UChar *dst, int32_t dstStart) const { // pin indices to legal values pinIndices(start, length); // do not copy anything if we alias dst itself const UChar *array = getArrayStart(); if(array + start != dst + dstStart) { us_arrayCopy(array, start, dst, dstStart, length); } } int32_t UnicodeString::extract(Char16Ptr dest, int32_t destCapacity, UErrorCode &errorCode) const { int32_t len = length(); if(U_SUCCESS(errorCode)) { if(isBogus() || destCapacity<0 || (destCapacity>0 && dest==0)) { errorCode=U_ILLEGAL_ARGUMENT_ERROR; } else { const UChar *array = getArrayStart(); if(len>0 && len<=destCapacity && array!=dest) { u_memcpy(dest, array, len); } return u_terminateUChars(dest, destCapacity, len, &errorCode); } } return len; } int32_t UnicodeString::extract(int32_t start, int32_t length, char *target, int32_t targetCapacity, enum EInvariant) const { // if the arguments are illegal, then do nothing if(targetCapacity < 0 || (targetCapacity > 0 && target == NULL)) { return 0; } // pin the indices to legal values pinIndices(start, length); if(length <= targetCapacity) { u_UCharsToChars(getArrayStart() + start, target, length); } UErrorCode status = U_ZERO_ERROR; return u_terminateChars(target, targetCapacity, length, &status); } UnicodeString UnicodeString::tempSubString(int32_t start, int32_t len) const { pinIndices(start, len); const UChar *array = getBuffer(); // not getArrayStart() to check kIsBogus & kOpenGetBuffer if(array==NULL) { array=fUnion.fStackFields.fBuffer; // anything not NULL because that would make an empty string len=-2; // bogus result string } return UnicodeString(FALSE, array + start, len); } int32_t UnicodeString::toUTF8(int32_t start, int32_t len, char *target, int32_t capacity) const { pinIndices(start, len); int32_t length8; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(target, capacity, &length8, getBuffer() + start, len, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); return length8; } #if U_CHARSET_IS_UTF8 int32_t UnicodeString::extract(int32_t start, int32_t len, char *target, uint32_t dstSize) const { // if the arguments are illegal, then do nothing if(/*dstSize < 0 || */(dstSize > 0 && target == 0)) { return 0; } return toUTF8(start, len, target, dstSize <= 0x7fffffff ? (int32_t)dstSize : 0x7fffffff); } // else see unistr_cnv.cpp #endif void UnicodeString::extractBetween(int32_t start, int32_t limit, UnicodeString& target) const { pinIndex(start); pinIndex(limit); doExtract(start, limit - start, target); } // When converting from UTF-16 to UTF-8, the result will have at most 3 times // as many bytes as the source has UChars. // The "worst cases" are writing systems like Indic, Thai and CJK with // 3:1 bytes:UChars. void UnicodeString::toUTF8(ByteSink &sink) const { int32_t length16 = length(); if(length16 != 0) { char stackBuffer[1024]; int32_t capacity = (int32_t)sizeof(stackBuffer); UBool utf8IsOwned = FALSE; char *utf8 = sink.GetAppendBuffer(length16 < capacity ? length16 : capacity, 3*length16, stackBuffer, capacity, &capacity); int32_t length8 = 0; UErrorCode errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, capacity, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); if(errorCode == U_BUFFER_OVERFLOW_ERROR) { utf8 = (char *)uprv_malloc(length8); if(utf8 != NULL) { utf8IsOwned = TRUE; errorCode = U_ZERO_ERROR; u_strToUTF8WithSub(utf8, length8, &length8, getBuffer(), length16, 0xFFFD, // Standard substitution character. NULL, // Don't care about number of substitutions. &errorCode); } else { errorCode = U_MEMORY_ALLOCATION_ERROR; } } if(U_SUCCESS(errorCode)) { sink.Append(utf8, length8); sink.Flush(); } if(utf8IsOwned) { uprv_free(utf8); } } } int32_t UnicodeString::toUTF32(UChar32 *utf32, int32_t capacity, UErrorCode &errorCode) const { int32_t length32=0; if(U_SUCCESS(errorCode)) { // getBuffer() and u_strToUTF32WithSub() check for illegal arguments. u_strToUTF32WithSub(utf32, capacity, &length32, getBuffer(), length(), 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); } return length32; } int32_t UnicodeString::indexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the first occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindFirst(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the first occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::lastIndexOf(const UChar *srcChars, int32_t srcStart, int32_t srcLength, int32_t start, int32_t length) const { if(isBogus() || srcChars == 0 || srcStart < 0 || srcLength == 0) { return -1; } // UnicodeString does not find empty substrings if(srcLength < 0 && srcChars[srcStart] == 0) { return -1; } // get the indices within bounds pinIndices(start, length); // find the last occurrence of the substring const UChar *array = getArrayStart(); const UChar *match = u_strFindLast(array + start, length, srcChars + srcStart, srcLength); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar c, int32_t start, int32_t length) const { if(isBogus()) { return -1; } // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } int32_t UnicodeString::doLastIndexOf(UChar32 c, int32_t start, int32_t length) const { // pin indices pinIndices(start, length); // find the last occurrence of c const UChar *array = getArrayStart(); const UChar *match = u_memrchr32(array + start, c, length); if(match == NULL) { return -1; } else { return (int32_t)(match - array); } } //======================================== // Write implementation //======================================== UnicodeString& UnicodeString::findAndReplace(int32_t start, int32_t length, const UnicodeString& oldText, int32_t oldStart, int32_t oldLength, const UnicodeString& newText, int32_t newStart, int32_t newLength) { if(isBogus() || oldText.isBogus() || newText.isBogus()) { return *this; } pinIndices(start, length); oldText.pinIndices(oldStart, oldLength); newText.pinIndices(newStart, newLength); if(oldLength == 0) { return *this; } while(length > 0 && length >= oldLength) { int32_t pos = indexOf(oldText, oldStart, oldLength, start, length); if(pos < 0) { // no more oldText's here: done break; } else { // we found oldText, replace it by newText and go beyond it replace(pos, oldLength, newText, newStart, newLength); length -= pos + oldLength - start; start = pos + newLength; } } return *this; } void UnicodeString::setToBogus() { releaseArray(); fUnion.fFields.fLengthAndFlags = kIsBogus; fUnion.fFields.fArray = 0; fUnion.fFields.fCapacity = 0; } // turn a bogus string into an empty one void UnicodeString::unBogus() { if(fUnion.fFields.fLengthAndFlags & kIsBogus) { setToEmpty(); } } const char16_t * UnicodeString::getTerminatedBuffer() { if(!isWritable()) { return nullptr; } UChar *array = getArrayStart(); int32_t len = length(); if(len < getCapacity()) { if(fUnion.fFields.fLengthAndFlags & kBufferIsReadonly) { // If len<capacity on a read-only alias, then array[len] is // either the original NUL (if constructed with (TRUE, s, length)) // or one of the original string contents characters (if later truncated), // therefore we can assume that array[len] is initialized memory. if(array[len] == 0) { return array; } } else if(((fUnion.fFields.fLengthAndFlags & kRefCounted) == 0 || refCount() == 1)) { // kRefCounted: Do not write the NUL if the buffer is shared. // That is mostly safe, except when the length of one copy was modified // without copy-on-write, e.g., via truncate(newLength) or remove(void). // Then the NUL would be written into the middle of another copy's string. // Otherwise, the buffer is fully writable and it is anyway safe to write the NUL. // Do not test if there is a NUL already because it might be uninitialized memory. // (That would be safe, but tools like valgrind & Purify would complain.) array[len] = 0; return array; } } if(len<INT32_MAX && cloneArrayIfNeeded(len+1)) { array = getArrayStart(); array[len] = 0; return array; } else { return nullptr; } } // setTo() analogous to the readonly-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UBool isTerminated, ConstChar16Ptr textPtr, int32_t textLength) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } const UChar *text = textPtr; if(text == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if( textLength < -1 || (textLength == -1 && !isTerminated) || (textLength >= 0 && isTerminated && text[textLength] != 0) ) { setToBogus(); return *this; } releaseArray(); if(textLength == -1) { // text is terminated, or else it would have failed the above test textLength = u_strlen(text); } fUnion.fFields.fLengthAndFlags = kReadonlyAlias; setArray((UChar *)text, textLength, isTerminated ? textLength + 1 : textLength); return *this; } // setTo() analogous to the writable-aliasing constructor with the same signature UnicodeString & UnicodeString::setTo(UChar *buffer, int32_t buffLength, int32_t buffCapacity) { if(fUnion.fFields.fLengthAndFlags & kOpenGetBuffer) { // do not modify a string that has an "open" getBuffer(minCapacity) return *this; } if(buffer == NULL) { // treat as an empty string, do not alias releaseArray(); setToEmpty(); return *this; } if(buffLength < -1 || buffCapacity < 0 || buffLength > buffCapacity) { setToBogus(); return *this; } else if(buffLength == -1) { // buffLength = u_strlen(buff); but do not look beyond buffCapacity const UChar *p = buffer, *limit = buffer + buffCapacity; while(p != limit && *p != 0) { ++p; } buffLength = (int32_t)(p - buffer); } releaseArray(); fUnion.fFields.fLengthAndFlags = kWritableAlias; setArray(buffer, buffLength, buffCapacity); return *this; } UnicodeString &UnicodeString::setToUTF8(StringPiece utf8) { unBogus(); int32_t length = utf8.length(); int32_t capacity; // The UTF-16 string will be at most as long as the UTF-8 string. if(length <= US_STACKBUF_SIZE) { capacity = US_STACKBUF_SIZE; } else { capacity = length + 1; // +1 for the terminating NUL. } UChar *utf16 = getBuffer(capacity); int32_t length16; UErrorCode errorCode = U_ZERO_ERROR; u_strFromUTF8WithSub(utf16, getCapacity(), &length16, utf8.data(), length, 0xfffd, // Substitution character. NULL, // Don't care about number of substitutions. &errorCode); releaseBuffer(length16); if(U_FAILURE(errorCode)) { setToBogus(); } return *this; } UnicodeString& UnicodeString::setCharAt(int32_t offset, UChar c) { int32_t len = length(); if(cloneArrayIfNeeded() && len > 0) { if(offset < 0) { offset = 0; } else if(offset >= len) { offset = len - 1; } getArrayStart()[offset] = c; } return *this; } UnicodeString& UnicodeString::replace(int32_t start, int32_t _length, UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t count = 0; UBool isError = FALSE; U16_APPEND(buffer, count, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError (srcChar is not a valid code point) then count==0 which means // we remove the source segment rather than replacing it with srcChar. return doReplace(start, _length, buffer, 0, isError ? 0 : count); } UnicodeString& UnicodeString::append(UChar32 srcChar) { UChar buffer[U16_MAX_LENGTH]; int32_t _length = 0; UBool isError = FALSE; U16_APPEND(buffer, _length, U16_MAX_LENGTH, srcChar, isError); // We test isError so that the compiler does not complain that we don't. // If isError then _length==0 which turns the doAppend() into a no-op anyway. return isError ? *this : doAppend(buffer, 0, _length); } UnicodeString& UnicodeString::doReplace( int32_t start, int32_t length, const UnicodeString& src, int32_t srcStart, int32_t srcLength) { // pin the indices to legal values src.pinIndices(srcStart, srcLength); // get the characters from src // and replace the range in ourselves with them return doReplace(start, length, src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doReplace(int32_t start, int32_t length, const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable()) { return *this; } int32_t oldLength = this->length(); // optimize (read-only alias).remove(0, start) and .remove(start, end) if((fUnion.fFields.fLengthAndFlags&kBufferIsReadonly) && srcLength == 0) { if(start == 0) { // remove prefix by adjusting the array pointer pinIndex(length); fUnion.fFields.fArray += length; fUnion.fFields.fCapacity -= length; setLength(oldLength - length); return *this; } else { pinIndex(start); if(length >= (oldLength - start)) { // remove suffix by reducing the length (like truncate()) setLength(start); fUnion.fFields.fCapacity = start; // not NUL-terminated any more return *this; } } } if(start == oldLength) { return doAppend(srcChars, srcStart, srcLength); } if(srcChars == 0) { srcLength = 0; } else { // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if (srcLength < 0) { // get the srcLength if necessary srcLength = u_strlen(srcChars); } } // pin the indices to legal values pinIndices(start, length); // Calculate the size of the string after the replace. // Avoid int32_t overflow. int32_t newLength = oldLength - length; if(srcLength > (INT32_MAX - newLength)) { setToBogus(); return *this; } newLength += srcLength; // Check for insertion into ourself const UChar *oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doReplace(start, length, copy.getArrayStart(), 0, srcLength); } // cloneArrayIfNeeded(doCopyArray=FALSE) may change fArray but will not copy the current contents; // therefore we need to keep the current fArray UChar oldStackBuffer[US_STACKBUF_SIZE]; if((fUnion.fFields.fLengthAndFlags&kUsingStackBuffer) && (newLength > US_STACKBUF_SIZE)) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values u_memcpy(oldStackBuffer, oldArray, oldLength); oldArray = oldStackBuffer; } // clone our array and allocate a bigger array if needed int32_t *bufferToDelete = 0; if(!cloneArrayIfNeeded(newLength, getGrowCapacity(newLength), FALSE, &bufferToDelete) ) { return *this; } // now do the replace UChar *newArray = getArrayStart(); if(newArray != oldArray) { // if fArray changed, then we need to copy everything except what will change us_arrayCopy(oldArray, 0, newArray, 0, start); us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } else if(length != srcLength) { // fArray did not change; copy only the portion that isn't changing, leaving a hole us_arrayCopy(oldArray, start + length, newArray, start + srcLength, oldLength - (start + length)); } // now fill in the hole with the new string us_arrayCopy(srcChars, 0, newArray, start, srcLength); setLength(newLength); // delayed delete in case srcChars == fArray when we started, and // to keep oldArray alive for the above operations if (bufferToDelete) { uprv_free(bufferToDelete); } return *this; } // Versions of doReplace() only for append() variants. // doReplace() and doAppend() optimize for different cases. UnicodeString& UnicodeString::doAppend(const UnicodeString& src, int32_t srcStart, int32_t srcLength) { if(srcLength == 0) { return *this; } // pin the indices to legal values src.pinIndices(srcStart, srcLength); return doAppend(src.getArrayStart(), srcStart, srcLength); } UnicodeString& UnicodeString::doAppend(const UChar *srcChars, int32_t srcStart, int32_t srcLength) { if(!isWritable() || srcLength == 0 || srcChars == NULL) { return *this; } // Perform all remaining operations relative to srcChars + srcStart. // From this point forward, do not use srcStart. srcChars += srcStart; if(srcLength < 0) { // get the srcLength if necessary if((srcLength = u_strlen(srcChars)) == 0) { return *this; } } int32_t oldLength = length(); int32_t newLength = oldLength + srcLength; // Check for append onto ourself const UChar* oldArray = getArrayStart(); if (isBufferWritable() && oldArray < srcChars + srcLength && srcChars < oldArray + oldLength) { // Copy into a new UnicodeString and start over UnicodeString copy(srcChars, srcLength); if (copy.isBogus()) { setToBogus(); return *this; } return doAppend(copy.getArrayStart(), 0, srcLength); } // optimize append() onto a large-enough, owned string if((newLength <= getCapacity() && isBufferWritable()) || cloneArrayIfNeeded(newLength, getGrowCapacity(newLength))) { UChar *newArray = getArrayStart(); // Do not copy characters when // UChar *buffer=str.getAppendBuffer(...); // is followed by // str.append(buffer, length); // or // str.appendString(buffer, length) // or similar. if(srcChars != newArray + oldLength) { us_arrayCopy(srcChars, 0, newArray, oldLength, srcLength); } setLength(newLength); } return *this; } /** * Replaceable API */ void UnicodeString::handleReplaceBetween(int32_t start, int32_t limit, const UnicodeString& text) { replaceBetween(start, limit, text); } /** * Replaceable API */ void UnicodeString::copy(int32_t start, int32_t limit, int32_t dest) { if (limit <= start) { return; // Nothing to do; avoid bogus malloc call } UChar* text = (UChar*) uprv_malloc( sizeof(UChar) * (limit - start) ); // Check to make sure text is not null. if (text != NULL) { extractBetween(start, limit, text, 0); insert(dest, text, 0, limit - start); uprv_free(text); } } /** * Replaceable API * * NOTE: This is for the Replaceable class. There is no rep.cpp, * so we implement this function here. */ UBool Replaceable::hasMetaData() const { return TRUE; } /** * Replaceable API */ UBool UnicodeString::hasMetaData() const { return FALSE; } UnicodeString& UnicodeString::doReverse(int32_t start, int32_t length) { if(length <= 1 || !cloneArrayIfNeeded()) { return *this; } // pin the indices to legal values pinIndices(start, length); if(length <= 1) { // pinIndices() might have shrunk the length return *this; } UChar *left = getArrayStart() + start; UChar *right = left + length - 1; // -1 for inclusive boundary (length>=2) UChar swap; UBool hasSupplementary = FALSE; // Before the loop we know left<right because length>=2. do { hasSupplementary |= (UBool)U16_IS_LEAD(swap = *left); hasSupplementary |= (UBool)U16_IS_LEAD(*left++ = *right); *right-- = swap; } while(left < right); // Make sure to test the middle code unit of an odd-length string. // Redundant if the length is even. hasSupplementary |= (UBool)U16_IS_LEAD(*left); /* if there are supplementary code points in the reversed range, then re-swap their surrogates */ if(hasSupplementary) { UChar swap2; left = getArrayStart() + start; right = left + length - 1; // -1 so that we can look at *(left+1) if left<right while(left < right) { if(U16_IS_TRAIL(swap = *left) && U16_IS_LEAD(swap2 = *(left + 1))) { *left++ = swap2; *left++ = swap; } else { ++left; } } } return *this; } UBool UnicodeString::padLeading(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // move contents up by padding width UChar *array = getArrayStart(); int32_t start = targetLength - oldLength; us_arrayCopy(array, 0, array, start, oldLength); // fill in padding character while(--start >= 0) { array[start] = padChar; } setLength(targetLength); return TRUE; } } UBool UnicodeString::padTrailing(int32_t targetLength, UChar padChar) { int32_t oldLength = length(); if(oldLength >= targetLength || !cloneArrayIfNeeded(targetLength)) { return FALSE; } else { // fill in padding character UChar *array = getArrayStart(); int32_t length = targetLength; while(--length >= oldLength) { array[length] = padChar; } setLength(targetLength); return TRUE; } } //======================================== // Hashing //======================================== int32_t UnicodeString::doHashCode() const { /* Delegate hash computation to uhash. This makes UnicodeString * hashing consistent with UChar* hashing. */ int32_t hashCode = ustr_hashUCharsN(getArrayStart(), length()); if (hashCode == kInvalidHashCode) { hashCode = kEmptyHashCode; } return hashCode; } //======================================== // External Buffer //======================================== char16_t * UnicodeString::getBuffer(int32_t minCapacity) { if(minCapacity>=-1 && cloneArrayIfNeeded(minCapacity)) { fUnion.fFields.fLengthAndFlags|=kOpenGetBuffer; setZeroLength(); return getArrayStart(); } else { return nullptr; } } void UnicodeString::releaseBuffer(int32_t newLength) { if(fUnion.fFields.fLengthAndFlags&kOpenGetBuffer && newLength>=-1) { // set the new fLength int32_t capacity=getCapacity(); if(newLength==-1) { // the new length is the string length, capped by fCapacity const UChar *array=getArrayStart(), *p=array, *limit=array+capacity; while(p<limit && *p!=0) { ++p; } newLength=(int32_t)(p-array); } else if(newLength>capacity) { newLength=capacity; } setLength(newLength); fUnion.fFields.fLengthAndFlags&=~kOpenGetBuffer; } } //======================================== // Miscellaneous //======================================== UBool UnicodeString::cloneArrayIfNeeded(int32_t newCapacity, int32_t growCapacity, UBool doCopyArray, int32_t **pBufferToDelete, UBool forceClone) { // default parameters need to be static, therefore // the defaults are -1 to have convenience defaults if(newCapacity == -1) { newCapacity = getCapacity(); } // while a getBuffer(minCapacity) is "open", // prevent any modifications of the string by returning FALSE here // if the string is bogus, then only an assignment or similar can revive it if(!isWritable()) { return FALSE; } /* * We need to make a copy of the array if * the buffer is read-only, or * the buffer is refCounted (shared), and refCount>1, or * the buffer is too small. * Return FALSE if memory could not be allocated. */ if(forceClone || fUnion.fFields.fLengthAndFlags & kBufferIsReadonly || (fUnion.fFields.fLengthAndFlags & kRefCounted && refCount() > 1) || newCapacity > getCapacity() ) { // check growCapacity for default value and use of the stack buffer if(growCapacity < 0) { growCapacity = newCapacity; } else if(newCapacity <= US_STACKBUF_SIZE && growCapacity > US_STACKBUF_SIZE) { growCapacity = US_STACKBUF_SIZE; } // save old values UChar oldStackBuffer[US_STACKBUF_SIZE]; UChar *oldArray; int32_t oldLength = length(); int16_t flags = fUnion.fFields.fLengthAndFlags; if(flags&kUsingStackBuffer) { U_ASSERT(!(flags&kRefCounted)); /* kRefCounted and kUsingStackBuffer are mutally exclusive */ if(doCopyArray && growCapacity > US_STACKBUF_SIZE) { // copy the stack buffer contents because it will be overwritten with // fUnion.fFields values us_arrayCopy(fUnion.fStackFields.fBuffer, 0, oldStackBuffer, 0, oldLength); oldArray = oldStackBuffer; } else { oldArray = NULL; // no need to copy from the stack buffer to itself } } else { oldArray = fUnion.fFields.fArray; U_ASSERT(oldArray!=NULL); /* when stack buffer is not used, oldArray must have a non-NULL reference */ } // allocate a new array if(allocate(growCapacity) || (newCapacity < growCapacity && allocate(newCapacity)) ) { if(doCopyArray) { // copy the contents // do not copy more than what fits - it may be smaller than before int32_t minLength = oldLength; newCapacity = getCapacity(); if(newCapacity < minLength) { minLength = newCapacity; } if(oldArray != NULL) { us_arrayCopy(oldArray, 0, getArrayStart(), 0, minLength); } setLength(minLength); } else { setZeroLength(); } // release the old array if(flags & kRefCounted) { // the array is refCounted; decrement and release if 0 u_atomic_int32_t *pRefCount = ((u_atomic_int32_t *)oldArray - 1); if(umtx_atomic_dec(pRefCount) == 0) { if(pBufferToDelete == 0) { // Note: cast to (void *) is needed with MSVC, where u_atomic_int32_t // is defined as volatile. (Volatile has useful non-standard behavior // with this compiler.) uprv_free((void *)pRefCount); } else { // the caller requested to delete it himself *pBufferToDelete = (int32_t *)pRefCount; } } } } else { // not enough memory for growCapacity and not even for the smaller newCapacity // reset the old values for setToBogus() to release the array if(!(flags&kUsingStackBuffer)) { fUnion.fFields.fArray = oldArray; } fUnion.fFields.fLengthAndFlags = flags; setToBogus(); return FALSE; } } return TRUE; } // UnicodeStringAppendable ------------------------------------------------- *** UnicodeStringAppendable::~UnicodeStringAppendable() {} UBool UnicodeStringAppendable::appendCodeUnit(UChar c) { return str.doAppend(&c, 0, 1).isWritable(); } UBool UnicodeStringAppendable::appendCodePoint(UChar32 c) { UChar buffer[U16_MAX_LENGTH]; int32_t cLength = 0; UBool isError = FALSE; U16_APPEND(buffer, cLength, U16_MAX_LENGTH, c, isError); return !isError && str.doAppend(buffer, 0, cLength).isWritable(); } UBool UnicodeStringAppendable::appendString(const UChar *s, int32_t length) { return str.doAppend(s, 0, length).isWritable(); } UBool UnicodeStringAppendable::reserveAppendCapacity(int32_t appendCapacity) { return str.cloneArrayIfNeeded(str.length() + appendCapacity); } UChar * UnicodeStringAppendable::getAppendBuffer(int32_t minCapacity, int32_t desiredCapacityHint, UChar *scratch, int32_t scratchCapacity, int32_t *resultCapacity) { if(minCapacity < 1 || scratchCapacity < minCapacity) { *resultCapacity = 0; return NULL; } int32_t oldLength = str.length(); if(minCapacity <= (kMaxCapacity - oldLength) && desiredCapacityHint <= (kMaxCapacity - oldLength) && str.cloneArrayIfNeeded(oldLength + minCapacity, oldLength + desiredCapacityHint)) { *resultCapacity = str.getCapacity() - oldLength; return str.getArrayStart() + oldLength; } *resultCapacity = scratchCapacity; return scratch; } U_NAMESPACE_END U_NAMESPACE_USE U_CAPI int32_t U_EXPORT2 uhash_hashUnicodeString(const UElement key) { const UnicodeString *str = (const UnicodeString*) key.pointer; return (str == NULL) ? 0 : str->hashCode(); } // Moved here from uhash_us.cpp so that using a UVector of UnicodeString* // does not depend on hashtable code. U_CAPI UBool U_EXPORT2 uhash_compareUnicodeString(const UElement key1, const UElement key2) { const UnicodeString *str1 = (const UnicodeString*) key1.pointer; const UnicodeString *str2 = (const UnicodeString*) key2.pointer; if (str1 == str2) { return TRUE; } if (str1 == NULL || str2 == NULL) { return FALSE; } return *str1 == *str2; } #ifdef U_STATIC_IMPLEMENTATION /* This should never be called. It is defined here to make sure that the virtual vector deleting destructor is defined within unistr.cpp. The vector deleting destructor is already a part of UObject, but defining it here makes sure that it is included with this object file. This makes sure that static library dependencies are kept to a minimum. */ static void uprv_UnicodeStringDummy(void) { delete [] (new UnicodeString[2]); } #endif
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_3872_0
crossvul-cpp_data_good_583_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, unsigned count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD else if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF; for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if(width>768 || raw_width>768 || height > 512 || raw_height>512 ) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; if(col>=0) FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* extra room for data stored w/o predictor */ int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float libraw_powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * libraw_powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; #ifdef LIBRAW_LIBRARY_BUILD if(offset>ifp->size()-8) // At least 8 bytes for tag/len offset = ifp->size()-8; #endif while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); if(len < 0) return; // just ignore wrong len?? or raise bad file exception? switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64(2.0f, -int_to_float((get4(),get4()))); aperture = libraw_powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = libraw_powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 { ushort q = get2(); cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024; } if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; if ((int)size < 0) return; // 2+GB is too much if (save + size < save) return; // 32bit overflow fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // data length should be in range w*h..w*h*2 if(width*height < (LIBRAW_MAX_ALLOC_MB*1024*512L) && width*height>1 && i >= width * height && i <= width*height*2) { #endif switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 0: throw LIBRAW_EXCEPTION_IO_CORRUPT; break; #endif } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD } else is_raw = 0; #endif } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ( (int)width + (int)left_margin > 65535) || ( (int)height + (int)top_margin > 65535) ) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_583_1
crossvul-cpp_data_bad_434_1
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include <cstdlib> #include <cmath> #include <limits> #include <stdlib.h> #include "unicode/plurrule.h" #include "cmemory.h" #include "number_decnum.h" #include "putilimp.h" #include "number_decimalquantity.h" #include "number_roundingutils.h" #include "double-conversion.h" #include "charstr.h" #include "number_utils.h" #include "uassert.h" using namespace icu; using namespace icu::number; using namespace icu::number::impl; using icu::double_conversion::DoubleToStringConverter; using icu::double_conversion::StringToDoubleConverter; namespace { int8_t NEGATIVE_FLAG = 1; int8_t INFINITY_FLAG = 2; int8_t NAN_FLAG = 4; /** Helper function for safe subtraction (no overflow). */ inline int32_t safeSubtract(int32_t a, int32_t b) { // Note: In C++, signed integer subtraction is undefined behavior. int32_t diff = static_cast<int32_t>(static_cast<uint32_t>(a) - static_cast<uint32_t>(b)); if (b < 0 && diff < a) { return INT32_MAX; } if (b > 0 && diff > a) { return INT32_MIN; } return diff; } static double DOUBLE_MULTIPLIERS[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21}; } // namespace icu::IFixedDecimal::~IFixedDecimal() = default; DecimalQuantity::DecimalQuantity() { setBcdToZero(); flags = 0; } DecimalQuantity::~DecimalQuantity() { if (usingBytes) { uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; usingBytes = false; } } DecimalQuantity::DecimalQuantity(const DecimalQuantity &other) { *this = other; } DecimalQuantity::DecimalQuantity(DecimalQuantity&& src) U_NOEXCEPT { *this = std::move(src); } DecimalQuantity &DecimalQuantity::operator=(const DecimalQuantity &other) { if (this == &other) { return *this; } copyBcdFrom(other); copyFieldsFrom(other); return *this; } DecimalQuantity& DecimalQuantity::operator=(DecimalQuantity&& src) U_NOEXCEPT { if (this == &src) { return *this; } moveBcdFrom(src); copyFieldsFrom(src); return *this; } void DecimalQuantity::copyFieldsFrom(const DecimalQuantity& other) { bogus = other.bogus; lOptPos = other.lOptPos; lReqPos = other.lReqPos; rReqPos = other.rReqPos; rOptPos = other.rOptPos; scale = other.scale; precision = other.precision; flags = other.flags; origDouble = other.origDouble; origDelta = other.origDelta; isApproximate = other.isApproximate; } void DecimalQuantity::clear() { lOptPos = INT32_MAX; lReqPos = 0; rReqPos = 0; rOptPos = INT32_MIN; flags = 0; setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data } void DecimalQuantity::setIntegerLength(int32_t minInt, int32_t maxInt) { // Validation should happen outside of DecimalQuantity, e.g., in the Precision class. U_ASSERT(minInt >= 0); U_ASSERT(maxInt >= minInt); // Special behavior: do not set minInt to be less than what is already set. // This is so significant digits rounding can set the integer length. if (minInt < lReqPos) { minInt = lReqPos; } // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE lOptPos = maxInt; lReqPos = minInt; } void DecimalQuantity::setFractionLength(int32_t minFrac, int32_t maxFrac) { // Validation should happen outside of DecimalQuantity, e.g., in the Precision class. U_ASSERT(minFrac >= 0); U_ASSERT(maxFrac >= minFrac); // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE rReqPos = -minFrac; rOptPos = -maxFrac; } uint64_t DecimalQuantity::getPositionFingerprint() const { uint64_t fingerprint = 0; fingerprint ^= lOptPos; fingerprint ^= (lReqPos << 16); fingerprint ^= (static_cast<uint64_t>(rReqPos) << 32); fingerprint ^= (static_cast<uint64_t>(rOptPos) << 48); return fingerprint; } void DecimalQuantity::roundToIncrement(double roundingIncrement, RoundingMode roundingMode, int32_t maxFrac, UErrorCode& status) { // TODO(13701): Move the nickel check into a higher-level API. if (roundingIncrement == 0.05) { roundToMagnitude(-2, roundingMode, true, status); roundToMagnitude(-maxFrac, roundingMode, false, status); return; } else if (roundingIncrement == 0.5) { roundToMagnitude(-1, roundingMode, true, status); roundToMagnitude(-maxFrac, roundingMode, false, status); return; } // TODO(13701): This is innefficient. Improve? // TODO(13701): Should we convert to decNumber instead? roundToInfinity(); double temp = toDouble(); temp /= roundingIncrement; // Use another DecimalQuantity to perform the actual rounding... DecimalQuantity dq; dq.setToDouble(temp); dq.roundToMagnitude(0, roundingMode, status); temp = dq.toDouble(); temp *= roundingIncrement; setToDouble(temp); // Since we reset the value to a double, we need to specify the rounding boundary // in order to get the DecimalQuantity out of approximation mode. // NOTE: In Java, we have minMaxFrac, but in C++, the two are differentiated. roundToMagnitude(-maxFrac, roundingMode, status); } void DecimalQuantity::multiplyBy(const DecNum& multiplicand, UErrorCode& status) { if (isInfinite() || isZero() || isNaN()) { return; } // Convert to DecNum, multiply, and convert back. DecNum decnum; toDecNum(decnum, status); if (U_FAILURE(status)) { return; } decnum.multiplyBy(multiplicand, status); if (U_FAILURE(status)) { return; } setToDecNum(decnum, status); } void DecimalQuantity::divideBy(const DecNum& divisor, UErrorCode& status) { if (isInfinite() || isZero() || isNaN()) { return; } // Convert to DecNum, multiply, and convert back. DecNum decnum; toDecNum(decnum, status); if (U_FAILURE(status)) { return; } decnum.divideBy(divisor, status); if (U_FAILURE(status)) { return; } setToDecNum(decnum, status); } void DecimalQuantity::negate() { flags ^= NEGATIVE_FLAG; } int32_t DecimalQuantity::getMagnitude() const { U_ASSERT(precision != 0); return scale + precision - 1; } bool DecimalQuantity::adjustMagnitude(int32_t delta) { if (precision != 0) { // i.e., scale += delta; origDelta += delta bool overflow = uprv_add32_overflow(scale, delta, &scale); overflow = uprv_add32_overflow(origDelta, delta, &origDelta) || overflow; // Make sure that precision + scale won't overflow, either int32_t dummy; overflow = overflow || uprv_add32_overflow(scale, precision, &dummy); return overflow; } return false; } double DecimalQuantity::getPluralOperand(PluralOperand operand) const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. U_ASSERT(!isApproximate); switch (operand) { case PLURAL_OPERAND_I: // Invert the negative sign if necessary return static_cast<double>(isNegative() ? -toLong(true) : toLong(true)); case PLURAL_OPERAND_F: return static_cast<double>(toFractionLong(true)); case PLURAL_OPERAND_T: return static_cast<double>(toFractionLong(false)); case PLURAL_OPERAND_V: return fractionCount(); case PLURAL_OPERAND_W: return fractionCountWithoutTrailingZeros(); default: return std::abs(toDouble()); } } bool DecimalQuantity::hasIntegerValue() const { return scale >= 0; } int32_t DecimalQuantity::getUpperDisplayMagnitude() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); int32_t magnitude = scale + precision; int32_t result = (lReqPos > magnitude) ? lReqPos : (lOptPos < magnitude) ? lOptPos : magnitude; return result - 1; } int32_t DecimalQuantity::getLowerDisplayMagnitude() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); int32_t magnitude = scale; int32_t result = (rReqPos < magnitude) ? rReqPos : (rOptPos > magnitude) ? rOptPos : magnitude; return result; } int8_t DecimalQuantity::getDigit(int32_t magnitude) const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. U_ASSERT(!isApproximate); return getDigitPos(magnitude - scale); } int32_t DecimalQuantity::fractionCount() const { return -getLowerDisplayMagnitude(); } int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const { return -scale > 0 ? -scale : 0; // max(-scale, 0) } bool DecimalQuantity::isNegative() const { return (flags & NEGATIVE_FLAG) != 0; } int8_t DecimalQuantity::signum() const { return isNegative() ? -1 : isZero() ? 0 : 1; } bool DecimalQuantity::isInfinite() const { return (flags & INFINITY_FLAG) != 0; } bool DecimalQuantity::isNaN() const { return (flags & NAN_FLAG) != 0; } bool DecimalQuantity::isZero() const { return precision == 0; } DecimalQuantity &DecimalQuantity::setToInt(int32_t n) { setBcdToZero(); flags = 0; if (n == INT32_MIN) { flags |= NEGATIVE_FLAG; // leave as INT32_MIN; handled below in _setToInt() } else if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToInt(n); compact(); } return *this; } void DecimalQuantity::_setToInt(int32_t n) { if (n == INT32_MIN) { readLongToBcd(-static_cast<int64_t>(n)); } else { readIntToBcd(n); } } DecimalQuantity &DecimalQuantity::setToLong(int64_t n) { setBcdToZero(); flags = 0; if (n < 0 && n > INT64_MIN) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToLong(n); compact(); } return *this; } void DecimalQuantity::_setToLong(int64_t n) { if (n == INT64_MIN) { DecNum decnum; UErrorCode localStatus = U_ZERO_ERROR; decnum.setTo("9.223372036854775808E+18", localStatus); if (U_FAILURE(localStatus)) { return; } // unexpected flags |= NEGATIVE_FLAG; readDecNumberToBcd(decnum); } else if (n <= INT32_MAX) { readIntToBcd(static_cast<int32_t>(n)); } else { readLongToBcd(n); } } DecimalQuantity &DecimalQuantity::setToDouble(double n) { setBcdToZero(); flags = 0; // signbit() from <math.h> handles +0.0 vs -0.0 if (std::signbit(n)) { flags |= NEGATIVE_FLAG; n = -n; } if (std::isnan(n) != 0) { flags |= NAN_FLAG; } else if (std::isfinite(n) == 0) { flags |= INFINITY_FLAG; } else if (n != 0) { _setToDoubleFast(n); compact(); } return *this; } void DecimalQuantity::_setToDoubleFast(double n) { isApproximate = true; origDouble = n; origDelta = 0; // Make sure the double is an IEEE 754 double. If not, fall back to the slow path right now. // TODO: Make a fast path for other types of doubles. if (!std::numeric_limits<double>::is_iec559) { convertToAccurateDouble(); // Turn off the approximate double flag, since the value is now exact. isApproximate = false; origDouble = 0.0; return; } // To get the bits from the double, use memcpy, which takes care of endianness. uint64_t ieeeBits; uprv_memcpy(&ieeeBits, &n, sizeof(n)); int32_t exponent = static_cast<int32_t>((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff; // Not all integers can be represented exactly for exponent > 52 if (exponent <= 52 && static_cast<int64_t>(n) == n) { _setToLong(static_cast<int64_t>(n)); return; } // 3.3219... is log2(10) auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809489); if (fracLength >= 0) { int32_t i = fracLength; // 1e22 is the largest exact double. for (; i >= 22; i -= 22) n *= 1e22; n *= DOUBLE_MULTIPLIERS[i]; } else { int32_t i = fracLength; // 1e22 is the largest exact double. for (; i <= -22; i += 22) n /= 1e22; n /= DOUBLE_MULTIPLIERS[-i]; } auto result = static_cast<int64_t>(std::round(n)); if (result != 0) { _setToLong(result); scale -= fracLength; } } void DecimalQuantity::convertToAccurateDouble() { U_ASSERT(origDouble != 0); int32_t delta = origDelta; // Call the slow oracle function (Double.toString in Java, DoubleToAscii in C++). char buffer[DoubleToStringConverter::kBase10MaximalLength + 1]; bool sign; // unused; always positive int32_t length; int32_t point; DoubleToStringConverter::DoubleToAscii( origDouble, DoubleToStringConverter::DtoaMode::SHORTEST, 0, buffer, sizeof(buffer), &sign, &length, &point ); setBcdToZero(); readDoubleConversionToBcd(buffer, length, point); scale += delta; explicitExactDouble = true; } DecimalQuantity &DecimalQuantity::setToDecNumber(StringPiece n, UErrorCode& status) { setBcdToZero(); flags = 0; // Compute the decNumber representation DecNum decnum; decnum.setTo(n, status); _setToDecNum(decnum, status); return *this; } DecimalQuantity& DecimalQuantity::setToDecNum(const DecNum& decnum, UErrorCode& status) { setBcdToZero(); flags = 0; _setToDecNum(decnum, status); return *this; } void DecimalQuantity::_setToDecNum(const DecNum& decnum, UErrorCode& status) { if (U_FAILURE(status)) { return; } if (decnum.isNegative()) { flags |= NEGATIVE_FLAG; } if (!decnum.isZero()) { readDecNumberToBcd(decnum); compact(); } } int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const { // NOTE: Call sites should be guarded by fitsInLong(), like this: // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ } // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits. uint64_t result = 0L; int32_t upperMagnitude = std::min(scale + precision, lOptPos) - 1; if (truncateIfOverflow) { upperMagnitude = std::min(upperMagnitude, 17); } for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } if (isNegative()) { return static_cast<int64_t>(0LL - result); // i.e., -result } return static_cast<int64_t>(result); } uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const { uint64_t result = 0L; int32_t magnitude = -1; int32_t lowerMagnitude = std::max(scale, rOptPos); if (includeTrailingZeros) { lowerMagnitude = std::min(lowerMagnitude, rReqPos); } for (; magnitude >= lowerMagnitude && result <= 1e18L; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } // Remove trailing zeros; this can happen during integer overflow cases. if (!includeTrailingZeros) { while (result > 0 && (result % 10) == 0) { result /= 10; } } return result; } bool DecimalQuantity::fitsInLong(bool ignoreFraction) const { if (isZero()) { return true; } if (scale < 0 && !ignoreFraction) { return false; } int magnitude = getMagnitude(); if (magnitude < 18) { return true; } if (magnitude > 18) { return false; } // Hard case: the magnitude is 10^18. // The largest int64 is: 9,223,372,036,854,775,807 for (int p = 0; p < precision; p++) { int8_t digit = getDigit(18 - p); static int8_t INT64_BCD[] = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 }; if (digit < INT64_BCD[p]) { return true; } else if (digit > INT64_BCD[p]) { return false; } } // Exactly equal to max long plus one. return isNegative(); } double DecimalQuantity::toDouble() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); if (isNaN()) { return NAN; } else if (isInfinite()) { return isNegative() ? -INFINITY : INFINITY; } // We are processing well-formed input, so we don't need any special options to StringToDoubleConverter. StringToDoubleConverter converter(0, 0, 0, "", ""); UnicodeString numberString = this->toScientificString(); int32_t count; return converter.StringToDouble( reinterpret_cast<const uint16_t*>(numberString.getBuffer()), numberString.length(), &count); } void DecimalQuantity::toDecNum(DecNum& output, UErrorCode& status) const { // Special handling for zero if (precision == 0) { output.setTo("0", status); } // Use the BCD constructor. We need to do a little bit of work to convert, though. // The decNumber constructor expects most-significant first, but we store least-significant first. MaybeStackArray<uint8_t, 20> ubcd(precision); for (int32_t m = 0; m < precision; m++) { ubcd[precision - m - 1] = static_cast<uint8_t>(getDigitPos(m)); } output.setTo(ubcd.getAlias(), precision, scale, isNegative(), status); } void DecimalQuantity::truncate() { if (scale < 0) { shiftRight(-scale); scale = 0; compact(); } } void DecimalQuantity::roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) { roundToMagnitude(magnitude, roundingMode, true, status); } void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) { roundToMagnitude(magnitude, roundingMode, false, status); } void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status) { // The position in the BCD at which rounding will be performed; digits to the right of position // will be rounded away. int position = safeSubtract(magnitude, scale); // "trailing" = least significant digit to the left of rounding int8_t trailingDigit = getDigitPos(position); if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. } else if (precision == 0) { // No rounding for zero. } else { // Perform rounding logic. // "leading" = most significant digit to the right of rounding int8_t leadingDigit = getDigitPos(safeSubtract(position, 1)); // Compute which section of the number we are in. // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles) // LOWER means we are between the bottom edge and the midpoint, like 1.391 // MIDPOINT means we are exactly in the middle, like 1.500 // UPPER means we are between the midpoint and the top edge, like 1.916 roundingutils::Section section; if (!isApproximate) { if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = roundingutils::SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = roundingutils::SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = roundingutils::SECTION_LOWER; } else { // .08, .09 => up to .10 section = roundingutils::SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = roundingutils::SECTION_LOWER; } else if (leadingDigit > 5) { // Includes nickel rounding .026-.029 and .076-.079 section = roundingutils::SECTION_UPPER; } else { // Includes nickel rounding .025 and .075 section = roundingutils::SECTION_MIDPOINT; for (int p = safeSubtract(position, 2); p >= 0; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_UPPER; break; } } } } else { int32_t p = safeSubtract(position, 2); int32_t minP = uprv_max(0, precision - 14); if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { section = roundingutils::SECTION_LOWER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_LOWER; break; } } } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = roundingutils::SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = roundingutils::SECTION_LOWER; break; } } } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = roundingutils::SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_UPPER; break; } } } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) { section = roundingutils::SECTION_UPPER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = roundingutils::SECTION_UPPER; break; } } } else if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = roundingutils::SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = roundingutils::SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = roundingutils::SECTION_LOWER; } else { // .08, .09 => up to .10 section = roundingutils::SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = roundingutils::SECTION_LOWER; } else { // Includes nickel rounding .026-.029 and .076-.079 section = roundingutils::SECTION_UPPER; } bool roundsAtMidpoint = roundingutils::roundsAtMidpoint(roundingMode); if (safeSubtract(position, 1) < precision - 14 || (roundsAtMidpoint && section == roundingutils::SECTION_MIDPOINT) || (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) { // Oops! This means that we have to get the exact representation of the double, // because the zone of uncertainty is along the rounding boundary. convertToAccurateDouble(); roundToMagnitude(magnitude, roundingMode, nickel, status); // start over return; } // Turn off the approximate double flag, since the value is now confirmed to be exact. isApproximate = false; origDouble = 0.0; origDelta = 0; if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. return; } // Good to continue rounding. if (section == -1) { section = roundingutils::SECTION_LOWER; } if (section == -2) { section = roundingutils::SECTION_UPPER; } } // Nickel rounding "half even" goes to the nearest whole (away from the 5). bool isEven = nickel ? (trailingDigit < 2 || trailingDigit > 7 || (trailingDigit == 2 && section != roundingutils::SECTION_UPPER) || (trailingDigit == 7 && section == roundingutils::SECTION_UPPER)) : (trailingDigit % 2) == 0; bool roundDown = roundingutils::getRoundingDirection(isEven, isNegative(), section, roundingMode, status); if (U_FAILURE(status)) { return; } // Perform truncation if (position >= precision) { setBcdToZero(); scale = magnitude; } else { shiftRight(position); } if (nickel) { if (trailingDigit < 5 && roundDown) { setDigitPos(0, 0); compact(); return; } else if (trailingDigit >= 5 && !roundDown) { setDigitPos(0, 9); trailingDigit = 9; // do not return: use the bubbling logic below } else { setDigitPos(0, 5); // compact not necessary: digit at position 0 is nonzero return; } } // Bubble the result to the higher digits if (!roundDown) { if (trailingDigit == 9) { int bubblePos = 0; // Note: in the long implementation, the most digits BCD can have at this point is // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe. for (; getDigitPos(bubblePos) == 9; bubblePos++) {} shiftRight(bubblePos); // shift off the trailing 9s } int8_t digit0 = getDigitPos(0); U_ASSERT(digit0 != 9); setDigitPos(0, static_cast<int8_t>(digit0 + 1)); precision += 1; // in case an extra digit got added } compact(); } } void DecimalQuantity::roundToInfinity() { if (isApproximate) { convertToAccurateDouble(); } } void DecimalQuantity::appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger) { U_ASSERT(leadingZeros >= 0); // Zero requires special handling to maintain the invariant that the least-significant digit // in the BCD is nonzero. if (value == 0) { if (appendAsInteger && precision != 0) { scale += leadingZeros + 1; } return; } // Deal with trailing zeros if (scale > 0) { leadingZeros += scale; if (appendAsInteger) { scale = 0; } } // Append digit shiftLeft(leadingZeros + 1); setDigitPos(0, value); // Fix scale if in integer mode if (appendAsInteger) { scale += leadingZeros + 1; } } UnicodeString DecimalQuantity::toPlainString() const { U_ASSERT(!isApproximate); UnicodeString sb; if (isNegative()) { sb.append(u'-'); } if (precision == 0 || getMagnitude() < 0) { sb.append(u'0'); } for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (m == -1) { sb.append(u'.'); } sb.append(getDigit(m) + u'0'); } return sb; } UnicodeString DecimalQuantity::toScientificString() const { U_ASSERT(!isApproximate); UnicodeString result; if (isNegative()) { result.append(u'-'); } if (precision == 0) { result.append(u"0E+0", -1); return result; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int32_t upperPos = std::min(precision + scale, lOptPos) - scale - 1; int32_t lowerPos = std::max(scale, rOptPos) - scale; int32_t p = upperPos; result.append(u'0' + getDigitPos(p)); if ((--p) >= lowerPos) { result.append(u'.'); for (; p >= lowerPos; p--) { result.append(u'0' + getDigitPos(p)); } } result.append(u'E'); int32_t _scale = upperPos + scale; if (_scale < 0) { _scale *= -1; result.append(u'-'); } else { result.append(u'+'); } if (_scale == 0) { result.append(u'0'); } int32_t insertIndex = result.length(); while (_scale > 0) { std::div_t res = std::div(_scale, 10); result.insert(insertIndex, u'0' + res.rem); _scale = res.quot; } return result; } //////////////////////////////////////////////////// /// End of DecimalQuantity_AbstractBCD.java /// /// Start of DecimalQuantity_DualStorageBCD.java /// //////////////////////////////////////////////////// int8_t DecimalQuantity::getDigitPos(int32_t position) const { if (usingBytes) { if (position < 0 || position >= precision) { return 0; } return fBCD.bcdBytes.ptr[position]; } else { if (position < 0 || position >= 16) { return 0; } return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf); } } void DecimalQuantity::setDigitPos(int32_t position, int8_t value) { U_ASSERT(position >= 0); if (usingBytes) { ensureCapacity(position + 1); fBCD.bcdBytes.ptr[position] = value; } else if (position >= 16) { switchStorage(); ensureCapacity(position + 1); fBCD.bcdBytes.ptr[position] = value; } else { int shift = position * 4; fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift); } } void DecimalQuantity::shiftLeft(int32_t numDigits) { if (!usingBytes && precision + numDigits > 16) { switchStorage(); } if (usingBytes) { ensureCapacity(precision + numDigits); int i = precision + numDigits - 1; for (; i >= numDigits; i--) { fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i - numDigits]; } for (; i >= 0; i--) { fBCD.bcdBytes.ptr[i] = 0; } } else { fBCD.bcdLong <<= (numDigits * 4); } scale -= numDigits; precision += numDigits; } void DecimalQuantity::shiftRight(int32_t numDigits) { if (usingBytes) { int i = 0; for (; i < precision - numDigits; i++) { fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i + numDigits]; } for (; i < precision; i++) { fBCD.bcdBytes.ptr[i] = 0; } } else { fBCD.bcdLong >>= (numDigits * 4); } scale += numDigits; precision -= numDigits; } void DecimalQuantity::setBcdToZero() { if (usingBytes) { uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; usingBytes = false; } fBCD.bcdLong = 0L; scale = 0; precision = 0; isApproximate = false; origDouble = 0; origDelta = 0; } void DecimalQuantity::readIntToBcd(int32_t n) { U_ASSERT(n != 0); // ints always fit inside the long implementation. uint64_t result = 0L; int i = 16; for (; n != 0; n /= 10, i--) { result = (result >> 4) + ((static_cast<uint64_t>(n) % 10) << 60); } U_ASSERT(!usingBytes); fBCD.bcdLong = result >> (i * 4); scale = 0; precision = 16 - i; } void DecimalQuantity::readLongToBcd(int64_t n) { U_ASSERT(n != 0); if (n >= 10000000000000000L) { ensureCapacity(); int i = 0; for (; n != 0L; n /= 10L, i++) { fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(n % 10); } U_ASSERT(usingBytes); scale = 0; precision = i; } else { uint64_t result = 0L; int i = 16; for (; n != 0L; n /= 10L, i--) { result = (result >> 4) + ((n % 10) << 60); } U_ASSERT(i >= 0); U_ASSERT(!usingBytes); fBCD.bcdLong = result >> (i * 4); scale = 0; precision = 16 - i; } } void DecimalQuantity::readDecNumberToBcd(const DecNum& decnum) { const decNumber* dn = decnum.getRawDecNumber(); if (dn->digits > 16) { ensureCapacity(dn->digits); for (int32_t i = 0; i < dn->digits; i++) { fBCD.bcdBytes.ptr[i] = dn->lsu[i]; } } else { uint64_t result = 0L; for (int32_t i = 0; i < dn->digits; i++) { result |= static_cast<uint64_t>(dn->lsu[i]) << (4 * i); } fBCD.bcdLong = result; } scale = dn->exponent; precision = dn->digits; } void DecimalQuantity::readDoubleConversionToBcd( const char* buffer, int32_t length, int32_t point) { // NOTE: Despite the fact that double-conversion's API is called // "DoubleToAscii", they actually use '0' (as opposed to u8'0'). if (length > 16) { ensureCapacity(length); for (int32_t i = 0; i < length; i++) { fBCD.bcdBytes.ptr[i] = buffer[length-i-1] - '0'; } } else { uint64_t result = 0L; for (int32_t i = 0; i < length; i++) { result |= static_cast<uint64_t>(buffer[length-i-1] - '0') << (4 * i); } fBCD.bcdLong = result; } scale = point - length; precision = length; } void DecimalQuantity::compact() { if (usingBytes) { int32_t delta = 0; for (; delta < precision && fBCD.bcdBytes.ptr[delta] == 0; delta++); if (delta == precision) { // Number is zero setBcdToZero(); return; } else { // Remove trailing zeros shiftRight(delta); } // Compute precision int32_t leading = precision - 1; for (; leading >= 0 && fBCD.bcdBytes.ptr[leading] == 0; leading--); precision = leading + 1; // Switch storage mechanism if possible if (precision <= 16) { switchStorage(); } } else { if (fBCD.bcdLong == 0L) { // Number is zero setBcdToZero(); return; } // Compact the number (remove trailing zeros) // TODO: Use a more efficient algorithm here and below. There is a logarithmic one. int32_t delta = 0; for (; delta < precision && getDigitPos(delta) == 0; delta++); fBCD.bcdLong >>= delta * 4; scale += delta; // Compute precision int32_t leading = precision - 1; for (; leading >= 0 && getDigitPos(leading) == 0; leading--); precision = leading + 1; } } void DecimalQuantity::ensureCapacity() { ensureCapacity(40); } void DecimalQuantity::ensureCapacity(int32_t capacity) { if (capacity == 0) { return; } int32_t oldCapacity = usingBytes ? fBCD.bcdBytes.len : 0; if (!usingBytes) { // TODO: There is nothing being done to check for memory allocation failures. // TODO: Consider indexing by nybbles instead of bytes in C++, so that we can // make these arrays half the size. fBCD.bcdBytes.ptr = static_cast<int8_t*>(uprv_malloc(capacity * sizeof(int8_t))); fBCD.bcdBytes.len = capacity; // Initialize the byte array to zeros (this is done automatically in Java) uprv_memset(fBCD.bcdBytes.ptr, 0, capacity * sizeof(int8_t)); } else if (oldCapacity < capacity) { auto bcd1 = static_cast<int8_t*>(uprv_malloc(capacity * 2 * sizeof(int8_t))); uprv_memcpy(bcd1, fBCD.bcdBytes.ptr, oldCapacity * sizeof(int8_t)); // Initialize the rest of the byte array to zeros (this is done automatically in Java) uprv_memset(bcd1 + oldCapacity, 0, (capacity - oldCapacity) * sizeof(int8_t)); uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = bcd1; fBCD.bcdBytes.len = capacity * 2; } usingBytes = true; } void DecimalQuantity::switchStorage() { if (usingBytes) { // Change from bytes to long uint64_t bcdLong = 0L; for (int i = precision - 1; i >= 0; i--) { bcdLong <<= 4; bcdLong |= fBCD.bcdBytes.ptr[i]; } uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; fBCD.bcdLong = bcdLong; usingBytes = false; } else { // Change from long to bytes // Copy the long into a local variable since it will get munged when we allocate the bytes uint64_t bcdLong = fBCD.bcdLong; ensureCapacity(); for (int i = 0; i < precision; i++) { fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(bcdLong & 0xf); bcdLong >>= 4; } U_ASSERT(usingBytes); } } void DecimalQuantity::copyBcdFrom(const DecimalQuantity &other) { setBcdToZero(); if (other.usingBytes) { ensureCapacity(other.precision); uprv_memcpy(fBCD.bcdBytes.ptr, other.fBCD.bcdBytes.ptr, other.precision * sizeof(int8_t)); } else { fBCD.bcdLong = other.fBCD.bcdLong; } } void DecimalQuantity::moveBcdFrom(DecimalQuantity &other) { setBcdToZero(); if (other.usingBytes) { usingBytes = true; fBCD.bcdBytes.ptr = other.fBCD.bcdBytes.ptr; fBCD.bcdBytes.len = other.fBCD.bcdBytes.len; // Take ownership away from the old instance: other.fBCD.bcdBytes.ptr = nullptr; other.usingBytes = false; } else { fBCD.bcdLong = other.fBCD.bcdLong; } } const char16_t* DecimalQuantity::checkHealth() const { if (usingBytes) { if (precision == 0) { return u"Zero precision but we are in byte mode"; } int32_t capacity = fBCD.bcdBytes.len; if (precision > capacity) { return u"Precision exceeds length of byte array"; } if (getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in byte mode"; } if (getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; } for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in byte array"; } if (getDigitPos(i) < 0) { return u"Digit below 0 in byte array"; } } for (int i = precision; i < capacity; i++) { if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in byte array"; } } } else { if (precision == 0 && fBCD.bcdLong != 0) { return u"Value in bcdLong even though precision is zero"; } if (precision > 16) { return u"Precision exceeds length of long"; } if (precision != 0 && getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in long mode"; } if (precision != 0 && getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; } for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in long"; } if (getDigitPos(i) < 0) { return u"Digit below 0 in long (?!)"; } } for (int i = precision; i < 16; i++) { if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in long"; } } } // No error return nullptr; } bool DecimalQuantity::operator==(const DecimalQuantity& other) const { bool basicEquals = scale == other.scale && precision == other.precision && flags == other.flags && lOptPos == other.lOptPos && lReqPos == other.lReqPos && rReqPos == other.rReqPos && rOptPos == other.rOptPos && isApproximate == other.isApproximate; if (!basicEquals) { return false; } if (precision == 0) { return true; } else if (isApproximate) { return origDouble == other.origDouble && origDelta == other.origDelta; } else { for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (getDigit(m) != other.getDigit(m)) { return false; } } return true; } } UnicodeString DecimalQuantity::toString() const { MaybeStackArray<char, 30> digits(precision + 1); for (int32_t i = 0; i < precision; i++) { digits[i] = getDigitPos(precision - i - 1) + '0'; } digits[precision] = 0; // terminate buffer char buffer8[100]; snprintf( buffer8, sizeof(buffer8), "<DecimalQuantity %d:%d:%d:%d %s %s%s%s%d>", (lOptPos > 999 ? 999 : lOptPos), lReqPos, rReqPos, (rOptPos < -999 ? -999 : rOptPos), (usingBytes ? "bytes" : "long"), (isNegative() ? "-" : ""), (precision == 0 ? "0" : digits.getAlias()), "E", scale); return UnicodeString(buffer8, -1, US_INV); } #endif /* #if !UCONFIG_NO_FORMATTING */
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_434_1
crossvul-cpp_data_good_434_0
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 1997-2016, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* * * File FMTABLE.CPP * * Modification History: * * Date Name Description * 03/25/97 clhuang Initial Implementation. ******************************************************************************** */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include <cstdlib> #include <math.h> #include "unicode/fmtable.h" #include "unicode/ustring.h" #include "unicode/measure.h" #include "unicode/curramt.h" #include "unicode/uformattable.h" #include "charstr.h" #include "cmemory.h" #include "cstring.h" #include "fmtableimp.h" #include "number_decimalquantity.h" // ***************************************************************************** // class Formattable // ***************************************************************************** U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Formattable) using number::impl::DecimalQuantity; //-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. // NOTE: As of 3.0, there are limitations to the UObject API. It does // not (yet) support cloning, operator=, nor operator==. To // work around this, I implement some simple inlines here. Later // these can be modified or removed. [alan] // NOTE: These inlines assume that all fObjects are in fact instances // of the Measure class, which is true as of 3.0. [alan] // Return TRUE if *a == *b. static inline UBool objectEquals(const UObject* a, const UObject* b) { // LATER: return *a == *b; return *((const Measure*) a) == *((const Measure*) b); } // Return a clone of *a. static inline UObject* objectClone(const UObject* a) { // LATER: return a->clone(); return ((const Measure*) a)->clone(); } // Return TRUE if *a is an instance of Measure. static inline UBool instanceOfMeasure(const UObject* a) { return dynamic_cast<const Measure*>(a) != NULL; } /** * Creates a new Formattable array and copies the values from the specified * original. * @param array the original array * @param count the original array count * @return the new Formattable array. */ static Formattable* createArrayCopy(const Formattable* array, int32_t count) { Formattable *result = new Formattable[count]; if (result != NULL) { for (int32_t i=0; i<count; ++i) result[i] = array[i]; // Don't memcpy! } return result; } //-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. /** * Set 'ec' to 'err' only if 'ec' is not already set to a failing UErrorCode. */ static void setError(UErrorCode& ec, UErrorCode err) { if (U_SUCCESS(ec)) { ec = err; } } // // Common initialization code, shared by constructors. // Put everything into a known state. // void Formattable::init() { fValue.fInt64 = 0; fType = kLong; fDecimalStr = NULL; fDecimalQuantity = NULL; fBogus.setToBogus(); } // ------------------------------------- // default constructor. // Creates a formattable object with a long value 0. Formattable::Formattable() { init(); } // ------------------------------------- // Creates a formattable object with a Date instance. Formattable::Formattable(UDate date, ISDATE /*isDate*/) { init(); fType = kDate; fValue.fDate = date; } // ------------------------------------- // Creates a formattable object with a double value. Formattable::Formattable(double value) { init(); fType = kDouble; fValue.fDouble = value; } // ------------------------------------- // Creates a formattable object with an int32_t value. Formattable::Formattable(int32_t value) { init(); fValue.fInt64 = value; } // ------------------------------------- // Creates a formattable object with an int64_t value. Formattable::Formattable(int64_t value) { init(); fType = kInt64; fValue.fInt64 = value; } // ------------------------------------- // Creates a formattable object with a decimal number value from a string. Formattable::Formattable(StringPiece number, UErrorCode &status) { init(); setDecimalNumber(number, status); } // ------------------------------------- // Creates a formattable object with a UnicodeString instance. Formattable::Formattable(const UnicodeString& stringToCopy) { init(); fType = kString; fValue.fString = new UnicodeString(stringToCopy); } // ------------------------------------- // Creates a formattable object with a UnicodeString* value. // (adopting symantics) Formattable::Formattable(UnicodeString* stringToAdopt) { init(); fType = kString; fValue.fString = stringToAdopt; } Formattable::Formattable(UObject* objectToAdopt) { init(); fType = kObject; fValue.fObject = objectToAdopt; } // ------------------------------------- Formattable::Formattable(const Formattable* arrayToCopy, int32_t count) : UObject(), fType(kArray) { init(); fType = kArray; fValue.fArrayAndCount.fArray = createArrayCopy(arrayToCopy, count); fValue.fArrayAndCount.fCount = count; } // ------------------------------------- // copy constructor Formattable::Formattable(const Formattable &source) : UObject(*this) { init(); *this = source; } // ------------------------------------- // assignment operator Formattable& Formattable::operator=(const Formattable& source) { if (this != &source) { // Disposes the current formattable value/setting. dispose(); // Sets the correct data type for this value. fType = source.fType; switch (fType) { case kArray: // Sets each element in the array one by one and records the array count. fValue.fArrayAndCount.fCount = source.fValue.fArrayAndCount.fCount; fValue.fArrayAndCount.fArray = createArrayCopy(source.fValue.fArrayAndCount.fArray, source.fValue.fArrayAndCount.fCount); break; case kString: // Sets the string value. fValue.fString = new UnicodeString(*source.fValue.fString); break; case kDouble: // Sets the double value. fValue.fDouble = source.fValue.fDouble; break; case kLong: case kInt64: // Sets the long value. fValue.fInt64 = source.fValue.fInt64; break; case kDate: // Sets the Date value. fValue.fDate = source.fValue.fDate; break; case kObject: fValue.fObject = objectClone(source.fValue.fObject); break; } UErrorCode status = U_ZERO_ERROR; if (source.fDecimalQuantity != NULL) { fDecimalQuantity = new DecimalQuantity(*source.fDecimalQuantity); } if (source.fDecimalStr != NULL) { fDecimalStr = new CharString(*source.fDecimalStr, status); if (U_FAILURE(status)) { delete fDecimalStr; fDecimalStr = NULL; } } } return *this; } // ------------------------------------- UBool Formattable::operator==(const Formattable& that) const { int32_t i; if (this == &that) return TRUE; // Returns FALSE if the data types are different. if (fType != that.fType) return FALSE; // Compares the actual data values. UBool equal = TRUE; switch (fType) { case kDate: equal = (fValue.fDate == that.fValue.fDate); break; case kDouble: equal = (fValue.fDouble == that.fValue.fDouble); break; case kLong: case kInt64: equal = (fValue.fInt64 == that.fValue.fInt64); break; case kString: equal = (*(fValue.fString) == *(that.fValue.fString)); break; case kArray: if (fValue.fArrayAndCount.fCount != that.fValue.fArrayAndCount.fCount) { equal = FALSE; break; } // Checks each element for equality. for (i=0; i<fValue.fArrayAndCount.fCount; ++i) { if (fValue.fArrayAndCount.fArray[i] != that.fValue.fArrayAndCount.fArray[i]) { equal = FALSE; break; } } break; case kObject: if (fValue.fObject == NULL || that.fValue.fObject == NULL) { equal = FALSE; } else { equal = objectEquals(fValue.fObject, that.fValue.fObject); } break; } // TODO: compare digit lists if numeric. return equal; } // ------------------------------------- Formattable::~Formattable() { dispose(); } // ------------------------------------- void Formattable::dispose() { // Deletes the data value if necessary. switch (fType) { case kString: delete fValue.fString; break; case kArray: delete[] fValue.fArrayAndCount.fArray; break; case kObject: delete fValue.fObject; break; default: break; } fType = kLong; fValue.fInt64 = 0; delete fDecimalStr; fDecimalStr = NULL; delete fDecimalQuantity; fDecimalQuantity = NULL; } Formattable * Formattable::clone() const { return new Formattable(*this); } // ------------------------------------- // Gets the data type of this Formattable object. Formattable::Type Formattable::getType() const { return fType; } UBool Formattable::isNumeric() const { switch (fType) { case kDouble: case kLong: case kInt64: return TRUE; default: return FALSE; } } // ------------------------------------- int32_t //Formattable::getLong(UErrorCode* status) const Formattable::getLong(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: return (int32_t)fValue.fInt64; case Formattable::kInt64: if (fValue.fInt64 > INT32_MAX) { status = U_INVALID_FORMAT_ERROR; return INT32_MAX; } else if (fValue.fInt64 < INT32_MIN) { status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { return (int32_t)fValue.fInt64; } case Formattable::kDouble: if (fValue.fDouble > INT32_MAX) { status = U_INVALID_FORMAT_ERROR; return INT32_MAX; } else if (fValue.fDouble < INT32_MIN) { status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { return (int32_t)fValue.fDouble; // loses fraction } case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } // TODO Later replace this with instanceof call if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getLong(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } // ------------------------------------- // Maximum int that can be represented exactly in a double. (53 bits) // Larger ints may be rounded to a near-by value as not all are representable. // TODO: move this constant elsewhere, possibly configure it for different // floating point formats, if any non-standard ones are still in use. static const int64_t U_DOUBLE_MAX_EXACT_INT = 9007199254740992LL; int64_t Formattable::getInt64(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: case Formattable::kInt64: return fValue.fInt64; case Formattable::kDouble: if (fValue.fDouble > (double)U_INT64_MAX) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MAX; } else if (fValue.fDouble < (double)U_INT64_MIN) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MIN; } else if (fabs(fValue.fDouble) > U_DOUBLE_MAX_EXACT_INT && fDecimalQuantity != NULL) { if (fDecimalQuantity->fitsInLong(true)) { return fDecimalQuantity->toLong(); } else { // Unexpected status = U_INVALID_FORMAT_ERROR; return fDecimalQuantity->isNegative() ? U_INT64_MIN : U_INT64_MAX; } } else { return (int64_t)fValue.fDouble; } case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getInt64(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } // ------------------------------------- double Formattable::getDouble(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: case Formattable::kInt64: // loses precision return (double)fValue.fInt64; case Formattable::kDouble: return fValue.fDouble; case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } // TODO Later replace this with instanceof call if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getDouble(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } const UObject* Formattable::getObject() const { return (fType == kObject) ? fValue.fObject : NULL; } // ------------------------------------- // Sets the value to a double value d. void Formattable::setDouble(double d) { dispose(); fType = kDouble; fValue.fDouble = d; } // ------------------------------------- // Sets the value to a long value l. void Formattable::setLong(int32_t l) { dispose(); fType = kLong; fValue.fInt64 = l; } // ------------------------------------- // Sets the value to an int64 value ll. void Formattable::setInt64(int64_t ll) { dispose(); fType = kInt64; fValue.fInt64 = ll; } // ------------------------------------- // Sets the value to a Date instance d. void Formattable::setDate(UDate d) { dispose(); fType = kDate; fValue.fDate = d; } // ------------------------------------- // Sets the value to a string value stringToCopy. void Formattable::setString(const UnicodeString& stringToCopy) { dispose(); fType = kString; fValue.fString = new UnicodeString(stringToCopy); } // ------------------------------------- // Sets the value to an array of Formattable objects. void Formattable::setArray(const Formattable* array, int32_t count) { dispose(); fType = kArray; fValue.fArrayAndCount.fArray = createArrayCopy(array, count); fValue.fArrayAndCount.fCount = count; } // ------------------------------------- // Adopts the stringToAdopt value. void Formattable::adoptString(UnicodeString* stringToAdopt) { dispose(); fType = kString; fValue.fString = stringToAdopt; } // ------------------------------------- // Adopts the array value and its count. void Formattable::adoptArray(Formattable* array, int32_t count) { dispose(); fType = kArray; fValue.fArrayAndCount.fArray = array; fValue.fArrayAndCount.fCount = count; } void Formattable::adoptObject(UObject* objectToAdopt) { dispose(); fType = kObject; fValue.fObject = objectToAdopt; } // ------------------------------------- UnicodeString& Formattable::getString(UnicodeString& result, UErrorCode& status) const { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); result.setToBogus(); } else { if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); } else { result = *fValue.fString; } } return result; } // ------------------------------------- const UnicodeString& Formattable::getString(UErrorCode& status) const { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); return *getBogus(); } if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); return *getBogus(); } return *fValue.fString; } // ------------------------------------- UnicodeString& Formattable::getString(UErrorCode& status) { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); return *getBogus(); } if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); return *getBogus(); } return *fValue.fString; } // ------------------------------------- const Formattable* Formattable::getArray(int32_t& count, UErrorCode& status) const { if (fType != kArray) { setError(status, U_INVALID_FORMAT_ERROR); count = 0; return NULL; } count = fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; } // ------------------------------------- // Gets the bogus string, ensures mondo bogosity. UnicodeString* Formattable::getBogus() const { return (UnicodeString*)&fBogus; /* cast away const :-( */ } // -------------------------------------- StringPiece Formattable::getDecimalNumber(UErrorCode &status) { if (U_FAILURE(status)) { return ""; } if (fDecimalStr != NULL) { return fDecimalStr->toStringPiece(); } CharString *decimalStr = internalGetCharString(status); if(decimalStr == NULL) { return ""; // getDecimalNumber returns "" for error cases } else { return decimalStr->toStringPiece(); } } CharString *Formattable::internalGetCharString(UErrorCode &status) { if(fDecimalStr == NULL) { if (fDecimalQuantity == NULL) { // No decimal number for the formattable yet. Which means the value was // set directly by the user as an int, int64 or double. If the value came // from parsing, or from the user setting a decimal number, fDecimalNum // would already be set. // LocalPointer<DecimalQuantity> dq(new DecimalQuantity(), status); if (U_FAILURE(status)) { return nullptr; } populateDecimalQuantity(*dq, status); if (U_FAILURE(status)) { return nullptr; } fDecimalQuantity = dq.orphan(); } fDecimalStr = new CharString(); if (fDecimalStr == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } // Older ICUs called uprv_decNumberToString here, which is not exactly the same as // DecimalQuantity::toScientificString(). The biggest difference is that uprv_decNumberToString does // not print scientific notation for magnitudes greater than -5 and smaller than some amount (+5?). if (fDecimalQuantity->isZero()) { fDecimalStr->append("0", -1, status); } else if (fDecimalQuantity->getMagnitude() != INT32_MIN && std::abs(fDecimalQuantity->getMagnitude()) < 5) { fDecimalStr->appendInvariantChars(fDecimalQuantity->toPlainString(), status); } else { fDecimalStr->appendInvariantChars(fDecimalQuantity->toScientificString(), status); } } return fDecimalStr; } void Formattable::populateDecimalQuantity(number::impl::DecimalQuantity& output, UErrorCode& status) const { if (fDecimalQuantity != nullptr) { output = *fDecimalQuantity; return; } switch (fType) { case kDouble: output.setToDouble(this->getDouble()); output.roundToInfinity(); break; case kLong: output.setToInt(this->getLong()); break; case kInt64: output.setToLong(this->getInt64()); break; default: // The formattable's value is not a numeric type. status = U_INVALID_STATE_ERROR; } } // --------------------------------------- void Formattable::adoptDecimalQuantity(DecimalQuantity *dq) { if (fDecimalQuantity != NULL) { delete fDecimalQuantity; } fDecimalQuantity = dq; if (dq == NULL) { // allow adoptDigitList(NULL) to clear return; } // Set the value into the Union of simple type values. // Cannot use the set() functions because they would delete the fDecimalNum value. if (fDecimalQuantity->fitsInLong()) { fValue.fInt64 = fDecimalQuantity->toLong(); if (fValue.fInt64 <= INT32_MAX && fValue.fInt64 >= INT32_MIN) { fType = kLong; } else { fType = kInt64; } } else { fType = kDouble; fValue.fDouble = fDecimalQuantity->toDouble(); } } // --------------------------------------- void Formattable::setDecimalNumber(StringPiece numberString, UErrorCode &status) { if (U_FAILURE(status)) { return; } dispose(); auto* dq = new DecimalQuantity(); dq->setToDecNumber(numberString, status); adoptDecimalQuantity(dq); // Note that we do not hang on to the caller's input string. // If we are asked for the string, we will regenerate one from fDecimalQuantity. } #if 0 //---------------------------------------------------- // console I/O //---------------------------------------------------- #ifdef _DEBUG #include <iostream> using namespace std; #include "unicode/datefmt.h" #include "unistrm.h" class FormattableStreamer /* not : public UObject because all methods are static */ { public: static void streamOut(ostream& stream, const Formattable& obj); private: FormattableStreamer() {} // private - forbid instantiation }; // This is for debugging purposes only. This will send a displayable // form of the Formattable object to the output stream. void FormattableStreamer::streamOut(ostream& stream, const Formattable& obj) { static DateFormat *defDateFormat = 0; UnicodeString buffer; switch(obj.getType()) { case Formattable::kDate : // Creates a DateFormat instance for formatting the // Date instance. if (defDateFormat == 0) { defDateFormat = DateFormat::createInstance(); } defDateFormat->format(obj.getDate(), buffer); stream << buffer; break; case Formattable::kDouble : // Output the double as is. stream << obj.getDouble() << 'D'; break; case Formattable::kLong : // Output the double as is. stream << obj.getLong() << 'L'; break; case Formattable::kString: // Output the double as is. Please see UnicodeString console // I/O routine for more details. stream << '"' << obj.getString(buffer) << '"'; break; case Formattable::kArray: int32_t i, count; const Formattable* array; array = obj.getArray(count); stream << '['; // Recursively calling the console I/O routine for each element in the array. for (i=0; i<count; ++i) { FormattableStreamer::streamOut(stream, array[i]); stream << ( (i==(count-1)) ? "" : ", " ); } stream << ']'; break; default: // Not a recognizable Formattable object. stream << "INVALID_Formattable"; } stream.flush(); } #endif #endif U_NAMESPACE_END /* ---- UFormattable implementation ---- */ U_NAMESPACE_USE U_DRAFT UFormattable* U_EXPORT2 ufmt_open(UErrorCode *status) { if( U_FAILURE(*status) ) { return NULL; } UFormattable *fmt = (new Formattable())->toUFormattable(); if( fmt == NULL ) { *status = U_MEMORY_ALLOCATION_ERROR; } return fmt; } U_DRAFT void U_EXPORT2 ufmt_close(UFormattable *fmt) { Formattable *obj = Formattable::fromUFormattable(fmt); delete obj; } U_INTERNAL UFormattableType U_EXPORT2 ufmt_getType(const UFormattable *fmt, UErrorCode *status) { if(U_FAILURE(*status)) { return (UFormattableType)UFMT_COUNT; } const Formattable *obj = Formattable::fromUFormattable(fmt); return (UFormattableType)obj->getType(); } U_INTERNAL UBool U_EXPORT2 ufmt_isNumeric(const UFormattable *fmt) { const Formattable *obj = Formattable::fromUFormattable(fmt); return obj->isNumeric(); } U_DRAFT UDate U_EXPORT2 ufmt_getDate(const UFormattable *fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getDate(*status); } U_DRAFT double U_EXPORT2 ufmt_getDouble(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getDouble(*status); } U_DRAFT int32_t U_EXPORT2 ufmt_getLong(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getLong(*status); } U_DRAFT const void *U_EXPORT2 ufmt_getObject(const UFormattable *fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); const void *ret = obj->getObject(); if( ret==NULL && (obj->getType() != Formattable::kObject) && U_SUCCESS( *status )) { *status = U_INVALID_FORMAT_ERROR; } return ret; } U_DRAFT const UChar* U_EXPORT2 ufmt_getUChars(UFormattable *fmt, int32_t *len, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); // avoid bogosity by checking the type first. if( obj->getType() != Formattable::kString ) { if( U_SUCCESS(*status) ){ *status = U_INVALID_FORMAT_ERROR; } return NULL; } // This should return a valid string UnicodeString &str = obj->getString(*status); if( U_SUCCESS(*status) && len != NULL ) { *len = str.length(); } return str.getTerminatedBuffer(); } U_DRAFT int32_t U_EXPORT2 ufmt_getArrayLength(const UFormattable* fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); int32_t count; (void)obj->getArray(count, *status); return count; } U_DRAFT UFormattable * U_EXPORT2 ufmt_getArrayItemByIndex(UFormattable* fmt, int32_t n, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); int32_t count; (void)obj->getArray(count, *status); if(U_FAILURE(*status)) { return NULL; } else if(n<0 || n>=count) { setError(*status, U_INDEX_OUTOFBOUNDS_ERROR); return NULL; } else { return (*obj)[n].toUFormattable(); // returns non-const Formattable } } U_DRAFT const char * U_EXPORT2 ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status) { if(U_FAILURE(*status)) { return ""; } Formattable *obj = Formattable::fromUFormattable(fmt); CharString *charString = obj->internalGetCharString(*status); if(U_FAILURE(*status)) { return ""; } if(charString == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; return ""; } else { if(len!=NULL) { *len = charString->length(); } return charString->data(); } } U_DRAFT int64_t U_EXPORT2 ufmt_getInt64(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getInt64(*status); } #endif /* #if !UCONFIG_NO_FORMATTING */ //eof
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_434_0
crossvul-cpp_data_good_1010_0
// ***************************************************************** -*- C++ -*- /* * Copyright (C) 2004-2018 Exiv2 authors * This program is part of the Exiv2 distribution. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA. */ /* File: webpimage.cpp */ /* Google's WEBP container spec can be found at the link below: https://developers.google.com/speed/webp/docs/riff_container */ // ***************************************************************************** // included header files #include "config.h" #include "webpimage.hpp" #include "image_int.hpp" #include "enforce.hpp" #include "futils.hpp" #include "basicio.hpp" #include "tags.hpp" #include "tags_int.hpp" #include "types.hpp" #include "tiffimage.hpp" #include "tiffimage_int.hpp" #include "convert.hpp" #include "safe_op.hpp" #include <cmath> #include <iomanip> #include <string> #include <cstring> #include <iostream> #include <sstream> #include <cassert> #include <cstdio> #define CHECK_BIT(var,pos) ((var) & (1<<(pos))) // ***************************************************************************** // class member definitions namespace Exiv2 { namespace Internal { }} // namespace Internal, Exiv2 namespace Exiv2 { using namespace Exiv2::Internal; // This static function is a temporary fix in v0.27. In the next version, // it will be added as a method of BasicIo. static void readOrThrow(BasicIo& iIo, byte* buf, long rcount, ErrorCode err) { const long nread = iIo.read(buf, rcount); enforce(nread == rcount, err); enforce(!iIo.error(), err); } WebPImage::WebPImage(BasicIo::AutoPtr io) : Image(ImageType::webp, mdNone, io) { } // WebPImage::WebPImage std::string WebPImage::mimeType() const { return "image/webp"; } /* =========================================== */ /* Misc. */ const byte WebPImage::WEBP_PAD_ODD = 0; const int WebPImage::WEBP_TAG_SIZE = 0x4; /* VP8X feature flags */ const int WebPImage::WEBP_VP8X_ICC_BIT = 0x20; const int WebPImage::WEBP_VP8X_ALPHA_BIT = 0x10; const int WebPImage::WEBP_VP8X_EXIF_BIT = 0x8; const int WebPImage::WEBP_VP8X_XMP_BIT = 0x4; /* Chunk header names */ const char* WebPImage::WEBP_CHUNK_HEADER_VP8X = "VP8X"; const char* WebPImage::WEBP_CHUNK_HEADER_VP8L = "VP8L"; const char* WebPImage::WEBP_CHUNK_HEADER_VP8 = "VP8 "; const char* WebPImage::WEBP_CHUNK_HEADER_ANMF = "ANMF"; const char* WebPImage::WEBP_CHUNK_HEADER_ANIM = "ANIM"; const char* WebPImage::WEBP_CHUNK_HEADER_ICCP = "ICCP"; const char* WebPImage::WEBP_CHUNK_HEADER_EXIF = "EXIF"; const char* WebPImage::WEBP_CHUNK_HEADER_XMP = "XMP "; /* =========================================== */ void WebPImage::setIptcData(const IptcData& /*iptcData*/) { // not supported // just quietly ignore the request // throw(Error(kerInvalidSettingForImage, "IPTC metadata", "WebP")); } void WebPImage::setComment(const std::string& /*comment*/) { // not supported throw(Error(kerInvalidSettingForImage, "Image comment", "WebP")); } /* =========================================== */ void WebPImage::writeMetadata() { if (io_->open() != 0) { throw Error(kerDataSourceOpenFailed, io_->path(), strError()); } IoCloser closer(*io_); BasicIo::AutoPtr tempIo(new MemIo); assert (tempIo.get() != 0); doWriteMetadata(*tempIo); // may throw io_->close(); io_->transfer(*tempIo); // may throw } // WebPImage::writeMetadata void WebPImage::doWriteMetadata(BasicIo& outIo) { if (!io_->isopen()) throw Error(kerInputDataReadFailed); if (!outIo.isopen()) throw Error(kerImageWriteFailed); #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Writing metadata" << std::endl; #endif byte data [WEBP_TAG_SIZE*3]; DataBuf chunkId(WEBP_TAG_SIZE+1); chunkId.pData_ [WEBP_TAG_SIZE] = '\0'; io_->read(data, WEBP_TAG_SIZE * 3); uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian); /* Set up header */ if (outIo.write(data, WEBP_TAG_SIZE * 3) != WEBP_TAG_SIZE * 3) throw Error(kerImageWriteFailed); /* Parse Chunks */ bool has_size = false; bool has_xmp = false; bool has_exif = false; bool has_vp8x = false; bool has_alpha = false; bool has_icc = iccProfileDefined(); int width = 0; int height = 0; byte size_buff[WEBP_TAG_SIZE]; Blob blob; if (exifData_.count() > 0) { ExifParser::encode(blob, littleEndian, exifData_); if (blob.size() > 0) { has_exif = true; } } if (xmpData_.count() > 0 && !writeXmpFromPacket()) { XmpParser::encode(xmpPacket_, xmpData_, XmpParser::useCompactFormat | XmpParser::omitAllFormatting); } has_xmp = xmpPacket_.size() > 0; std::string xmp(xmpPacket_); /* Verify for a VP8X Chunk First before writing in case we have any exif or xmp data, also check for any chunks with alpha frame/layer set */ while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, WEBP_TAG_SIZE); io_->read(size_buff, WEBP_TAG_SIZE); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, payload.size_); byte c; if ( payload.size_ % 2 ) io_->read(&c,1); /* Chunk with information about features used in the file. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_vp8x) { has_vp8x = true; } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[4], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[7], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with with animation control data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANIM) && !has_alpha) { has_alpha = true; } #endif /* Chunk with with lossy image data. */ #ifdef __CHECK_FOR_ALPHA__ // Maybe in the future if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_alpha) { has_alpha = true; } #endif if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_size) { has_size = true; byte size_buf[2]; /* Refer to this https://tools.ietf.org/html/rfc6386 for height and width reference for VP8 chunks */ // Fetch width - stored in 16bits memcpy(&size_buf, &payload.pData_[6], 2); width = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; // Fetch height - stored in 16bits memcpy(&size_buf, &payload.pData_[8], 2); height = Exiv2::getUShort(size_buf, littleEndian) & 0x3fff; } /* Chunk with with lossless image data. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_alpha) { if ((payload.pData_[4] & WEBP_VP8X_ALPHA_BIT) == WEBP_VP8X_ALPHA_BIT) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_size) { has_size = true; byte size_buf_w[2]; byte size_buf_h[3]; /* For VP8L chunks width & height are stored in 28 bits of a 32 bit field requires bitshifting to get actual sizes. Width and height are split even into 14 bits each. Refer to this https://goo.gl/bpgMJf */ // Fetch width - 14 bits wide memcpy(&size_buf_w, &payload.pData_[1], 2); size_buf_w[1] &= 0x3F; width = Exiv2::getUShort(size_buf_w, littleEndian) + 1; // Fetch height - 14 bits wide memcpy(&size_buf_h, &payload.pData_[2], 3); size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2); size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2); height = Exiv2::getUShort(size_buf_h, littleEndian) + 1; } /* Chunk with animation frame. */ if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_alpha) { if ((payload.pData_[5] & 0x2) == 0x2) { has_alpha = true; } } if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_size) { has_size = true; byte size_buf[WEBP_TAG_SIZE]; // Fetch width - stored in 24bits memcpy(&size_buf, &payload.pData_[6], 3); size_buf[3] = 0; width = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height - stored in 24bits memcpy(&size_buf, &payload.pData_[9], 3); size_buf[3] = 0; height = Exiv2::getULong(size_buf, littleEndian) + 1; } /* Chunk with alpha data. */ if (equalsWebPTag(chunkId, "ALPH") && !has_alpha) { has_alpha = true; } } /* Inject a VP8X chunk if one isn't available. */ if (!has_vp8x) { inject_VP8X(outIo, has_xmp, has_exif, has_alpha, has_icc, width, height); } io_->seek(12, BasicIo::beg); while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { io_->read(chunkId.pData_, 4); io_->read(size_buff, 4); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(size); io_->read(payload.pData_, size); if ( io_->tell() % 2 ) io_->seek(+1,BasicIo::cur); // skip pad if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X)) { if (has_icc){ payload.pData_[0] |= WEBP_VP8X_ICC_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_ICC_BIT; } if (has_xmp){ payload.pData_[0] |= WEBP_VP8X_XMP_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_XMP_BIT; } if (has_exif) { payload.pData_[0] |= WEBP_VP8X_EXIF_BIT; } else { payload.pData_[0] &= ~WEBP_VP8X_EXIF_BIT; } if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } if (has_icc) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_ICCP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) iccProfile_.size_, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) { throw Error(kerImageWriteFailed); } has_icc = false; } } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) { // Skip it altogether handle it prior to here :) } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) { // Skip and add new data afterwards } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) { // Skip and add new data afterwards } else { if (outIo.write(chunkId.pData_, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write(payload.pData_, payload.size_) != payload.size_) throw Error(kerImageWriteFailed); } // Encoder required to pad odd sized data with a null byte if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_exif) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_EXIF, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); us2Data(data, (uint16_t) blob.size()+8, bigEndian); ul2Data(data, (uint32_t) blob.size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)&blob[0], static_cast<long>(blob.size())) != (long)blob.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } if (has_xmp) { if (outIo.write((const byte*)WEBP_CHUNK_HEADER_XMP, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); ul2Data(data, (uint32_t) xmpPacket().size(), littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (outIo.write((const byte*)xmp.data(), static_cast<long>(xmp.size())) != (long)xmp.size()) { throw Error(kerImageWriteFailed); } if (outIo.tell() % 2) { if (outIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } } // Fix File Size Payload Data outIo.seek(0, BasicIo::beg); filesize = outIo.size() - 8; outIo.seek(4, BasicIo::beg); ul2Data(data, (uint32_t) filesize, littleEndian); if (outIo.write(data, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); } // WebPImage::writeMetadata /* =========================================== */ void WebPImage::printStructure(std::ostream& out, PrintStructureOption option,int depth) { if (io_->open() != 0) { throw Error(kerDataSourceOpenFailed, io_->path(), strError()); } // Ensure this is the correct image type if (!isWebPType(*io_, true)) { if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData); throw Error(kerNotAnImage, "WEBP"); } bool bPrint = option==kpsBasic || option==kpsRecursive; if ( bPrint || option == kpsXMP || option == kpsIccProfile || option == kpsIptcErase ) { byte data [WEBP_TAG_SIZE * 2]; io_->read(data, WEBP_TAG_SIZE * 2); uint64_t filesize = Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian); DataBuf chunkId(5) ; chunkId.pData_[4] = '\0' ; if ( bPrint ) { out << Internal::indent(depth) << "STRUCTURE OF WEBP FILE: " << io().path() << std::endl; out << Internal::indent(depth) << Internal::stringFormat(" Chunk | Length | Offset | Payload") << std::endl; } io_->seek(0,BasicIo::beg); // rewind while ( !io_->eof() && (uint64_t) io_->tell() < filesize) { uint64_t offset = (uint64_t) io_->tell(); byte size_buff[WEBP_TAG_SIZE]; io_->read(chunkId.pData_, WEBP_TAG_SIZE); io_->read(size_buff, WEBP_TAG_SIZE); long size = Exiv2::getULong(size_buff, littleEndian); DataBuf payload(offset?size:WEBP_TAG_SIZE); // header is different from chunks io_->read(payload.pData_, payload.size_); if ( bPrint ) { out << Internal::indent(depth) << Internal::stringFormat(" %s | %8u | %8u | ", (const char*)chunkId.pData_,(uint32_t)size,(uint32_t)offset) << Internal::binaryToString(makeSlice(payload, 0, payload.size_ > 32 ? 32 : payload.size_)) << std::endl; } if ( equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF) && option==kpsRecursive ) { // create memio object with the payload, then print the structure BasicIo::AutoPtr p = BasicIo::AutoPtr(new MemIo(payload.pData_,payload.size_)); printTiffStructure(*p,out,option,depth); } bool bPrintPayload = (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP) && option==kpsXMP) || (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP) && option==kpsIccProfile) ; if ( bPrintPayload ) { out.write((const char*) payload.pData_,payload.size_); } if ( offset && io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); // skip padding byte on sub-chunks } } } /* =========================================== */ void WebPImage::readMetadata() { if (io_->open() != 0) throw Error(kerDataSourceOpenFailed, io_->path(), strError()); IoCloser closer(*io_); // Ensure that this is the correct image type if (!isWebPType(*io_, true)) { if (io_->error() || io_->eof()) throw Error(kerFailedToReadImageData); throw Error(kerNotAJpeg); } clearMetadata(); byte data[12]; DataBuf chunkId(5); chunkId.pData_[4] = '\0' ; readOrThrow(*io_, data, WEBP_TAG_SIZE * 3, Exiv2::kerCorruptedMetadata); const uint32_t filesize_u32 = Safe::add(Exiv2::getULong(data + WEBP_TAG_SIZE, littleEndian), 8U); enforce(filesize_u32 <= io_->size(), Exiv2::kerCorruptedMetadata); // Check that `filesize_u32` is safe to cast to `long`. enforce(filesize_u32 <= static_cast<size_t>(std::numeric_limits<long>::max()), Exiv2::kerCorruptedMetadata); WebPImage::decodeChunks(static_cast<long>(filesize_u32)); } // WebPImage::readMetadata void WebPImage::decodeChunks(long filesize) { DataBuf chunkId(5); byte size_buff[WEBP_TAG_SIZE]; bool has_canvas_data = false; #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Reading metadata" << std::endl; #endif chunkId.pData_[4] = '\0' ; while (!io_->eof() && io_->tell() < filesize) { readOrThrow(*io_, chunkId.pData_, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata); readOrThrow(*io_, size_buff, WEBP_TAG_SIZE, Exiv2::kerCorruptedMetadata); const uint32_t size_u32 = Exiv2::getULong(size_buff, littleEndian); // Check that `size_u32` is safe to cast to `long`. enforce(size_u32 <= static_cast<size_t>(std::numeric_limits<long>::max()), Exiv2::kerCorruptedMetadata); const long size = static_cast<long>(size_u32); // Check that `size` is within bounds. enforce(io_->tell() <= filesize, Exiv2::kerCorruptedMetadata); enforce(size <= (filesize - io_->tell()), Exiv2::kerCorruptedMetadata); DataBuf payload(size); if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8X) && !has_canvas_data) { enforce(size >= 10, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf[WEBP_TAG_SIZE]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf, &payload.pData_[4], 3); size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height memcpy(&size_buf, &payload.pData_[7], 3); size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8) && !has_canvas_data) { enforce(size >= 10, Exiv2::kerCorruptedMetadata); has_canvas_data = true; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); byte size_buf[WEBP_TAG_SIZE]; // Fetch width"" memcpy(&size_buf, &payload.pData_[6], 2); size_buf[2] = 0; size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff; // Fetch height memcpy(&size_buf, &payload.pData_[8], 2); size_buf[2] = 0; size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) & 0x3fff; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_VP8L) && !has_canvas_data) { enforce(size >= 5, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf_w[2]; byte size_buf_h[3]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf_w, &payload.pData_[1], 2); size_buf_w[1] &= 0x3F; pixelWidth_ = Exiv2::getUShort(size_buf_w, littleEndian) + 1; // Fetch height memcpy(&size_buf_h, &payload.pData_[2], 3); size_buf_h[0] = ((size_buf_h[0] >> 6) & 0x3) | ((size_buf_h[1] & 0x3F) << 0x2); size_buf_h[1] = ((size_buf_h[1] >> 6) & 0x3) | ((size_buf_h[2] & 0xF) << 0x2); pixelHeight_ = Exiv2::getUShort(size_buf_h, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ANMF) && !has_canvas_data) { enforce(size >= 12, Exiv2::kerCorruptedMetadata); has_canvas_data = true; byte size_buf[WEBP_TAG_SIZE]; readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); // Fetch width memcpy(&size_buf, &payload.pData_[6], 3); size_buf[3] = 0; pixelWidth_ = Exiv2::getULong(size_buf, littleEndian) + 1; // Fetch height memcpy(&size_buf, &payload.pData_[9], 3); size_buf[3] = 0; pixelHeight_ = Exiv2::getULong(size_buf, littleEndian) + 1; } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_ICCP)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); this->setIccProfile(payload); } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_EXIF)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); byte size_buff[2]; // 4 meaningful bytes + 2 padding bytes byte exifLongHeader[] = { 0xFF, 0x01, 0xFF, 0xE1, 0x00, 0x00 }; byte exifShortHeader[] = { 0x45, 0x78, 0x69, 0x66, 0x00, 0x00 }; byte exifTiffLEHeader[] = { 0x49, 0x49, 0x2A }; // "MM*" byte exifTiffBEHeader[] = { 0x4D, 0x4D, 0x00, 0x2A }; // "II\0*" byte* rawExifData = NULL; long offset = 0; bool s_header = false; bool le_header = false; bool be_header = false; long pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 4); if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifLongHeader, 6); if (pos != -1) { s_header = true; } } if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffLEHeader, 3); if (pos != -1) { le_header = true; } } if (pos == -1) { pos = getHeaderOffset (payload.pData_, payload.size_, (byte*)&exifTiffBEHeader, 4); if (pos != -1) { be_header = true; } } if (s_header) { offset += 6; } if (be_header || le_header) { offset += 12; } const long size = payload.size_ + offset; rawExifData = (byte*)malloc(size); if (s_header) { us2Data(size_buff, (uint16_t) (size - 6), bigEndian); memcpy(rawExifData, (char*)&exifLongHeader, 4); memcpy(rawExifData + 4, (char*)&size_buff, 2); } if (be_header || le_header) { us2Data(size_buff, (uint16_t) (size - 6), bigEndian); memcpy(rawExifData, (char*)&exifLongHeader, 4); memcpy(rawExifData + 4, (char*)&size_buff, 2); memcpy(rawExifData + 6, (char*)&exifShortHeader, 6); } memcpy(rawExifData + offset, payload.pData_, payload.size_); #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Display Hex Dump [size:" << (unsigned long)size << "]" << std::endl; std::cout << Internal::binaryToHex(rawExifData, size); #endif if (pos != -1) { XmpData xmpData; ByteOrder bo = ExifParser::decode(exifData_, payload.pData_ + pos, payload.size_ - pos); setByteOrder(bo); } else { #ifndef SUPPRESS_WARNINGS EXV_WARNING << "Failed to decode Exif metadata." << std::endl; #endif exifData_.clear(); } if (rawExifData) free(rawExifData); } else if (equalsWebPTag(chunkId, WEBP_CHUNK_HEADER_XMP)) { readOrThrow(*io_, payload.pData_, payload.size_, Exiv2::kerCorruptedMetadata); xmpPacket_.assign(reinterpret_cast<char*>(payload.pData_), payload.size_); if (xmpPacket_.size() > 0 && XmpParser::decode(xmpData_, xmpPacket_)) { #ifndef SUPPRESS_WARNINGS EXV_WARNING << "Failed to decode XMP metadata." << std::endl; #endif } else { #ifdef EXIV2_DEBUG_MESSAGES std::cout << "Display Hex Dump [size:" << (unsigned long)payload.size_ << "]" << std::endl; std::cout << Internal::binaryToHex(payload.pData_, payload.size_); #endif } } else { io_->seek(size, BasicIo::cur); } if ( io_->tell() % 2 ) io_->seek(+1, BasicIo::cur); } } /* =========================================== */ Image::AutoPtr newWebPInstance(BasicIo::AutoPtr io, bool /*create*/) { Image::AutoPtr image(new WebPImage(io)); if (!image->good()) { image.reset(); } return image; } bool isWebPType(BasicIo& iIo, bool /*advance*/) { if (iIo.size() < 12) { return false; } const int32_t len = 4; const unsigned char RiffImageId[4] = { 'R', 'I', 'F' ,'F'}; const unsigned char WebPImageId[4] = { 'W', 'E', 'B' ,'P'}; byte webp[len]; byte data[len]; byte riff[len]; iIo.read(riff, len); iIo.read(data, len); iIo.read(webp, len); bool matched_riff = (memcmp(riff, RiffImageId, len) == 0); bool matched_webp = (memcmp(webp, WebPImageId, len) == 0); iIo.seek(-12, BasicIo::cur); return matched_riff && matched_webp; } /*! @brief Function used to check equality of a Tags with a particular string (ignores case while comparing). @param buf Data buffer that will contain Tag to compare @param str char* Pointer to string @return Returns true if the buffer value is equal to string. */ bool WebPImage::equalsWebPTag(Exiv2::DataBuf& buf, const char* str) { for(int i = 0; i < 4; i++ ) if(toupper(buf.pData_[i]) != str[i]) return false; return true; } /*! @brief Function used to add missing EXIF & XMP flags to the feature section. @param iIo get BasicIo pointer to inject data @param has_xmp Verify if we have xmp data and set required flag @param has_exif Verify if we have exif data and set required flag @return Returns void */ void WebPImage::inject_VP8X(BasicIo& iIo, bool has_xmp, bool has_exif, bool has_alpha, bool has_icc, int width, int height) { byte size[4] = { 0x0A, 0x00, 0x00, 0x00 }; byte data[10] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE); iIo.write(size, WEBP_TAG_SIZE); if (has_alpha) { data[0] |= WEBP_VP8X_ALPHA_BIT; } if (has_icc) { data[0] |= WEBP_VP8X_ICC_BIT; } if (has_xmp) { data[0] |= WEBP_VP8X_XMP_BIT; } if (has_exif) { data[0] |= WEBP_VP8X_EXIF_BIT; } /* set width - stored in 24bits*/ int w = width - 1; data[4] = w & 0xFF; data[5] = (w >> 8) & 0xFF; data[6] = (w >> 16) & 0xFF; /* set height - stored in 24bits */ int h = height - 1; data[7] = h & 0xFF; data[8] = (h >> 8) & 0xFF; data[9] = (h >> 16) & 0xFF; iIo.write(data, 10); /* Handle inject an icc profile right after VP8X chunk */ if (has_icc) { byte size_buff[WEBP_TAG_SIZE]; ul2Data(size_buff, iccProfile_.size_, littleEndian); if (iIo.write((const byte*)WEBP_CHUNK_HEADER_VP8X, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (iIo.write(size_buff, WEBP_TAG_SIZE) != WEBP_TAG_SIZE) throw Error(kerImageWriteFailed); if (iIo.write(iccProfile_.pData_, iccProfile_.size_) != iccProfile_.size_) throw Error(kerImageWriteFailed); if (iIo.tell() % 2) { if (iIo.write(&WEBP_PAD_ODD, 1) != 1) throw Error(kerImageWriteFailed); } has_icc = false; } } long WebPImage::getHeaderOffset(byte* data, long data_size, byte* header, long header_size) { if (data_size < header_size) { return -1; } long pos = -1; for (long i=0; i < data_size - header_size; i++) { if (memcmp(header, &data[i], header_size) == 0) { pos = i; break; } } return pos; } } // namespace Exiv2
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_1010_0
crossvul-cpp_data_bad_434_2
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2016, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ /* Modification History: * Date Name Description * 07/15/99 helena Ported to HPUX 10/11 CC. */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "numfmtst.h" #include "unicode/currpinf.h" #include "unicode/dcfmtsym.h" #include "unicode/decimfmt.h" #include "unicode/localpointer.h" #include "unicode/ucurr.h" #include "unicode/ustring.h" #include "unicode/measfmt.h" #include "unicode/curramt.h" #include "unicode/strenum.h" #include "textfile.h" #include "tokiter.h" #include "charstr.h" #include "cstr.h" #include "putilimp.h" #include "winnmtst.h" #include <cmath> #include <float.h> #include <string.h> #include <stdlib.h> #include "cmemory.h" #include "cstring.h" #include "unicode/numsys.h" #include "fmtableimp.h" #include "numberformattesttuple.h" #include "unicode/msgfmt.h" #include "number_decimalquantity.h" #include "unicode/numberformatter.h" #if (U_PLATFORM == U_PF_AIX) || (U_PLATFORM == U_PF_OS390) // These should not be macros. If they are, // replace them with std::isnan and std::isinf #if defined(isnan) #undef isnan namespace std { bool isnan(double x) { return _isnan(x); } } #endif #if defined(isinf) #undef isinf namespace std { bool isinf(double x) { return _isinf(x); } } #endif #endif using icu::number::impl::DecimalQuantity; using namespace icu::number; //#define NUMFMTST_CACHE_DEBUG 1 #include "stdio.h" /* for sprintf */ // #include "iostream" // for cout //#define NUMFMTST_DEBUG 1 static const UChar EUR[] = {69,85,82,0}; // "EUR" static const UChar ISO_CURRENCY_USD[] = {0x55, 0x53, 0x44, 0}; // "USD" // ***************************************************************************** // class NumberFormatTest // ***************************************************************************** #define CHECK(status,str) if (U_FAILURE(status)) { errcheckln(status, UnicodeString("FAIL: ") + str + " - " + u_errorName(status)); return; } #define CHECK_DATA(status,str) if (U_FAILURE(status)) { dataerrln(UnicodeString("FAIL: ") + str + " - " + u_errorName(status)); return; } void NumberFormatTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* /*par*/ ) { TESTCASE_AUTO_BEGIN; TESTCASE_AUTO(TestCurrencySign); TESTCASE_AUTO(TestCurrency); TESTCASE_AUTO(TestParse); TESTCASE_AUTO(TestRounding487); TESTCASE_AUTO(TestQuotes); TESTCASE_AUTO(TestExponential); TESTCASE_AUTO(TestPatterns); // Upgrade to alphaWorks - liu 5/99 TESTCASE_AUTO(TestExponent); TESTCASE_AUTO(TestScientific); TESTCASE_AUTO(TestPad); TESTCASE_AUTO(TestPatterns2); TESTCASE_AUTO(TestSecondaryGrouping); TESTCASE_AUTO(TestSurrogateSupport); TESTCASE_AUTO(TestAPI); TESTCASE_AUTO(TestCurrencyObject); TESTCASE_AUTO(TestCurrencyPatterns); //TESTCASE_AUTO(TestDigitList); TESTCASE_AUTO(TestWhiteSpaceParsing); TESTCASE_AUTO(TestComplexCurrency); // This test removed because CLDR no longer uses choice formats in currency symbols. TESTCASE_AUTO(TestRegCurrency); TESTCASE_AUTO(TestSymbolsWithBadLocale); TESTCASE_AUTO(TestAdoptDecimalFormatSymbols); TESTCASE_AUTO(TestScientific2); TESTCASE_AUTO(TestScientificGrouping); TESTCASE_AUTO(TestInt64); TESTCASE_AUTO(TestPerMill); TESTCASE_AUTO(TestIllegalPatterns); TESTCASE_AUTO(TestCases); TESTCASE_AUTO(TestCurrencyNames); TESTCASE_AUTO(TestCurrencyAmount); TESTCASE_AUTO(TestCurrencyUnit); TESTCASE_AUTO(TestCoverage); TESTCASE_AUTO(TestLocalizedPatternSymbolCoverage); TESTCASE_AUTO(TestJB3832); TESTCASE_AUTO(TestHost); TESTCASE_AUTO(TestHostClone); TESTCASE_AUTO(TestCurrencyFormat); TESTCASE_AUTO(TestRounding); TESTCASE_AUTO(TestNonpositiveMultiplier); TESTCASE_AUTO(TestNumberingSystems); TESTCASE_AUTO(TestSpaceParsing); TESTCASE_AUTO(TestMultiCurrencySign); TESTCASE_AUTO(TestCurrencyFormatForMixParsing); TESTCASE_AUTO(TestMismatchedCurrencyFormatFail); TESTCASE_AUTO(TestDecimalFormatCurrencyParse); TESTCASE_AUTO(TestCurrencyIsoPluralFormat); TESTCASE_AUTO(TestCurrencyParsing); TESTCASE_AUTO(TestParseCurrencyInUCurr); TESTCASE_AUTO(TestFormatAttributes); TESTCASE_AUTO(TestFieldPositionIterator); TESTCASE_AUTO(TestDecimal); TESTCASE_AUTO(TestCurrencyFractionDigits); TESTCASE_AUTO(TestExponentParse); TESTCASE_AUTO(TestExplicitParents); TESTCASE_AUTO(TestLenientParse); TESTCASE_AUTO(TestAvailableNumberingSystems); TESTCASE_AUTO(TestRoundingPattern); TESTCASE_AUTO(Test9087); TESTCASE_AUTO(TestFormatFastpaths); TESTCASE_AUTO(TestFormattableSize); TESTCASE_AUTO(TestUFormattable); TESTCASE_AUTO(TestSignificantDigits); TESTCASE_AUTO(TestShowZero); TESTCASE_AUTO(TestCompatibleCurrencies); TESTCASE_AUTO(TestBug9936); TESTCASE_AUTO(TestParseNegativeWithFaLocale); TESTCASE_AUTO(TestParseNegativeWithAlternateMinusSign); TESTCASE_AUTO(TestCustomCurrencySignAndSeparator); TESTCASE_AUTO(TestParseSignsAndMarks); TESTCASE_AUTO(Test10419RoundingWith0FractionDigits); TESTCASE_AUTO(Test10468ApplyPattern); TESTCASE_AUTO(TestRoundingScientific10542); TESTCASE_AUTO(TestZeroScientific10547); TESTCASE_AUTO(TestAccountingCurrency); TESTCASE_AUTO(TestEquality); TESTCASE_AUTO(TestCurrencyUsage); TESTCASE_AUTO(TestDoubleLimit11439); TESTCASE_AUTO(TestGetAffixes); TESTCASE_AUTO(TestToPatternScientific11648); TESTCASE_AUTO(TestBenchmark); TESTCASE_AUTO(TestCtorApplyPatternDifference); TESTCASE_AUTO(TestFractionalDigitsForCurrency); TESTCASE_AUTO(TestFormatCurrencyPlural); TESTCASE_AUTO(Test11868); TESTCASE_AUTO(Test11739_ParseLongCurrency); TESTCASE_AUTO(Test13035_MultiCodePointPaddingInPattern); TESTCASE_AUTO(Test13737_ParseScientificStrict); TESTCASE_AUTO(Test10727_RoundingZero); TESTCASE_AUTO(Test11376_getAndSetPositivePrefix); TESTCASE_AUTO(Test11475_signRecognition); TESTCASE_AUTO(Test11640_getAffixes); TESTCASE_AUTO(Test11649_toPatternWithMultiCurrency); TESTCASE_AUTO(Test13327_numberingSystemBufferOverflow); TESTCASE_AUTO(Test13391_chakmaParsing); TESTCASE_AUTO(Test11735_ExceptionIssue); TESTCASE_AUTO(Test11035_FormatCurrencyAmount); TESTCASE_AUTO(Test11318_DoubleConversion); TESTCASE_AUTO(TestParsePercentRegression); TESTCASE_AUTO(TestMultiplierWithScale); TESTCASE_AUTO(TestFastFormatInt32); TESTCASE_AUTO(Test11646_Equality); TESTCASE_AUTO(TestParseNaN); TESTCASE_AUTO(Test11897_LocalizedPatternSeparator); TESTCASE_AUTO(Test13055_PercentageRounding); TESTCASE_AUTO(Test11839); TESTCASE_AUTO(Test10354); TESTCASE_AUTO(Test11645_ApplyPatternEquality); TESTCASE_AUTO(Test12567); TESTCASE_AUTO(Test11626_CustomizeCurrencyPluralInfo); TESTCASE_AUTO(Test20073_StrictPercentParseErrorIndex); TESTCASE_AUTO(Test13056_GroupingSize); TESTCASE_AUTO(Test11025_CurrencyPadding); TESTCASE_AUTO(Test11648_ExpDecFormatMalPattern); TESTCASE_AUTO(Test11649_DecFmtCurrencies); TESTCASE_AUTO(Test13148_ParseGroupingSeparators); TESTCASE_AUTO(Test12753_PatternDecimalPoint); TESTCASE_AUTO(Test11647_PatternCurrencySymbols); TESTCASE_AUTO(Test11913_BigDecimal); TESTCASE_AUTO(Test11020_RoundingInScientificNotation); TESTCASE_AUTO(Test11640_TripleCurrencySymbol); TESTCASE_AUTO(Test13763_FieldPositionIteratorOffset); TESTCASE_AUTO(Test13777_ParseLongNameNonCurrencyMode); TESTCASE_AUTO(Test13804_EmptyStringsWhenParsing); TESTCASE_AUTO(Test20037_ScientificIntegerOverflow); TESTCASE_AUTO(Test13840_ParseLongStringCrash); TESTCASE_AUTO(Test13850_EmptyStringCurrency); TESTCASE_AUTO_END; } // ------------------------------------- // Test API (increase code coverage) void NumberFormatTest::TestAPI(void) { logln("Test API"); UErrorCode status = U_ZERO_ERROR; NumberFormat *test = NumberFormat::createInstance("root", status); if(U_FAILURE(status)) { dataerrln("unable to create format object - %s", u_errorName(status)); } if(test != NULL) { test->setMinimumIntegerDigits(10); test->setMaximumIntegerDigits(1); test->setMinimumFractionDigits(10); test->setMaximumFractionDigits(1); UnicodeString result; FieldPosition pos; Formattable bla("Paja Patak"); // Donald Duck for non Serbian speakers test->format(bla, result, pos, status); if(U_SUCCESS(status)) { errln("Yuck... Formatted a duck... As a number!"); } else { status = U_ZERO_ERROR; } result.remove(); int64_t ll = 12; test->format(ll, result); assertEquals("format int64_t error", u"2.0", result); test->setMinimumIntegerDigits(4); test->setMinimumFractionDigits(4); result.remove(); test->format(ll, result); assertEquals("format int64_t error", u"0,012.0000", result); ParsePosition ppos; LocalPointer<CurrencyAmount> currAmt(test->parseCurrency("",ppos)); // old test for (U_FAILURE(status)) was bogus here, method does not set status! if (ppos.getIndex()) { errln("Parsed empty string as currency"); } delete test; } } class StubNumberFormat :public NumberFormat{ public: StubNumberFormat(){}; virtual UnicodeString& format(double ,UnicodeString& appendTo,FieldPosition& ) const { return appendTo; } virtual UnicodeString& format(int32_t ,UnicodeString& appendTo,FieldPosition& ) const { return appendTo.append((UChar)0x0033); } virtual UnicodeString& format(int64_t number,UnicodeString& appendTo,FieldPosition& pos) const { return NumberFormat::format(number, appendTo, pos); } virtual UnicodeString& format(const Formattable& , UnicodeString& appendTo, FieldPosition& , UErrorCode& ) const { return appendTo; } virtual void parse(const UnicodeString& , Formattable& , ParsePosition& ) const {} virtual void parse( const UnicodeString& , Formattable& , UErrorCode& ) const {} virtual UClassID getDynamicClassID(void) const { static char classID = 0; return (UClassID)&classID; } virtual Format* clone() const {return NULL;} }; void NumberFormatTest::TestCoverage(void){ StubNumberFormat stub; UnicodeString agent("agent"); FieldPosition pos; int64_t num = 4; if (stub.format(num, agent, pos) != UnicodeString("agent3")){ errln("NumberFormat::format(int64, UnicodString&, FieldPosition&) should delegate to (int32, ,)"); }; } void NumberFormatTest::TestLocalizedPatternSymbolCoverage() { IcuTestErrorCode errorCode(*this, "TestLocalizedPatternSymbolCoverage"); // Ticket #12961: DecimalFormat::toLocalizedPattern() is not working as designed. DecimalFormatSymbols dfs(errorCode); dfs.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u'⁖'); dfs.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u'⁘'); dfs.setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, u'⁙'); dfs.setSymbol(DecimalFormatSymbols::kDigitSymbol, u'▰'); dfs.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, u'໐'); dfs.setSymbol(DecimalFormatSymbols::kSignificantDigitSymbol, u'⁕'); dfs.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u'†'); dfs.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u'‡'); dfs.setSymbol(DecimalFormatSymbols::kPercentSymbol, u'⁜'); dfs.setSymbol(DecimalFormatSymbols::kPerMillSymbol, u'‱'); dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"⁑⁑"); // tests multi-char sequence dfs.setSymbol(DecimalFormatSymbols::kPadEscapeSymbol, u'⁂'); { UnicodeString standardPattern(u"#,##0.05+%;#,##0.05-%"); UnicodeString localizedPattern(u"▰⁖▰▰໐⁘໐໕†⁜⁙▰⁖▰▰໐⁘໐໕‡⁜"); DecimalFormat df1("#", new DecimalFormatSymbols(dfs), errorCode); df1.applyPattern(standardPattern, errorCode); DecimalFormat df2("#", new DecimalFormatSymbols(dfs), errorCode); df2.applyLocalizedPattern(localizedPattern, errorCode); assertTrue("DecimalFormat instances should be equal", df1 == df2); UnicodeString p2; assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern(p2)); UnicodeString lp1; assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern(lp1)); } { UnicodeString standardPattern(u"* @@@E0‰"); UnicodeString localizedPattern(u"⁂ ⁕⁕⁕⁑⁑໐‱"); DecimalFormat df1("#", new DecimalFormatSymbols(dfs), errorCode); df1.applyPattern(standardPattern, errorCode); DecimalFormat df2("#", new DecimalFormatSymbols(dfs), errorCode); df2.applyLocalizedPattern(localizedPattern, errorCode); assertTrue("DecimalFormat instances should be equal", df1 == df2); UnicodeString p2; assertEquals("toPattern should match on localizedPattern instance", standardPattern, df2.toPattern(p2)); UnicodeString lp1; assertEquals("toLocalizedPattern should match on standardPattern instance", localizedPattern, df1.toLocalizedPattern(lp1)); } } // Test various patterns void NumberFormatTest::TestPatterns(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "FAIL: Could not construct DecimalFormatSymbols - %s", u_errorName(status)); return; } const char* pat[] = { "#.#", "#.", ".#", "#" }; int32_t pat_length = UPRV_LENGTHOF(pat); const char* newpat[] = { "0.#", "0.", "#.0", "0" }; const char* num[] = { "0", "0.", ".0", "0" }; for (int32_t i=0; i<pat_length; ++i) { status = U_ZERO_ERROR; DecimalFormat fmt(pat[i], sym, status); if (U_FAILURE(status)) { errln((UnicodeString)"FAIL: DecimalFormat constructor failed for " + pat[i]); continue; } UnicodeString newp; fmt.toPattern(newp); if (!(newp == newpat[i])) errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] + "; " + newp + " seen instead"); UnicodeString s; (*(NumberFormat*)&fmt).format((int32_t)0, s); if (!(s == num[i])) { errln((UnicodeString)"FAIL: Pattern " + pat[i] + " should format zero as " + num[i] + "; " + s + " seen instead"); logln((UnicodeString)"Min integer digits = " + fmt.getMinimumIntegerDigits()); } } } /* icu_2_4::DigitList::operator== 0 0 2 icuuc24d.dll digitlst.cpp Doug icu_2_4::DigitList::append 0 0 4 icuin24d.dll digitlst.h Doug icu_2_4::DigitList::operator!= 0 0 1 icuuc24d.dll digitlst.h Doug */ /* void NumberFormatTest::TestDigitList(void) { // API coverage for DigitList DigitList list1; list1.append('1'); list1.fDecimalAt = 1; DigitList list2; list2.set((int32_t)1); if (list1 != list2) { errln("digitlist append, operator!= or set failed "); } if (!(list1 == list2)) { errln("digitlist append, operator== or set failed "); } } */ // ------------------------------------- // Test exponential pattern void NumberFormatTest::TestExponential(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "FAIL: Bad status returned by DecimalFormatSymbols ct - %s", u_errorName(status)); return; } const char* pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" }; int32_t pat_length = UPRV_LENGTHOF(pat); // The following #if statements allow this test to be built and run on // platforms that do not have standard IEEE numerics. For example, // S/390 doubles have an exponent range of -78 to +75. For the // following #if statements to work, float.h must define // DBL_MAX_10_EXP to be a compile-time constant. // This section may be expanded as needed. #if DBL_MAX_10_EXP > 300 double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 }; int32_t val_length = UPRV_LENGTHOF(val); const char* valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271", // 00.000E00 "12.340E-03", "12.346E07", "12.300E299", "-31.416E-272", // ##0.######E000 "12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" }; double valParse[] = { 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123460000, 1.23E300, -3.1416E-271, 0.01234, 123456800, 1.23E300, -3.141593E-271, 0.01234, 123500000, 1.23E300, -3.142E-271, }; #elif DBL_MAX_10_EXP > 70 double val[] = { 0.01234, 123456789, 1.23e70, -3.141592653e-71 }; int32_t val_length = UPRV_LENGTHOF(val); char* valFormat[] = { // 0.####E0 "1.234E-2", "1.2346E8", "1.23E70", "-3.1416E-71", // 00.000E00 "12.340E-03", "12.346E07", "12.300E69", "-31.416E-72", // ##0.######E000 "12.34E-003", "123.4568E006", "12.3E069", "-31.41593E-072", // 0.###E0;[0.###E0] "1.234E-2", "1.235E8", "1.23E70", "[3.142E-71]" }; double valParse[] = { 0.01234, 123460000, 1.23E70, -3.1416E-71, 0.01234, 123460000, 1.23E70, -3.1416E-71, 0.01234, 123456800, 1.23E70, -3.141593E-71, 0.01234, 123500000, 1.23E70, -3.142E-71, }; #else // Don't test double conversion double* val = 0; int32_t val_length = 0; char** valFormat = 0; double* valParse = 0; logln("Warning: Skipping double conversion tests"); #endif int32_t lval[] = { 0, -1, 1, 123456789 }; int32_t lval_length = UPRV_LENGTHOF(lval); const char* lvalFormat[] = { // 0.####E0 "0E0", "-1E0", "1E0", "1.2346E8", // 00.000E00 "00.000E00", "-10.000E-01", "10.000E-01", "12.346E07", // ##0.######E000 "0E000", "-1E000", "1E000", "123.4568E006", // 0.###E0;[0.###E0] "0E0", "[1E0]", "1E0", "1.235E8" }; int32_t lvalParse[] = { 0, -1, 1, 123460000, 0, -1, 1, 123460000, 0, -1, 1, 123456800, 0, -1, 1, 123500000, }; int32_t ival = 0, ilval = 0; for (int32_t p=0; p<pat_length; ++p) { DecimalFormat fmt(pat[p], sym, status); if (U_FAILURE(status)) { errln("FAIL: Bad status returned by DecimalFormat ct"); continue; } UnicodeString pattern; logln((UnicodeString)"Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern(pattern) + "\""); int32_t v; for (v=0; v<val_length; ++v) { UnicodeString s; (*(NumberFormat*)&fmt).format(val[v], s); logln((UnicodeString)" " + val[v] + " -format-> " + s); if (s != valFormat[v+ival]) errln((UnicodeString)"FAIL: Expected " + valFormat[v+ival]); ParsePosition pos(0); Formattable af; fmt.parse(s, af, pos); double a; UBool useEpsilon = FALSE; if (af.getType() == Formattable::kLong) a = af.getLong(); else if (af.getType() == Formattable::kDouble) { a = af.getDouble(); #if U_PF_OS390 <= U_PLATFORM && U_PLATFORM <= U_PF_OS400 // S/390 will show a failure like this: //| -3.141592652999999e-271 -format-> -3.1416E-271 //| -parse-> -3.1416e-271 //| FAIL: Expected -3.141599999999999e-271 // To compensate, we use an epsilon-based equality // test on S/390 only. We don't want to do this in // general because it's less exacting. useEpsilon = TRUE; #endif } else { errln(UnicodeString("FAIL: Non-numeric Formattable returned: ") + pattern + " " + s); continue; } if (pos.getIndex() == s.length()) { logln((UnicodeString)" -parse-> " + a); // Use epsilon comparison as necessary if ((useEpsilon && (uprv_fabs(a - valParse[v+ival]) / a > (2*DBL_EPSILON))) || (!useEpsilon && a != valParse[v+ival])) { errln((UnicodeString)"FAIL: Expected " + valParse[v+ival] + " but got " + a + " on input " + s); } } else { errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); errln((UnicodeString)" should be (" + s.length() + " chars) -> " + valParse[v+ival]); } } for (v=0; v<lval_length; ++v) { UnicodeString s; (*(NumberFormat*)&fmt).format(lval[v], s); logln((UnicodeString)" " + lval[v] + "L -format-> " + s); if (s != lvalFormat[v+ilval]) errln((UnicodeString)"ERROR: Expected " + lvalFormat[v+ilval] + " Got: " + s); ParsePosition pos(0); Formattable af; fmt.parse(s, af, pos); if (af.getType() == Formattable::kLong || af.getType() == Formattable::kInt64) { UErrorCode status = U_ZERO_ERROR; int32_t a = af.getLong(status); if (pos.getIndex() == s.length()) { logln((UnicodeString)" -parse-> " + a); if (a != lvalParse[v+ilval]) errln((UnicodeString)"FAIL: Expected " + lvalParse[v+ilval] + " but got " + a); } else errln((UnicodeString)"FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a); } else errln((UnicodeString)"FAIL: Non-long Formattable returned for " + s + " Double: " + af.getDouble() + ", Long: " + af.getLong()); } ival += val_length; ilval += lval_length; } } void NumberFormatTest::TestScientific2() { // jb 2552 UErrorCode status = U_ZERO_ERROR; DecimalFormat* fmt = (DecimalFormat*)NumberFormat::createCurrencyInstance("en_US", status); if (U_SUCCESS(status)) { double num = 12.34; expect(*fmt, num, "$12.34"); fmt->setScientificNotation(TRUE); expect(*fmt, num, "$1.23E1"); fmt->setScientificNotation(FALSE); expect(*fmt, num, "$12.34"); } delete fmt; } void NumberFormatTest::TestScientificGrouping() { // jb 2552 UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("##0.00E0",status); if (assertSuccess("", status, true, __FILE__, __LINE__)) { expect(fmt, .01234, "12.3E-3"); expect(fmt, .1234, "123E-3"); expect(fmt, 1.234, "1.23E0"); expect(fmt, 12.34, "12.3E0"); expect(fmt, 123.4, "123E0"); expect(fmt, 1234., "1.23E3"); } } /*static void setFromString(DigitList& dl, const char* str) { char c; UBool decimalSet = FALSE; dl.clear(); while ((c = *str++)) { if (c == '-') { dl.fIsPositive = FALSE; } else if (c == '+') { dl.fIsPositive = TRUE; } else if (c == '.') { dl.fDecimalAt = dl.fCount; decimalSet = TRUE; } else { dl.append(c); } } if (!decimalSet) { dl.fDecimalAt = dl.fCount; } }*/ void NumberFormatTest::TestInt64() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("#.#E0",status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } fmt.setMaximumFractionDigits(20); if (U_SUCCESS(status)) { expect(fmt, (Formattable)(int64_t)0, "0E0"); expect(fmt, (Formattable)(int64_t)-1, "-1E0"); expect(fmt, (Formattable)(int64_t)1, "1E0"); expect(fmt, (Formattable)(int64_t)2147483647, "2.147483647E9"); expect(fmt, (Formattable)((int64_t)-2147483647-1), "-2.147483648E9"); expect(fmt, (Formattable)(int64_t)U_INT64_MAX, "9.223372036854775807E18"); expect(fmt, (Formattable)(int64_t)U_INT64_MIN, "-9.223372036854775808E18"); } // also test digitlist /* int64_t int64max = U_INT64_MAX; int64_t int64min = U_INT64_MIN; const char* int64maxstr = "9223372036854775807"; const char* int64minstr = "-9223372036854775808"; UnicodeString fail("fail: "); // test max int64 value DigitList dl; setFromString(dl, int64maxstr); { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + int64maxstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != int64max) { errln(fail + int64maxstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != int64max) { errln(fail + int64maxstr); } } // test negative of max int64 value (1 shy of min int64 value) dl.fIsPositive = FALSE; { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + "-" + int64maxstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != -int64max) { errln(fail + "-" + int64maxstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != -int64max) { errln(fail + "-" + int64maxstr); } } // test min int64 value setFromString(dl, int64minstr); { if (!dl.fitsIntoInt64(FALSE)) { errln(fail + "-" + int64minstr + " didn't fit"); } int64_t int64Value = dl.getInt64(); if (int64Value != int64min) { errln(fail + int64minstr); } dl.set(int64Value); int64Value = dl.getInt64(); if (int64Value != int64min) { errln(fail + int64minstr); } } // test negative of min int 64 value (1 more than max int64 value) dl.fIsPositive = TRUE; // won't fit { if (dl.fitsIntoInt64(FALSE)) { errln(fail + "-(" + int64minstr + ") didn't fit"); } }*/ } // ------------------------------------- // Test the handling of quotes void NumberFormatTest::TestQuotes(void) { UErrorCode status = U_ZERO_ERROR; UnicodeString *pat; DecimalFormatSymbols *sym = new DecimalFormatSymbols(Locale::getUS(), status); if (U_FAILURE(status)) { errcheckln(status, "Fail to create DecimalFormatSymbols - %s", u_errorName(status)); delete sym; return; } pat = new UnicodeString("a'fo''o'b#"); DecimalFormat *fmt = new DecimalFormat(*pat, *sym, status); UnicodeString s; ((NumberFormat*)fmt)->format((int32_t)123, s); logln((UnicodeString)"Pattern \"" + *pat + "\""); logln((UnicodeString)" Format 123 -> " + escape(s)); if (!(s=="afo'ob123")) errln((UnicodeString)"FAIL: Expected afo'ob123"); s.truncate(0); delete fmt; delete pat; pat = new UnicodeString("a''b#"); fmt = new DecimalFormat(*pat, *sym, status); ((NumberFormat*)fmt)->format((int32_t)123, s); logln((UnicodeString)"Pattern \"" + *pat + "\""); logln((UnicodeString)" Format 123 -> " + escape(s)); if (!(s=="a'b123")) errln((UnicodeString)"FAIL: Expected a'b123"); delete fmt; delete pat; delete sym; } /** * Test the handling of the currency symbol in patterns. */ void NumberFormatTest::TestCurrencySign(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale::getUS(), status); UnicodeString pat; UChar currency = 0x00A4; if (U_FAILURE(status)) { errcheckln(status, "Fail to create DecimalFormatSymbols - %s", u_errorName(status)); delete sym; return; } // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append("#,##0.00;-"). append(currency).append("#,##0.00"); DecimalFormat *fmt = new DecimalFormat(pat, *sym, status); UnicodeString s; ((NumberFormat*)fmt)->format(1234.56, s); pat.truncate(0); logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); if (s != "$1,234.56") dataerrln((UnicodeString)"FAIL: Expected $1,234.56"); s.truncate(0); ((NumberFormat*)fmt)->format(- 1234.56, s); logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); if (s != "-$1,234.56") dataerrln((UnicodeString)"FAIL: Expected -$1,234.56"); delete fmt; pat.truncate(0); // "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00" pat.append(currency).append(currency). append(" #,##0.00;"). append(currency).append(currency). append(" -#,##0.00"); fmt = new DecimalFormat(pat, *sym, status); s.truncate(0); ((NumberFormat*)fmt)->format(1234.56, s); logln((UnicodeString)"Pattern \"" + fmt->toPattern(pat) + "\""); logln((UnicodeString)" Format " + 1234.56 + " -> " + escape(s)); if (s != "USD 1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD 1,234.56"); s.truncate(0); ((NumberFormat*)fmt)->format(-1234.56, s); logln((UnicodeString)" Format " + (-1234.56) + " -> " + escape(s)); if (s != "USD -1,234.56") dataerrln((UnicodeString)"FAIL: Expected USD -1,234.56"); delete fmt; delete sym; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + u_errorName(status)); } // ------------------------------------- static UChar toHexString(int32_t i) { return (UChar)(i + (i < 10 ? 0x30 : (0x41 - 10))); } UnicodeString& NumberFormatTest::escape(UnicodeString& s) { UnicodeString buf; for (int32_t i=0; i<s.length(); ++i) { UChar c = s[(int32_t)i]; if (c <= (UChar)0x7F) buf += c; else { buf += (UChar)0x5c; buf += (UChar)0x55; buf += toHexString((c & 0xF000) >> 12); buf += toHexString((c & 0x0F00) >> 8); buf += toHexString((c & 0x00F0) >> 4); buf += toHexString(c & 0x000F); } } return (s = buf); } // ------------------------------------- static const char* testCases[][2]= { /* locale ID */ /* expected */ {"ca_ES_PREEURO", "\\u20A7\\u00A01.150" }, {"de_LU_PREEURO", "1,150\\u00A0F" }, {"el_GR_PREEURO", "1.150,50\\u00A0\\u0394\\u03C1\\u03C7" }, {"en_BE_PREEURO", "1.150,50\\u00A0BEF" }, {"es_ES_PREEURO", "1.150\\u00A0\\u20A7" }, {"eu_ES_PREEURO", "\\u20A7\\u00A01.150" }, {"gl_ES_PREEURO", "1.150\\u00A0\\u20A7" }, {"it_IT_PREEURO", "ITL\\u00A01.150" }, {"pt_PT_PREEURO", "1,150$50\\u00A0\\u200B"}, // per cldrbug 7670 {"en_US@currency=JPY", "\\u00A51,150"}, {"en_US@currency=jpy", "\\u00A51,150"}, {"en-US-u-cu-jpy", "\\u00A51,150"} }; /** * Test localized currency patterns. */ void NumberFormatTest::TestCurrency(void) { UErrorCode status = U_ZERO_ERROR; NumberFormat* currencyFmt = NumberFormat::createCurrencyInstance(Locale::getCanadaFrench(), status); if (U_FAILURE(status)) { dataerrln("Error calling NumberFormat::createCurrencyInstance()"); return; } UnicodeString s; currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre ici a..........." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0$"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>$ but got " + s); delete currencyFmt; s.truncate(0); char loc[256]={0}; int len = uloc_canonicalize("de_DE_PREEURO", loc, 256, &status); (void)len; // Suppress unused variable warning. currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc),status); currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre en Allemagne a.." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0DM"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>DM but got " + s); delete currencyFmt; s.truncate(0); len = uloc_canonicalize("fr_FR_PREEURO", loc, 256, &status); currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc), status); currencyFmt->format(1.50, s); logln((UnicodeString)"Un pauvre en France a....." + s); if (!(s==CharsToUnicodeString("1,50\\u00A0F"))) errln((UnicodeString)"FAIL: Expected 1,50<nbsp>F"); delete currencyFmt; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + (int32_t)status); for(int i=0; i < UPRV_LENGTHOF(testCases); i++){ status = U_ZERO_ERROR; const char *localeID = testCases[i][0]; UnicodeString expected(testCases[i][1], -1, US_INV); expected = expected.unescape(); s.truncate(0); char loc[256]={0}; uloc_canonicalize(localeID, loc, 256, &status); currencyFmt = NumberFormat::createCurrencyInstance(Locale(loc), status); if(U_FAILURE(status)){ errln("Could not create currency formatter for locale %s",localeID); continue; } currencyFmt->format(1150.50, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln((UnicodeString)"FAIL: Status " + (int32_t)status); } delete currencyFmt; } } // ------------------------------------- /** * Test the Currency object handling, new as of ICU 2.2. */ void NumberFormatTest::TestCurrencyObject() { UErrorCode ec = U_ZERO_ERROR; NumberFormat* fmt = NumberFormat::createCurrencyInstance(Locale::getUS(), ec); if (U_FAILURE(ec)) { dataerrln("FAIL: getCurrencyInstance(US) - %s", u_errorName(ec)); delete fmt; return; } Locale null("", "", ""); expectCurrency(*fmt, null, 1234.56, "$1,234.56"); expectCurrency(*fmt, Locale::getFrance(), 1234.56, CharsToUnicodeString("\\u20AC1,234.56")); // Euro expectCurrency(*fmt, Locale::getJapan(), 1234.56, CharsToUnicodeString("\\u00A51,235")); // Yen expectCurrency(*fmt, Locale("fr", "CH", ""), 1234.56, "CHF 1,234.56"); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(*fmt, Locale::getUS(), 1234.56, "$1,234.56"); delete fmt; fmt = NumberFormat::createCurrencyInstance(Locale::getFrance(), ec); if (U_FAILURE(ec)) { errln("FAIL: getCurrencyInstance(FRANCE)"); delete fmt; return; } expectCurrency(*fmt, null, 1234.56, CharsToUnicodeString("1\\u202F234,56 \\u20AC")); expectCurrency(*fmt, Locale::getJapan(), 1234.56, CharsToUnicodeString("1\\u202F235 JPY")); // Yen expectCurrency(*fmt, Locale("fr", "CH", ""), 1234.56, CharsToUnicodeString("1\\u202F234,56 CHF")); // no more 0.05 rounding here, see cldrbug 5548 expectCurrency(*fmt, Locale::getUS(), 1234.56, CharsToUnicodeString("1\\u202F234,56 $US")); expectCurrency(*fmt, Locale::getFrance(), 1234.56, CharsToUnicodeString("1\\u202F234,56 \\u20AC")); // Euro delete fmt; } // ------------------------------------- /** * Do rudimentary testing of parsing. */ void NumberFormatTest::TestParse(void) { UErrorCode status = U_ZERO_ERROR; UnicodeString arg("0"); DecimalFormat* format = new DecimalFormat("00", status); //try { Formattable n; format->parse(arg, n, status); logln((UnicodeString)"parse(" + arg + ") = " + n.getLong()); if (n.getType() != Formattable::kLong || n.getLong() != 0) errln((UnicodeString)"FAIL: Expected 0"); delete format; if (U_FAILURE(status)) errcheckln(status, (UnicodeString)"FAIL: Status " + u_errorName(status)); //} //catch(Exception e) { // errln((UnicodeString)"Exception caught: " + e); //} } // ------------------------------------- static const char *lenientAffixTestCases[] = { "(1)", "( 1)", "(1 )", "( 1 )" }; static const char *lenientMinusTestCases[] = { "-5", "\\u22125", "\\u27965" }; static const char *lenientCurrencyTestCases[] = { "$1,000", "$ 1,000", "$1000", "$ 1000", "$1 000.00", "$ 1 000.00", "$ 1\\u00A0000.00", "1000.00" }; // changed from () to - per cldrbug 5674 static const char *lenientNegativeCurrencyTestCases[] = { "-$1,000", "-$ 1,000", "-$1000", "-$ 1000", "-$1 000.00", "-$ 1 000.00", "- $ 1,000.00 ", "-$ 1\\u00A0000.00", "-1000.00" }; static const char *lenientPercentTestCases[] = { "25%", " 25%", " 25 %", "25 %", "25\\u00A0%", "25" }; static const char *lenientNegativePercentTestCases[] = { "-25%", " -25%", " - 25%", "- 25 %", " - 25 %", "-25 %", "-25\\u00A0%", "-25", "- 25" }; static const char *strictFailureTestCases[] = { " 1000", "10,00", "1,000,.0" }; /** * Test lenient parsing. */ void NumberFormatTest::TestLenientParse(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormat *format = new DecimalFormat("(#,##0)", status); Formattable n; if (format == NULL || U_FAILURE(status)) { dataerrln("Unable to create DecimalFormat (#,##0) - %s", u_errorName(status)); } else { format->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientAffixTestCases); t += 1) { UnicodeString testCase = ctou(lenientAffixTestCases[t]); format->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != 1) { dataerrln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientAffixTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete format; } Locale en_US("en_US"); Locale sv_SE("sv_SE"); NumberFormat *mFormat = NumberFormat::createInstance(sv_SE, UNUM_DECIMAL, status); if (mFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (sv_SE, UNUM_DECIMAL) - %s", u_errorName(status)); } else { mFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(lenientMinusTestCases); t += 1) { UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete mFormat; } mFormat = NumberFormat::createInstance(en_US, UNUM_DECIMAL, status); if (mFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US, UNUM_DECIMAL) - %s", u_errorName(status)); } else { mFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(lenientMinusTestCases); t += 1) { UnicodeString testCase = ctou(lenientMinusTestCases[t]); mFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) || n.getType() != Formattable::kLong || n.getLong() != -5) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientMinusTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete mFormat; } NumberFormat *cFormat = NumberFormat::createInstance(en_US, UNUM_CURRENCY, status); if (cFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US, UNUM_CURRENCY) - %s", u_errorName(status)); } else { cFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientCurrencyTestCases); t += 1) { UnicodeString testCase = ctou(lenientCurrencyTestCases[t]); cFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientCurrencyTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } for (int32_t t = 0; t < UPRV_LENGTHOF (lenientNegativeCurrencyTestCases); t += 1) { UnicodeString testCase = ctou(lenientNegativeCurrencyTestCases[t]); cFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != -1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativeCurrencyTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete cFormat; } NumberFormat *pFormat = NumberFormat::createPercentInstance(en_US, status); if (pFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat::createPercentInstance (en_US) - %s", u_errorName(status)); } else { pFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF (lenientPercentTestCases); t += 1) { UnicodeString testCase = ctou(lenientPercentTestCases[t]); pFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != 0.25) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientPercentTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } } for (int32_t t = 0; t < UPRV_LENGTHOF (lenientNegativePercentTestCases); t += 1) { UnicodeString testCase = ctou(lenientNegativePercentTestCases[t]); pFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getDouble()); if (U_FAILURE(status) ||n.getType() != Formattable::kDouble || n.getDouble() != -0.25) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) lenientNegativePercentTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status) + "; got: " + n.getDouble(status)); status = U_ZERO_ERROR; } } delete pFormat; } // Test cases that should fail with a strict parse and pass with a // lenient parse. NumberFormat *nFormat = NumberFormat::createInstance(en_US, status); if (nFormat == NULL || U_FAILURE(status)) { dataerrln("Unable to create NumberFormat (en_US) - %s", u_errorName(status)); } else { // first, make sure that they fail with a strict parse for (int32_t t = 0; t < UPRV_LENGTHOF(strictFailureTestCases); t += 1) { UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (! U_FAILURE(status)) { errln((UnicodeString)"Strict Parse succeeded for \"" + (UnicodeString) strictFailureTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); } status = U_ZERO_ERROR; } // then, make sure that they pass with a lenient parse nFormat->setLenient(TRUE); for (int32_t t = 0; t < UPRV_LENGTHOF(strictFailureTestCases); t += 1) { UnicodeString testCase = ctou(strictFailureTestCases[t]); nFormat->parse(testCase, n, status); logln((UnicodeString)"parse(" + testCase + ") = " + n.getLong()); if (U_FAILURE(status) ||n.getType() != Formattable::kLong || n.getLong() != 1000) { errln((UnicodeString)"Lenient parse failed for \"" + (UnicodeString) strictFailureTestCases[t] + (UnicodeString) "\"; error code = " + u_errorName(status)); status = U_ZERO_ERROR; } } delete nFormat; } } // ------------------------------------- /** * Test proper rounding by the format method. */ void NumberFormatTest::TestRounding487(void) { UErrorCode status = U_ZERO_ERROR; NumberFormat *nf = NumberFormat::createInstance(status); if (U_FAILURE(status)) { dataerrln("Error calling NumberFormat::createInstance()"); return; } roundingTest(*nf, 0.00159999, 4, "0.0016"); roundingTest(*nf, 0.00995, 4, "0.01"); roundingTest(*nf, 12.3995, 3, "12.4"); roundingTest(*nf, 12.4999, 0, "12"); roundingTest(*nf, - 19.5, 0, "-20"); delete nf; if (U_FAILURE(status)) errln((UnicodeString)"FAIL: Status " + (int32_t)status); } /** * Test the functioning of the secondary grouping value. */ void NumberFormatTest::TestSecondaryGrouping(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols ct"); DecimalFormat f("#,##,###", US, status); CHECK(status, "DecimalFormat ct"); expect2(f, (int32_t)123456789L, "12,34,56,789"); expectPat(f, "#,##,##0"); f.applyPattern("#,###", status); CHECK(status, "applyPattern"); f.setSecondaryGroupingSize(4); expect2(f, (int32_t)123456789L, "12,3456,789"); expectPat(f, "#,####,##0"); NumberFormat *g = NumberFormat::createInstance(Locale("hi", "IN"), status); CHECK_DATA(status, "createInstance(hi_IN)"); UnicodeString out; int32_t l = (int32_t)1876543210L; g->format(l, out); delete g; // expect "1,87,65,43,210", but with Hindi digits // 01234567890123 UBool ok = TRUE; if (out.length() != 14) { ok = FALSE; } else { for (int32_t i=0; i<out.length(); ++i) { UBool expectGroup = FALSE; switch (i) { case 1: case 4: case 7: case 10: expectGroup = TRUE; break; } // Later -- fix this to get the actual grouping // character from the resource bundle. UBool isGroup = (out.charAt(i) == 0x002C); if (isGroup != expectGroup) { ok = FALSE; break; } } } if (!ok) { errln((UnicodeString)"FAIL Expected " + l + " x hi_IN -> \"1,87,65,43,210\" (with Hindi digits), got \"" + escape(out) + "\""); } else { logln((UnicodeString)"Ok " + l + " x hi_IN -> \"" + escape(out) + "\""); } } void NumberFormatTest::TestWhiteSpaceParsing(void) { UErrorCode ec = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), ec); DecimalFormat fmt("a b#0c ", US, ec); if (U_FAILURE(ec)) { errcheckln(ec, "FAIL: Constructor - %s", u_errorName(ec)); return; } // From ICU 62, flexible whitespace needs lenient mode fmt.setLenient(TRUE); int32_t n = 1234; expect(fmt, "a b1234c ", n); expect(fmt, "a b1234c ", n); } /** * Test currencies whose display name is a ChoiceFormat. */ void NumberFormatTest::TestComplexCurrency() { // UErrorCode ec = U_ZERO_ERROR; // Locale loc("kn", "IN", ""); // NumberFormat* fmt = NumberFormat::createCurrencyInstance(loc, ec); // if (U_SUCCESS(ec)) { // expect2(*fmt, 1.0, CharsToUnicodeString("Re.\\u00A01.00")); // Use .00392625 because that's 2^-8. Any value less than 0.005 is fine. // expect(*fmt, 1.00390625, CharsToUnicodeString("Re.\\u00A01.00")); // tricky // expect2(*fmt, 12345678.0, CharsToUnicodeString("Rs.\\u00A01,23,45,678.00")); // expect2(*fmt, 0.5, CharsToUnicodeString("Rs.\\u00A00.50")); // expect2(*fmt, -1.0, CharsToUnicodeString("-Re.\\u00A01.00")); // expect2(*fmt, -10.0, CharsToUnicodeString("-Rs.\\u00A010.00")); // } else { // errln("FAIL: getCurrencyInstance(kn_IN)"); // } // delete fmt; } // ------------------------------------- void NumberFormatTest::roundingTest(NumberFormat& nf, double x, int32_t maxFractionDigits, const char* expected) { nf.setMaximumFractionDigits(maxFractionDigits); UnicodeString out; nf.format(x, out); logln((UnicodeString)"" + x + " formats with " + maxFractionDigits + " fractional digits to " + out); if (!(out==expected)) errln((UnicodeString)"FAIL: Expected " + expected); } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestExponent(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat fmt1(UnicodeString("0.###E0"), US, status); CHECK(status, "DecimalFormat(0.###E0)"); DecimalFormat fmt2(UnicodeString("0.###E+0"), US, status); CHECK(status, "DecimalFormat(0.###E+0)"); int32_t n = 1234; expect2(fmt1, n, "1.234E3"); expect2(fmt2, n, "1.234E+3"); expect(fmt1, "1.234E+3", n); // Either format should parse "E+3" } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestScientific(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); // Test pattern round-trip const char* PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" }; int32_t PAT_length = UPRV_LENGTHOF(PAT); int32_t DIGITS[] = { // min int, max int, min frac, max frac 1, 1, 0, 0, // "#E0" 1, 1, 0, 4, // "0.####E0" 2, 2, 3, 3, // "00.000E00" 1, 3, 0, 4, // "##0.####E000" 1, 1, 0, 3, // "0.###E0;[0.###E0]" }; for (int32_t i=0; i<PAT_length; ++i) { UnicodeString pat(PAT[i]); DecimalFormat df(pat, US, status); CHECK(status, "DecimalFormat constructor"); UnicodeString pat2; df.toPattern(pat2); if (pat == pat2) { logln(UnicodeString("Ok Pattern rt \"") + pat + "\" -> \"" + pat2 + "\""); } else { errln(UnicodeString("FAIL Pattern rt \"") + pat + "\" -> \"" + pat2 + "\""); } // Make sure digit counts match what we expect if (df.getMinimumIntegerDigits() != DIGITS[4*i] || df.getMaximumIntegerDigits() != DIGITS[4*i+1] || df.getMinimumFractionDigits() != DIGITS[4*i+2] || df.getMaximumFractionDigits() != DIGITS[4*i+3]) { errln(UnicodeString("FAIL \"" + pat + "\" min/max int; min/max frac = ") + df.getMinimumIntegerDigits() + "/" + df.getMaximumIntegerDigits() + ";" + df.getMinimumFractionDigits() + "/" + df.getMaximumFractionDigits() + ", expect " + DIGITS[4*i] + "/" + DIGITS[4*i+1] + ";" + DIGITS[4*i+2] + "/" + DIGITS[4*i+3]); } } // Test the constructor for default locale. We have to // manually set the default locale, as there is no // guarantee that the default locale has the same // scientific format. Locale def = Locale::getDefault(); Locale::setDefault(Locale::getUS(), status); expect2(NumberFormat::createScientificInstance(status), 12345.678901, "1.2345678901E4", status); Locale::setDefault(def, status); expect2(new DecimalFormat("#E0", US, status), 12345.0, "1.2345E4", status); expect(new DecimalFormat("0E0", US, status), 12345.0, "1E4", status); expect2(NumberFormat::createScientificInstance(Locale::getUS(), status), 12345.678901, "1.2345678901E4", status); expect(new DecimalFormat("##0.###E0", US, status), 12345.0, "12.34E3", status); expect(new DecimalFormat("##0.###E0", US, status), 12345.00001, "12.35E3", status); expect2(new DecimalFormat("##0.####E0", US, status), (int32_t) 12345, "12.345E3", status); expect2(NumberFormat::createScientificInstance(Locale::getFrance(), status), 12345.678901, "1,2345678901E4", status); expect(new DecimalFormat("##0.####E0", US, status), 789.12345e-9, "789.12E-9", status); expect2(new DecimalFormat("##0.####E0", US, status), 780.e-9, "780E-9", status); expect(new DecimalFormat(".###E0", US, status), 45678.0, ".457E5", status); expect2(new DecimalFormat(".###E0", US, status), (int32_t) 0, ".0E0", status); /* expect(new DecimalFormat[] { new DecimalFormat("#E0", US), new DecimalFormat("##E0", US), new DecimalFormat("####E0", US), new DecimalFormat("0E0", US), new DecimalFormat("00E0", US), new DecimalFormat("000E0", US), }, new Long(45678000), new String[] { "4.5678E7", "45.678E6", "4567.8E4", "5E7", "46E6", "457E5", } ); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("#E0", US, status), (int32_t) 45678000, "4.5678E7", status); expect2(new DecimalFormat("##E0", US, status), (int32_t) 45678000, "45.678E6", status); expect2(new DecimalFormat("####E0", US, status), (int32_t) 45678000, "4567.8E4", status); expect(new DecimalFormat("0E0", US, status), (int32_t) 45678000, "5E7", status); expect(new DecimalFormat("00E0", US, status), (int32_t) 45678000, "46E6", status); expect(new DecimalFormat("000E0", US, status), (int32_t) 45678000, "457E5", status); /* expect(new DecimalFormat("###E0", US, status), new Object[] { new Double(0.0000123), "12.3E-6", new Double(0.000123), "123E-6", new Double(0.00123), "1.23E-3", new Double(0.0123), "12.3E-3", new Double(0.123), "123E-3", new Double(1.23), "1.23E0", new Double(12.3), "12.3E0", new Double(123), "123E0", new Double(1230), "1.23E3", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("###E0", US, status), 0.0000123, "12.3E-6", status); expect2(new DecimalFormat("###E0", US, status), 0.000123, "123E-6", status); expect2(new DecimalFormat("###E0", US, status), 0.00123, "1.23E-3", status); expect2(new DecimalFormat("###E0", US, status), 0.0123, "12.3E-3", status); expect2(new DecimalFormat("###E0", US, status), 0.123, "123E-3", status); expect2(new DecimalFormat("###E0", US, status), 1.23, "1.23E0", status); expect2(new DecimalFormat("###E0", US, status), 12.3, "12.3E0", status); expect2(new DecimalFormat("###E0", US, status), 123.0, "123E0", status); expect2(new DecimalFormat("###E0", US, status), 1230.0, "1.23E3", status); /* expect(new DecimalFormat("0.#E+00", US, status), new Object[] { new Double(0.00012), "1.2E-04", new Long(12000), "1.2E+04", }); ! ! Unroll this test into individual tests below... ! */ expect2(new DecimalFormat("0.#E+00", US, status), 0.00012, "1.2E-04", status); expect2(new DecimalFormat("0.#E+00", US, status), (int32_t) 12000, "1.2E+04", status); } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestPad(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); expect2(new DecimalFormat("*^##.##", US, status), int32_t(0), "^^^^0", status); expect2(new DecimalFormat("*^##.##", US, status), -1.3, "^-1.3", status); expect2(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), int32_t(0), "0.0E0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####E0*_ 'g-m/s^2'", US, status), 1.0/3, "333.333E-3_ g-m/s^2", status); expect2(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), int32_t(0), "0.0______ g-m/s^2", status); expect(new DecimalFormat("##0.0####*_ 'g-m/s^2'", US, status), 1.0/3, "0.33333__ g-m/s^2", status); // Test padding before a sign const char *formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)"; expect2(new DecimalFormat(formatStr, US, status), int32_t(-10), "xxxxxxxxxx(10.0)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(-1000),"xxxxxxx(1,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(-1000000),"xxx(1,000,000.0)", status); expect2(new DecimalFormat(formatStr, US, status), -100.37, "xxxxxxxx(100.37)", status); expect2(new DecimalFormat(formatStr, US, status), -10456.37, "xxxxx(10,456.37)", status); expect2(new DecimalFormat(formatStr, US, status), -1120456.37, "xx(1,120,456.37)", status); expect2(new DecimalFormat(formatStr, US, status), -112045600.37, "(112,045,600.37)", status); expect2(new DecimalFormat(formatStr, US, status), -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(10), "xxxxxxxxxxxx10.0", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(1000),"xxxxxxxxx1,000.0", status); expect2(new DecimalFormat(formatStr, US, status), int32_t(1000000),"xxxxx1,000,000.0", status); expect2(new DecimalFormat(formatStr, US, status), 100.37, "xxxxxxxxxx100.37", status); expect2(new DecimalFormat(formatStr, US, status), 10456.37, "xxxxxxx10,456.37", status); expect2(new DecimalFormat(formatStr, US, status), 1120456.37, "xxxx1,120,456.37", status); expect2(new DecimalFormat(formatStr, US, status), 112045600.37, "xx112,045,600.37", status); expect2(new DecimalFormat(formatStr, US, status), 10252045600.37,"10,252,045,600.37", status); // Test padding between a sign and a number const char *formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)"; expect2(new DecimalFormat(formatStr2, US, status), int32_t(-10), "(10.0xxxxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(-1000),"(1,000.0xxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(-1000000),"(1,000,000.0xxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -100.37, "(100.37xxxxxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -10456.37, "(10,456.37xxxxx)", status); expect2(new DecimalFormat(formatStr2, US, status), -1120456.37, "(1,120,456.37xx)", status); expect2(new DecimalFormat(formatStr2, US, status), -112045600.37, "(112,045,600.37)", status); expect2(new DecimalFormat(formatStr2, US, status), -1252045600.37,"(1,252,045,600.37)", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(10), "10.0xxxxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(1000),"1,000.0xxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), int32_t(1000000),"1,000,000.0xxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 100.37, "100.37xxxxxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 10456.37, "10,456.37xxxxxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 1120456.37, "1,120,456.37xxxx", status); expect2(new DecimalFormat(formatStr2, US, status), 112045600.37, "112,045,600.37xx", status); expect2(new DecimalFormat(formatStr2, US, status), 10252045600.37,"10,252,045,600.37", status); //testing the setPadCharacter(UnicodeString) and getPadCharacterString() DecimalFormat fmt("#", US, status); CHECK(status, "DecimalFormat constructor"); UnicodeString padString("P"); fmt.setPadCharacter(padString); expectPad(fmt, "*P##.##", DecimalFormat::kPadBeforePrefix, 5, padString); fmt.setPadCharacter((UnicodeString)"^"); expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, (UnicodeString)"^"); //commented untill implementation is complete /* fmt.setPadCharacter((UnicodeString)"^^^"); expectPad(fmt, "*^^^#", DecimalFormat::kPadBeforePrefix, 3, (UnicodeString)"^^^"); padString.remove(); padString.append((UChar)0x0061); padString.append((UChar)0x0302); fmt.setPadCharacter(padString); UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000}; UnicodeString pattern(patternChars); expectPad(fmt, pattern , DecimalFormat::kPadBeforePrefix, 4, padString); */ } /** * Upgrade to alphaWorks */ void NumberFormatTest::TestPatterns2(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat fmt("#", US, status); CHECK(status, "DecimalFormat constructor"); UChar hat = 0x005E; /*^*/ expectPad(fmt, "*^#", DecimalFormat::kPadBeforePrefix, 1, hat); expectPad(fmt, "$*^#", DecimalFormat::kPadAfterPrefix, 2, hat); expectPad(fmt, "#*^", DecimalFormat::kPadBeforeSuffix, 1, hat); expectPad(fmt, "#$*^", DecimalFormat::kPadAfterSuffix, 2, hat); expectPad(fmt, "$*^$#", ILLEGAL); expectPad(fmt, "#$*^$", ILLEGAL); expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat::kPadBeforeSuffix, 12, (UChar)0x0078 /*x*/); expectPad(fmt, "''#0*x", DecimalFormat::kPadBeforeSuffix, 3, (UChar)0x0078 /*x*/); expectPad(fmt, "'I''ll'*a###.##", DecimalFormat::kPadAfterPrefix, 10, (UChar)0x0061 /*a*/); fmt.applyPattern("AA#,##0.00ZZ", status); CHECK(status, "applyPattern"); fmt.setPadCharacter(hat); fmt.setFormatWidth(10); fmt.setPadPosition(DecimalFormat::kPadBeforePrefix); expectPat(fmt, "*^AA#,##0.00ZZ"); fmt.setPadPosition(DecimalFormat::kPadBeforeSuffix); expectPat(fmt, "AA#,##0.00*^ZZ"); fmt.setPadPosition(DecimalFormat::kPadAfterSuffix); expectPat(fmt, "AA#,##0.00ZZ*^"); // 12 3456789012 UnicodeString exp("AA*^#,##0.00ZZ", ""); fmt.setFormatWidth(12); fmt.setPadPosition(DecimalFormat::kPadAfterPrefix); expectPat(fmt, exp); fmt.setFormatWidth(13); // 12 34567890123 expectPat(fmt, "AA*^##,##0.00ZZ"); fmt.setFormatWidth(14); // 12 345678901234 expectPat(fmt, "AA*^###,##0.00ZZ"); fmt.setFormatWidth(15); // 12 3456789012345 expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case fmt.setFormatWidth(16); // 12 34567890123456 expectPat(fmt, "AA*^#####,##0.00ZZ"); } void NumberFormatTest::TestSurrogateSupport(void) { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols custom(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); custom.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, "decimal"); custom.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, "plus"); custom.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, " minus "); custom.setSymbol(DecimalFormatSymbols::kExponentialSymbol, "exponent"); UnicodeString patternStr("*\\U00010000##.##", ""); patternStr = patternStr.unescape(); UnicodeString expStr("\\U00010000\\U00010000\\U00010000\\U000100000", ""); expStr = expStr.unescape(); expect2(new DecimalFormat(patternStr, custom, status), int32_t(0), expStr, status); status = U_ZERO_ERROR; expect2(new DecimalFormat("*^##.##", custom, status), int32_t(0), "^^^^0", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##.##", custom, status), -1.3, " minus 1decimal3", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), int32_t(0), "0decimal0exponent0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0####E0 'g-m/s^2'", custom, status), 1.0/3, "333decimal333exponent minus 3 g-m/s^2", status); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), int32_t(0), "0decimal0 g-m/s^2", status); status = U_ZERO_ERROR; expect(new DecimalFormat("##0.0#### 'g-m/s^2'", custom, status), 1.0/3, "0decimal33333 g-m/s^2", status); UnicodeString zero((UChar32)0x10000); UnicodeString one((UChar32)0x10001); UnicodeString two((UChar32)0x10002); UnicodeString five((UChar32)0x10005); custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, zero); custom.setSymbol(DecimalFormatSymbols::kOneDigitSymbol, one); custom.setSymbol(DecimalFormatSymbols::kTwoDigitSymbol, two); custom.setSymbol(DecimalFormatSymbols::kFiveDigitSymbol, five); expStr = UnicodeString("\\U00010001decimal\\U00010002\\U00010005\\U00010000", ""); expStr = expStr.unescape(); status = U_ZERO_ERROR; expect2(new DecimalFormat("##0.000", custom, status), 1.25, expStr, status); custom.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, (UChar)0x30); custom.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "units of money"); custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, "money separator"); patternStr = UNICODE_STRING_SIMPLE("0.00 \\u00A4' in your bank account'"); patternStr = patternStr.unescape(); expStr = UnicodeString(" minus 20money separator00 units of money in your bank account", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), int32_t(-20), expStr, status); custom.setSymbol(DecimalFormatSymbols::kPercentSymbol, "percent"); patternStr = "'You''ve lost ' -0.00 %' of your money today'"; patternStr = patternStr.unescape(); expStr = UnicodeString(" minus You've lost minus 2000decimal00 percent of your money today", ""); status = U_ZERO_ERROR; expect2(new DecimalFormat(patternStr, custom, status), int32_t(-20), expStr, status); } void NumberFormatTest::TestCurrencyPatterns(void) { int32_t i, locCount; const Locale* locs = NumberFormat::getAvailableLocales(locCount); for (i=0; i<locCount; ++i) { UErrorCode ec = U_ZERO_ERROR; NumberFormat* nf = NumberFormat::createCurrencyInstance(locs[i], ec); if (U_FAILURE(ec)) { errln("FAIL: Can't create NumberFormat(%s) - %s", locs[i].getName(), u_errorName(ec)); } else { // Make sure currency formats do not have a variable number // of fraction digits int32_t min = nf->getMinimumFractionDigits(); int32_t max = nf->getMaximumFractionDigits(); if (min != max) { UnicodeString a, b; nf->format(1.0, a); nf->format(1.125, b); errln((UnicodeString)"FAIL: " + locs[i].getName() + " min fraction digits != max fraction digits; " "x 1.0 => " + escape(a) + "; x 1.125 => " + escape(b)); } // Make sure EURO currency formats have exactly 2 fraction digits DecimalFormat* df = dynamic_cast<DecimalFormat*>(nf); if (df != NULL) { if (u_strcmp(EUR, df->getCurrency()) == 0) { if (min != 2 || max != 2) { UnicodeString a; nf->format(1.0, a); errln((UnicodeString)"FAIL: " + locs[i].getName() + " is a EURO format but it does not have 2 fraction digits; " "x 1.0 => " + escape(a)); } } } } delete nf; } } void NumberFormatTest::TestRegCurrency(void) { #if !UCONFIG_NO_SERVICE UErrorCode status = U_ZERO_ERROR; UChar USD[4]; ucurr_forLocale("en_US", USD, 4, &status); UChar YEN[4]; ucurr_forLocale("ja_JP", YEN, 4, &status); UChar TMP[4]; static const UChar QQQ[] = {0x51, 0x51, 0x51, 0}; if(U_FAILURE(status)) { errcheckln(status, "Unable to get currency for locale, error %s", u_errorName(status)); return; } UCurrRegistryKey enkey = ucurr_register(YEN, "en_US", &status); UCurrRegistryKey enUSEUROkey = ucurr_register(QQQ, "en_US_EURO", &status); ucurr_forLocale("en_US", TMP, 4, &status); if (u_strcmp(YEN, TMP) != 0) { errln("FAIL: didn't return YEN registered for en_US"); } ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(QQQ, TMP) != 0) { errln("FAIL: didn't return QQQ for en_US_EURO"); } int32_t fallbackLen = ucurr_forLocale("en_XX_BAR", TMP, 4, &status); if (fallbackLen) { errln("FAIL: tried to fallback en_XX_BAR"); } status = U_ZERO_ERROR; // reset if (!ucurr_unregister(enkey, &status)) { errln("FAIL: couldn't unregister enkey"); } ucurr_forLocale("en_US", TMP, 4, &status); if (u_strcmp(USD, TMP) != 0) { errln("FAIL: didn't return USD for en_US after unregister of en_US"); } status = U_ZERO_ERROR; // reset ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(QQQ, TMP) != 0) { errln("FAIL: didn't return QQQ for en_US_EURO after unregister of en_US"); } ucurr_forLocale("en_US_BLAH", TMP, 4, &status); if (u_strcmp(USD, TMP) != 0) { errln("FAIL: could not find USD for en_US_BLAH after unregister of en"); } status = U_ZERO_ERROR; // reset if (!ucurr_unregister(enUSEUROkey, &status)) { errln("FAIL: couldn't unregister enUSEUROkey"); } ucurr_forLocale("en_US_EURO", TMP, 4, &status); if (u_strcmp(EUR, TMP) != 0) { errln("FAIL: didn't return EUR for en_US_EURO after unregister of en_US_EURO"); } status = U_ZERO_ERROR; // reset #endif } void NumberFormatTest::TestCurrencyNames(void) { // Do a basic check of getName() // USD { "US$", "US Dollar" } // 04/04/1792- UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = {0x55, 0x53, 0x44, 0}; /*USD*/ static const UChar USX[] = {0x55, 0x53, 0x58, 0}; /*USX*/ static const UChar CAD[] = {0x43, 0x41, 0x44, 0}; /*CAD*/ static const UChar ITL[] = {0x49, 0x54, 0x4C, 0}; /*ITL*/ UBool isChoiceFormat; int32_t len; const UBool possibleDataError = TRUE; // Warning: HARD-CODED LOCALE DATA in this test. If it fails, CHECK // THE LOCALE DATA before diving into the code. assertEquals("USD.getName(SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(NARROW_SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(LONG_NAME, en)", UnicodeString("US Dollar"), UnicodeString(ucurr_getName(USD, "en", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME, en)", UnicodeString("CA$"), UnicodeString(ucurr_getName(CAD, "en", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(NARROW_SYMBOL_NAME, en)", UnicodeString("$"), UnicodeString(ucurr_getName(CAD, "en", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME, en_CA)", UnicodeString("$"), UnicodeString(ucurr_getName(CAD, "en_CA", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(SYMBOL_NAME, en_CA)", UnicodeString("US$"), UnicodeString(ucurr_getName(USD, "en_CA", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(NARROW_SYMBOL_NAME, en_CA)", UnicodeString("$"), UnicodeString(ucurr_getName(USD, "en_CA", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USD.getName(SYMBOL_NAME) in en_NZ", UnicodeString("US$"), UnicodeString(ucurr_getName(USD, "en_NZ", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("CAD.getName(SYMBOL_NAME)", UnicodeString("CA$"), UnicodeString(ucurr_getName(CAD, "en_NZ", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(SYMBOL_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(NARROW_SYMBOL_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_NARROW_SYMBOL_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertEquals("USX.getName(LONG_NAME)", UnicodeString("USX"), UnicodeString(ucurr_getName(USX, "en_US", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec)), possibleDataError); assertSuccess("ucurr_getName", ec); ec = U_ZERO_ERROR; // Test that a default or fallback warning is being returned. JB 4239. ucurr_getName(CAD, "es_ES", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (es_ES fallback)", U_USING_FALLBACK_WARNING == ec, TRUE, possibleDataError); ucurr_getName(CAD, "zh_TW", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (zh_TW fallback)", U_USING_FALLBACK_WARNING == ec, TRUE, possibleDataError); ucurr_getName(CAD, "en_US", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (en_US default)", U_USING_DEFAULT_WARNING == ec || U_USING_FALLBACK_WARNING == ec, TRUE); ucurr_getName(CAD, "ti", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (ti default)", U_USING_DEFAULT_WARNING == ec, TRUE); // Test that a default warning is being returned when falling back to root. JB 4536. ucurr_getName(ITL, "cy", UCURR_LONG_NAME, &isChoiceFormat, &len, &ec); assertTrue("ucurr_getName (cy default to root)", U_USING_DEFAULT_WARNING == ec, TRUE); // TODO add more tests later } void NumberFormatTest::TestCurrencyUnit(void){ UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = u"USD"; static const char USD8[] = "USD"; static const UChar BAD[] = u"???"; static const UChar BAD2[] = u"??A"; static const UChar XXX[] = u"XXX"; static const char XXX8[] = "XXX"; CurrencyUnit cu(USD, ec); assertSuccess("CurrencyUnit", ec); assertEquals("getISOCurrency()", USD, cu.getISOCurrency()); assertEquals("getSubtype()", USD8, cu.getSubtype()); CurrencyUnit cu2(cu); if (!(cu2 == cu)){ errln("CurrencyUnit copy constructed object should be same"); } CurrencyUnit * cu3 = (CurrencyUnit *)cu.clone(); if (!(*cu3 == cu)){ errln("CurrencyUnit cloned object should be same"); } CurrencyUnit bad(BAD, ec); assertSuccess("CurrencyUnit", ec); if (cu.getIndex() == bad.getIndex()) { errln("Indexes of different currencies should differ."); } CurrencyUnit bad2(BAD2, ec); assertSuccess("CurrencyUnit", ec); if (bad2.getIndex() != bad.getIndex()) { errln("Indexes of unrecognized currencies should be the same."); } if (bad == bad2) { errln("Different unrecognized currencies should not be equal."); } bad = bad2; if (bad != bad2) { errln("Currency unit assignment should be the same."); } delete cu3; // Test default constructor CurrencyUnit def; assertEquals("Default currency", XXX, def.getISOCurrency()); assertEquals("Default currency as subtype", XXX8, def.getSubtype()); // Test slicing MeasureUnit sliced1 = cu; MeasureUnit sliced2 = cu; assertEquals("Subtype after slicing 1", USD8, sliced1.getSubtype()); assertEquals("Subtype after slicing 2", USD8, sliced2.getSubtype()); CurrencyUnit restored1(sliced1, ec); CurrencyUnit restored2(sliced2, ec); assertSuccess("Restoring from MeasureUnit", ec); assertEquals("Subtype after restoring 1", USD8, restored1.getSubtype()); assertEquals("Subtype after restoring 2", USD8, restored2.getSubtype()); assertEquals("ISO Code after restoring 1", USD, restored1.getISOCurrency()); assertEquals("ISO Code after restoring 2", USD, restored2.getISOCurrency()); // Test copy constructor failure LocalPointer<MeasureUnit> meter(MeasureUnit::createMeter(ec)); assertSuccess("Creating meter", ec); CurrencyUnit failure(*meter, ec); assertEquals("Copying from meter should fail", ec, U_ILLEGAL_ARGUMENT_ERROR); assertEquals("Copying should not give uninitialized ISO code", u"", failure.getISOCurrency()); } void NumberFormatTest::TestCurrencyAmount(void){ UErrorCode ec = U_ZERO_ERROR; static const UChar USD[] = {85, 83, 68, 0}; /*USD*/ CurrencyAmount ca(9, USD, ec); assertSuccess("CurrencyAmount", ec); CurrencyAmount ca2(ca); if (!(ca2 == ca)){ errln("CurrencyAmount copy constructed object should be same"); } ca2=ca; if (!(ca2 == ca)){ errln("CurrencyAmount assigned object should be same"); } CurrencyAmount *ca3 = (CurrencyAmount *)ca.clone(); if (!(*ca3 == ca)){ errln("CurrencyAmount cloned object should be same"); } delete ca3; } void NumberFormatTest::TestSymbolsWithBadLocale(void) { Locale locDefault; static const char *badLocales[] = { // length < ULOC_FULLNAME_CAPACITY "x-crazy_ZZ_MY_SPECIAL_ADMINISTRATION_REGION_NEEDS_A_SPECIAL_VARIANT_WITH_A_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_LONG_NAME", // length > ULOC_FULLNAME_CAPACITY "x-crazy_ZZ_MY_SPECIAL_ADMINISTRATION_REGION_NEEDS_A_SPECIAL_VARIANT_WITH_A_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_LONG_NAME" }; // expect U_USING_DEFAULT_WARNING for both unsigned int i; for (i = 0; i < UPRV_LENGTHOF(badLocales); i++) { const char *localeName = badLocales[i]; Locale locBad(localeName); TEST_ASSERT_TRUE(!locBad.isBogus()); UErrorCode status = U_ZERO_ERROR; UnicodeString intlCurrencySymbol((UChar)0xa4); intlCurrencySymbol.append((UChar)0xa4); logln("Current locale is %s", Locale::getDefault().getName()); Locale::setDefault(locBad, status); logln("Current locale is %s", Locale::getDefault().getName()); DecimalFormatSymbols mySymbols(status); if (status != U_USING_DEFAULT_WARNING) { errln("DecimalFormatSymbols should return U_USING_DEFAULT_WARNING."); } if (strcmp(mySymbols.getLocale().getName(), locBad.getName()) != 0) { errln("DecimalFormatSymbols does not have the right locale.", locBad.getName()); } int symbolEnum = (int)DecimalFormatSymbols::kDecimalSeparatorSymbol; for (; symbolEnum < (int)DecimalFormatSymbols::kFormatSymbolCount; symbolEnum++) { UnicodeString symbolString = mySymbols.getSymbol((DecimalFormatSymbols::ENumberFormatSymbol)symbolEnum); logln(UnicodeString("DecimalFormatSymbols[") + symbolEnum + UnicodeString("] = ") + prettify(symbolString)); if (symbolString.length() == 0 && symbolEnum != (int)DecimalFormatSymbols::kGroupingSeparatorSymbol && symbolEnum != (int)DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol) { errln("DecimalFormatSymbols has an empty string at index %d.", symbolEnum); } } status = U_ZERO_ERROR; Locale::setDefault(locDefault, status); logln("Current locale is %s", Locale::getDefault().getName()); } } /** * Check that adoptDecimalFormatSymbols and setDecimalFormatSymbols * behave the same, except for memory ownership semantics. (No * version of this test on Java, since Java has only one method.) */ void NumberFormatTest::TestAdoptDecimalFormatSymbols(void) { UErrorCode ec = U_ZERO_ERROR; DecimalFormatSymbols *sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errcheckln(ec, "Fail: DecimalFormatSymbols constructor - %s", u_errorName(ec)); delete sym; return; } UnicodeString pat(" #,##0.00"); pat.insert(0, (UChar)0x00A4); DecimalFormat fmt(pat, sym, ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormat constructor"); return; } UnicodeString str; fmt.format(2350.75, str); if (str == "$ 2,350.75") { logln(str); } else { dataerrln("Fail: " + str + ", expected $ 2,350.75"); } sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); delete sym; return; } sym->setSymbol(DecimalFormatSymbols::kCurrencySymbol, "Q"); fmt.adoptDecimalFormatSymbols(sym); str.truncate(0); fmt.format(2350.75, str); if (str == "Q 2,350.75") { logln(str); } else { dataerrln("Fail: adoptDecimalFormatSymbols -> " + str + ", expected Q 2,350.75"); } sym = new DecimalFormatSymbols(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); delete sym; return; } DecimalFormat fmt2(pat, sym, ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormat constructor"); return; } DecimalFormatSymbols sym2(Locale::getUS(), ec); if (U_FAILURE(ec)) { errln("Fail: DecimalFormatSymbols constructor"); return; } sym2.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "Q"); fmt2.setDecimalFormatSymbols(sym2); str.truncate(0); fmt2.format(2350.75, str); if (str == "Q 2,350.75") { logln(str); } else { dataerrln("Fail: setDecimalFormatSymbols -> " + str + ", expected Q 2,350.75"); } } void NumberFormatTest::TestPerMill() { UErrorCode ec = U_ZERO_ERROR; UnicodeString str; DecimalFormat fmt(ctou("###.###\\u2030"), ec); if (!assertSuccess("DecimalFormat ct", ec)) return; assertEquals("0.4857 x ###.###\\u2030", ctou("485.7\\u2030"), fmt.format(0.4857, str), true); DecimalFormatSymbols sym(Locale::getUS(), ec); if (!assertSuccess("", ec, true, __FILE__, __LINE__)) { return; } sym.setSymbol(DecimalFormatSymbols::kPerMillSymbol, ctou("m")); DecimalFormat fmt2("", sym, ec); if (!assertSuccess("", ec, true, __FILE__, __LINE__)) { return; } fmt2.applyLocalizedPattern("###.###m", ec); if (!assertSuccess("setup", ec)) return; str.truncate(0); assertEquals("0.4857 x ###.###m", "485.7m", fmt2.format(0.4857, str)); } /** * Generic test for patterns that should be legal/illegal. */ void NumberFormatTest::TestIllegalPatterns() { // Test cases: // Prefix with "-:" for illegal patterns // Prefix with "+:" for legal patterns const char* DATA[] = { // Unquoted special characters in the suffix are illegal "-:000.000|###", "+:000.000'|###'", 0 }; for (int32_t i=0; DATA[i]; ++i) { const char* pat=DATA[i]; UBool valid = (*pat) == '+'; pat += 2; UErrorCode ec = U_ZERO_ERROR; DecimalFormat fmt(pat, ec); // locale doesn't matter here if (U_SUCCESS(ec) == valid) { logln("Ok: pattern \"%s\": %s", pat, u_errorName(ec)); } else { errcheckln(ec, "FAIL: pattern \"%s\" should have %s; got %s", pat, (valid?"succeeded":"failed"), u_errorName(ec)); } } } //---------------------------------------------------------------------- static const char* KEYWORDS[] = { /*0*/ "ref=", // <reference pattern to parse numbers> /*1*/ "loc=", // <locale for formats> /*2*/ "f:", // <pattern or '-'> <number> <exp. string> /*3*/ "fp:", // <pattern or '-'> <number> <exp. string> <exp. number> /*4*/ "rt:", // <pattern or '-'> <(exp.) number> <(exp.) string> /*5*/ "p:", // <pattern or '-'> <string> <exp. number> /*6*/ "perr:", // <pattern or '-'> <invalid string> /*7*/ "pat:", // <pattern or '-'> <exp. toPattern or '-' or 'err'> /*8*/ "fpc:", // <pattern or '-'> <curr.amt> <exp. string> <exp. curr.amt> 0 }; /** * Return an integer representing the next token from this * iterator. The integer will be an index into the given list, or * -1 if there are no more tokens, or -2 if the token is not on * the list. */ static int32_t keywordIndex(const UnicodeString& tok) { for (int32_t i=0; KEYWORDS[i]!=0; ++i) { if (tok==KEYWORDS[i]) { return i; } } return -1; } /** * Parse a CurrencyAmount using the given NumberFormat, with * the 'delim' character separating the number and the currency. */ static void parseCurrencyAmount(const UnicodeString& str, const NumberFormat& fmt, UChar delim, Formattable& result, UErrorCode& ec) { UnicodeString num, cur; int32_t i = str.indexOf(delim); str.extractBetween(0, i, num); str.extractBetween(i+1, INT32_MAX, cur); Formattable n; fmt.parse(num, n, ec); result.adoptObject(new CurrencyAmount(n, cur.getTerminatedBuffer(), ec)); } void NumberFormatTest::TestCases() { UErrorCode ec = U_ZERO_ERROR; TextFile reader("NumberFormatTestCases.txt", "UTF8", ec); if (U_FAILURE(ec)) { dataerrln("Couldn't open NumberFormatTestCases.txt"); return; } TokenIterator tokens(&reader); Locale loc("en", "US", ""); DecimalFormat *ref = 0, *fmt = 0; MeasureFormat *mfmt = 0; UnicodeString pat, tok, mloc, str, out, where, currAmt; Formattable n; for (;;) { ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) { break; } where = UnicodeString("(") + tokens.getLineNumber() + ") "; int32_t cmd = keywordIndex(tok); switch (cmd) { case 0: // ref= <reference pattern> if (!tokens.next(tok, ec)) goto error; delete ref; ref = new DecimalFormat(tok, new DecimalFormatSymbols(Locale::getUS(), ec), ec); if (U_FAILURE(ec)) { dataerrln("Error constructing DecimalFormat"); goto error; } break; case 1: // loc= <locale> if (!tokens.next(tok, ec)) goto error; loc = Locale::createFromName(CharString().appendInvariantChars(tok, ec).data()); break; case 2: // f: case 3: // fp: case 4: // rt: case 5: // p: if (!tokens.next(tok, ec)) goto error; if (tok != "-") { pat = tok; delete fmt; fmt = new DecimalFormat(pat, new DecimalFormatSymbols(loc, ec), ec); if (U_FAILURE(ec)) { errln("FAIL: " + where + "Pattern \"" + pat + "\": " + u_errorName(ec)); ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (cmd == 3) { if (!tokens.next(tok, ec)) goto error; } continue; } } if (cmd == 2 || cmd == 3 || cmd == 4) { // f: <pattern or '-'> <number> <exp. string> // fp: <pattern or '-'> <number> <exp. string> <exp. number> // rt: <pattern or '-'> <number> <string> UnicodeString num; if (!tokens.next(num, ec)) goto error; if (!tokens.next(str, ec)) goto error; ref->parse(num, n, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".format(" + num + ")", str, fmt->format(n, out.remove(), ec)); assertSuccess("format", ec); if (cmd == 3) { // fp: if (!tokens.next(num, ec)) goto error; ref->parse(num, n, ec); assertSuccess("parse", ec); } if (cmd != 2) { // != f: Formattable m; fmt->parse(str, m, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".parse(\"" + str + "\")", n, m); } } // p: <pattern or '-'> <string to parse> <exp. number> else { UnicodeString expstr; if (!tokens.next(str, ec)) goto error; if (!tokens.next(expstr, ec)) goto error; Formattable exp, n; ref->parse(expstr, exp, ec); assertSuccess("parse", ec); fmt->parse(str, n, ec); assertSuccess("parse", ec); assertEquals(where + "\"" + pat + "\".parse(\"" + str + "\")", exp, n); } break; case 8: // fpc: if (!tokens.next(tok, ec)) goto error; if (tok != "-") { mloc = tok; delete mfmt; mfmt = MeasureFormat::createCurrencyFormat( Locale::createFromName( CharString().appendInvariantChars(mloc, ec).data()), ec); if (U_FAILURE(ec)) { errln("FAIL: " + where + "Loc \"" + mloc + "\": " + u_errorName(ec)); ec = U_ZERO_ERROR; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; continue; } } else if (mfmt == NULL) { errln("FAIL: " + where + "Loc \"" + mloc + "\": skip case using previous locale, no valid MeasureFormat"); if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; if (!tokens.next(tok, ec)) goto error; continue; } // fpc: <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt> if (!tokens.next(currAmt, ec)) goto error; if (!tokens.next(str, ec)) goto error; parseCurrencyAmount(currAmt, *ref, (UChar)0x2F/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, mfmt->format(n, out.remove(), ec)); assertSuccess("format", ec); } if (!tokens.next(currAmt, ec)) goto error; parseCurrencyAmount(currAmt, *ref, (UChar)0x2F/*'/'*/, n, ec); if (assertSuccess("parseCurrencyAmount", ec)) { Formattable m; mfmt->parseObject(str, m, ec); if (assertSuccess("parseCurrency", ec)) { assertEquals(where + "getCurrencyFormat(" + mloc + ").parse(\"" + str + "\")", n, m); } else { errln("FAIL: source " + str); } } break; case 6: // perr: <pattern or '-'> <invalid string> errln("FAIL: Under construction"); goto done; case 7: { // pat: <pattern> <exp. toPattern, or '-' or 'err'> UnicodeString testpat; UnicodeString exppat; if (!tokens.next(testpat, ec)) goto error; if (!tokens.next(exppat, ec)) goto error; UBool err = exppat == "err"; UBool existingPat = FALSE; if (testpat == "-") { if (err) { errln("FAIL: " + where + "Invalid command \"pat: - err\""); continue; } existingPat = TRUE; testpat = pat; } if (exppat == "-") exppat = testpat; DecimalFormat* f = 0; UErrorCode ec2 = U_ZERO_ERROR; if (existingPat) { f = fmt; } else { f = new DecimalFormat(testpat, ec2); } if (U_SUCCESS(ec2)) { if (err) { errln("FAIL: " + where + "Invalid pattern \"" + testpat + "\" was accepted"); } else { UnicodeString pat2; assertEquals(where + "\"" + testpat + "\".toPattern()", exppat, f->toPattern(pat2)); } } else { if (err) { logln("Ok: " + where + "Invalid pattern \"" + testpat + "\" failed: " + u_errorName(ec2)); } else { errln("FAIL: " + where + "Valid pattern \"" + testpat + "\" failed: " + u_errorName(ec2)); } } if (!existingPat) delete f; } break; case -1: errln("FAIL: " + where + "Unknown command \"" + tok + "\""); goto done; } } goto done; error: if (U_SUCCESS(ec)) { errln("FAIL: Unexpected EOF"); } else { errcheckln(ec, "FAIL: " + where + "Unexpected " + u_errorName(ec)); } done: delete mfmt; delete fmt; delete ref; } //---------------------------------------------------------------------- // Support methods //---------------------------------------------------------------------- UBool NumberFormatTest::equalValue(const Formattable& a, const Formattable& b) { if (a.getType() == b.getType()) { return a == b; } if (a.getType() == Formattable::kLong) { if (b.getType() == Formattable::kInt64) { return a.getLong() == b.getLong(); } else if (b.getType() == Formattable::kDouble) { return (double) a.getLong() == b.getDouble(); // TODO check use of double instead of long } } else if (a.getType() == Formattable::kDouble) { if (b.getType() == Formattable::kLong) { return a.getDouble() == (double) b.getLong(); } else if (b.getType() == Formattable::kInt64) { return a.getDouble() == (double)b.getInt64(); } } else if (a.getType() == Formattable::kInt64) { if (b.getType() == Formattable::kLong) { return a.getInt64() == (int64_t)b.getLong(); } else if (b.getType() == Formattable::kDouble) { return a.getInt64() == (int64_t)b.getDouble(); } } return FALSE; } void NumberFormatTest::expect3(NumberFormat& fmt, const Formattable& n, const UnicodeString& str) { // Don't round-trip format test, since we explicitly do it expect_rbnf(fmt, n, str, FALSE); expect_rbnf(fmt, str, n); } void NumberFormatTest::expect2(NumberFormat& fmt, const Formattable& n, const UnicodeString& str) { // Don't round-trip format test, since we explicitly do it expect(fmt, n, str, FALSE); expect(fmt, str, n); } void NumberFormatTest::expect2(NumberFormat* fmt, const Formattable& n, const UnicodeString& exp, UErrorCode status) { if (fmt == NULL || U_FAILURE(status)) { dataerrln("FAIL: NumberFormat constructor"); } else { expect2(*fmt, n, exp); } delete fmt; } void NumberFormatTest::expect(NumberFormat& fmt, const UnicodeString& str, const Formattable& n) { UErrorCode status = U_ZERO_ERROR; Formattable num; fmt.parse(str, num, status); if (U_FAILURE(status)) { dataerrln(UnicodeString("FAIL: Parse failed for \"") + str + "\" - " + u_errorName(status)); return; } UnicodeString pat; ((DecimalFormat*) &fmt)->toPattern(pat); if (equalValue(num, n)) { logln(UnicodeString("Ok \"") + str + "\" x " + pat + " = " + toString(num)); } else { dataerrln(UnicodeString("FAIL \"") + str + "\" x " + pat + " = " + toString(num) + ", expected " + toString(n)); } } void NumberFormatTest::expect_rbnf(NumberFormat& fmt, const UnicodeString& str, const Formattable& n) { UErrorCode status = U_ZERO_ERROR; Formattable num; fmt.parse(str, num, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + str + "\""); return; } if (equalValue(num, n)) { logln(UnicodeString("Ok \"") + str + " = " + toString(num)); } else { errln(UnicodeString("FAIL \"") + str + " = " + toString(num) + ", expected " + toString(n)); } } void NumberFormatTest::expect_rbnf(NumberFormat& fmt, const Formattable& n, const UnicodeString& exp, UBool rt) { UnicodeString saw; FieldPosition pos; UErrorCode status = U_ZERO_ERROR; fmt.format(n, saw, pos, status); CHECK(status, "NumberFormat::format"); if (saw == exp) { logln(UnicodeString("Ok ") + toString(n) + " = \"" + escape(saw) + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { Formattable n2; fmt.parse(exp, n2, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + exp + "\""); return; } UnicodeString saw2; fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } } else { errln(UnicodeString("FAIL ") + toString(n) + " = \"" + escape(saw) + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expect(NumberFormat& fmt, const Formattable& n, const UnicodeString& exp, UBool rt) { UnicodeString saw; FieldPosition pos; UErrorCode status = U_ZERO_ERROR; fmt.format(n, saw, pos, status); CHECK(status, "NumberFormat::format"); UnicodeString pat; ((DecimalFormat*) &fmt)->toPattern(pat); if (saw == exp) { logln(UnicodeString("Ok ") + toString(n) + " x " + escape(pat) + " = \"" + escape(saw) + "\""); // We should be able to round-trip the formatted string => // number => string (but not the other way around: number // => string => number2, might have number2 != number): if (rt) { Formattable n2; fmt.parse(exp, n2, status); if (U_FAILURE(status)) { errln(UnicodeString("FAIL: Parse failed for \"") + exp + "\" - " + u_errorName(status)); return; } UnicodeString saw2; fmt.format(n2, saw2, pos, status); CHECK(status, "NumberFormat::format"); if (saw2 != exp) { errln((UnicodeString)"FAIL \"" + exp + "\" => " + toString(n2) + " => \"" + saw2 + "\""); } } } else { dataerrln(UnicodeString("FAIL ") + toString(n) + " x " + escape(pat) + " = \"" + escape(saw) + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expect(NumberFormat* fmt, const Formattable& n, const UnicodeString& exp, UBool rt, UErrorCode status) { if (fmt == NULL || U_FAILURE(status)) { dataerrln("FAIL: NumberFormat constructor"); } else { expect(*fmt, n, exp, rt); } delete fmt; } void NumberFormatTest::expectCurrency(NumberFormat& nf, const Locale& locale, double value, const UnicodeString& string) { UErrorCode ec = U_ZERO_ERROR; DecimalFormat& fmt = * (DecimalFormat*) &nf; const UChar DEFAULT_CURR[] = {45/*-*/,0}; UChar curr[4]; u_strcpy(curr, DEFAULT_CURR); if (*locale.getLanguage() != 0) { ucurr_forLocale(locale.getName(), curr, 4, &ec); assertSuccess("ucurr_forLocale", ec); fmt.setCurrency(curr, ec); assertSuccess("DecimalFormat::setCurrency", ec); fmt.setCurrency(curr); //Deprecated variant, for coverage only } UnicodeString s; fmt.format(value, s); s.findAndReplace((UChar32)0x00A0, (UChar32)0x0020); // Default display of the number yields "1234.5599999999999" // instead of "1234.56". Use a formatter to fix this. NumberFormat* f = NumberFormat::createInstance(Locale::getUS(), ec); UnicodeString v; if (U_FAILURE(ec)) { // Oops; bad formatter. Use default op+= display. v = (UnicodeString)"" + value; } else { f->setMaximumFractionDigits(4); f->setGroupingUsed(FALSE); f->format(value, v); } delete f; if (s == string) { logln((UnicodeString)"Ok: " + v + " x " + curr + " => " + prettify(s)); } else { errln((UnicodeString)"FAIL: " + v + " x " + curr + " => " + prettify(s) + ", expected " + prettify(string)); } } void NumberFormatTest::expectPat(DecimalFormat& fmt, const UnicodeString& exp) { UnicodeString pat; fmt.toPattern(pat); if (pat == exp) { logln(UnicodeString("Ok \"") + pat + "\""); } else { errln(UnicodeString("FAIL \"") + pat + "\", expected \"" + exp + "\""); } } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos) { expectPad(fmt, pat, pos, 0, (UnicodeString)""); } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos, int32_t width, UChar pad) { expectPad(fmt, pat, pos, width, UnicodeString(pad)); } void NumberFormatTest::expectPad(DecimalFormat& fmt, const UnicodeString& pat, int32_t pos, int32_t width, const UnicodeString& pad) { int32_t apos = 0, awidth = 0; UnicodeString apadStr; UErrorCode status = U_ZERO_ERROR; fmt.applyPattern(pat, status); if (U_SUCCESS(status)) { apos = fmt.getPadPosition(); awidth = fmt.getFormatWidth(); apadStr=fmt.getPadCharacterString(); } else { apos = -1; awidth = width; apadStr = pad; } if (apos == pos && awidth == width && apadStr == pad) { UnicodeString infoStr; if (pos == ILLEGAL) { infoStr = UnicodeString(" width=", "") + awidth + UnicodeString(" pad=", "") + apadStr; } logln(UnicodeString("Ok \"") + pat + "\" pos=" + apos + infoStr); } else { errln(UnicodeString("FAIL \"") + pat + "\" pos=" + apos + " width=" + awidth + " pad=" + apadStr + ", expected " + pos + " " + width + " " + pad); } } // This test is flaky b/c the symbols for CNY and JPY are equivalent in this locale - FIXME void NumberFormatTest::TestCompatibleCurrencies() { /* static const UChar JPY[] = {0x4A, 0x50, 0x59, 0}; static const UChar CNY[] = {0x43, 0x4E, 0x59, 0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createCurrencyInstance(Locale::getUS(), status)); if (U_FAILURE(status)) { errln("Could not create number format instance."); return; } logln("%s:%d - testing parse of halfwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, JPY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, JPY, 1235, "\\uFFE51,235"); logln("%s:%d - testing parse of halfwidth yen sign\n", __FILE__, __LINE__); expectParseCurrency(*fmt, CNY, 1235, "CN\\u00A51,235"); LocalPointer<NumberFormat> fmtTW( NumberFormat::createCurrencyInstance(Locale::getTaiwan(), status)); logln("%s:%d - testing parse of halfwidth yen sign in TW\n", __FILE__, __LINE__); expectParseCurrency(*fmtTW, CNY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign in TW\n", __FILE__, __LINE__); expectParseCurrency(*fmtTW, CNY, 1235, "\\uFFE51,235"); LocalPointer<NumberFormat> fmtJP( NumberFormat::createCurrencyInstance(Locale::getJapan(), status)); logln("%s:%d - testing parse of halfwidth yen sign in JP\n", __FILE__, __LINE__); expectParseCurrency(*fmtJP, JPY, 1235, "\\u00A51,235"); logln("%s:%d - testing parse of fullwidth yen sign in JP\n", __FILE__, __LINE__); expectParseCurrency(*fmtJP, JPY, 1235, "\\uFFE51,235"); // more.. */ } void NumberFormatTest::expectParseCurrency(const NumberFormat &fmt, const UChar* currency, double amount, const char *text) { ParsePosition ppos; UnicodeString utext = ctou(text); LocalPointer<CurrencyAmount> currencyAmount(fmt.parseCurrency(utext, ppos)); if (!ppos.getIndex()) { errln(UnicodeString("Parse of ") + utext + " should have succeeded."); return; } UErrorCode status = U_ZERO_ERROR; char theInfo[100]; sprintf(theInfo, "For locale %s, string \"%s\", currency ", fmt.getLocale(ULOC_ACTUAL_LOCALE, status).getBaseName(), text); u_austrcpy(theInfo+uprv_strlen(theInfo), currency); char theOperation[100]; uprv_strcpy(theOperation, theInfo); uprv_strcat(theOperation, ", check amount:"); assertTrue(theOperation, amount == currencyAmount->getNumber().getDouble(status)); uprv_strcpy(theOperation, theInfo); uprv_strcat(theOperation, ", check currency:"); assertEquals(theOperation, currency, currencyAmount->getISOCurrency()); } void NumberFormatTest::TestJB3832(){ const char* localeID = "pt_PT@currency=PTE"; Locale loc(localeID); UErrorCode status = U_ZERO_ERROR; UnicodeString expected(CharsToUnicodeString("1,150$50\\u00A0\\u200B")); // per cldrbug 7670 UnicodeString s; NumberFormat* currencyFmt = NumberFormat::createCurrencyInstance(loc, status); if(U_FAILURE(status)){ dataerrln("Could not create currency formatter for locale %s - %s", localeID, u_errorName(status)); return; } currencyFmt->format(1150.50, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } delete currencyFmt; } void NumberFormatTest::TestHost() { #if U_PLATFORM_USES_ONLY_WIN32_API Win32NumberTest::testLocales(this); #endif Locale loc("en_US@compat=host"); for (UNumberFormatStyle k = UNUM_DECIMAL; k < UNUM_FORMAT_STYLE_COUNT; k = (UNumberFormatStyle)(k+1)) { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> full(NumberFormat::createInstance(loc, k, status)); if (!NumberFormat::isStyleSupported(k)) { if (status != U_UNSUPPORTED_ERROR) { errln("FAIL: expected style %d to be unsupported - %s", k, u_errorName(status)); } continue; } if (full.isNull() || U_FAILURE(status)) { dataerrln("FAIL: Can't create number instance of style %d for host - %s", k, u_errorName(status)); return; } UnicodeString result1; Formattable number(10.00); full->format(number, result1, status); if (U_FAILURE(status)) { errln("FAIL: Can't format for host"); return; } Formattable formattable; full->parse(result1, formattable, status); if (U_FAILURE(status)) { errln("FAIL: Can't parse for host"); return; } } } void NumberFormatTest::TestHostClone() { /* Verify that a cloned formatter gives the same results and is useable after the original has been deleted. */ // This is mainly important on Windows. UErrorCode status = U_ZERO_ERROR; Locale loc("en_US@compat=host"); UDate now = Calendar::getNow(); NumberFormat *full = NumberFormat::createInstance(loc, status); if (full == NULL || U_FAILURE(status)) { dataerrln("FAIL: Can't create NumberFormat date instance - %s", u_errorName(status)); return; } UnicodeString result1; full->format(now, result1, status); Format *fullClone = full->clone(); delete full; full = NULL; UnicodeString result2; fullClone->format(now, result2, status); if (U_FAILURE(status)) { errln("FAIL: format failure."); } if (result1 != result2) { errln("FAIL: Clone returned different result from non-clone."); } delete fullClone; } void NumberFormatTest::TestCurrencyFormat() { // This test is here to increase code coverage. UErrorCode status = U_ZERO_ERROR; MeasureFormat *cloneObj; UnicodeString str; Formattable toFormat, result; static const UChar ISO_CODE[4] = {0x0047, 0x0042, 0x0050, 0}; Locale saveDefaultLocale = Locale::getDefault(); Locale::setDefault( Locale::getUK(), status ); if (U_FAILURE(status)) { errln("couldn't set default Locale!"); return; } MeasureFormat *measureObj = MeasureFormat::createCurrencyFormat(status); Locale::setDefault( saveDefaultLocale, status ); if (U_FAILURE(status)){ dataerrln("FAIL: Status %s", u_errorName(status)); return; } cloneObj = (MeasureFormat *)measureObj->clone(); if (cloneObj == NULL) { errln("Clone doesn't work"); return; } toFormat.adoptObject(new CurrencyAmount(1234.56, ISO_CODE, status)); measureObj->format(toFormat, str, status); measureObj->parseObject(str, result, status); if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } if (result != toFormat) { errln("measureObj does not round trip. Formatted string was \"" + str + "\" Got: " + toString(result) + " Expected: " + toString(toFormat)); } status = U_ZERO_ERROR; str.truncate(0); cloneObj->format(toFormat, str, status); cloneObj->parseObject(str, result, status); if (U_FAILURE(status)){ errln("FAIL: Status %s", u_errorName(status)); } if (result != toFormat) { errln("Clone does not round trip. Formatted string was \"" + str + "\" Got: " + toString(result) + " Expected: " + toString(toFormat)); } if (*measureObj != *cloneObj) { errln("Cloned object is not equal to the original object"); } delete measureObj; delete cloneObj; status = U_USELESS_COLLATOR_ERROR; if (MeasureFormat::createCurrencyFormat(status) != NULL) { errln("createCurrencyFormat should have returned NULL."); } } /* Port of ICU4J rounding test. */ void NumberFormatTest::TestRounding() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *df = (DecimalFormat*)NumberFormat::createCurrencyInstance(Locale::getEnglish(), status); if (U_FAILURE(status)) { dataerrln("Unable to create decimal formatter. - %s", u_errorName(status)); return; } int roundingIncrements[]={1, 2, 5, 20, 50, 100}; int testValues[]={0, 300}; for (int j=0; j<2; j++) { for (int mode=DecimalFormat::kRoundUp;mode<DecimalFormat::kRoundHalfEven;mode++) { df->setRoundingMode((DecimalFormat::ERoundingMode)mode); for (int increment=0; increment<6; increment++) { double base=testValues[j]; double rInc=roundingIncrements[increment]; checkRounding(df, base, 20, rInc); rInc=1.000000000/rInc; checkRounding(df, base, 20, rInc); } } } delete df; } void NumberFormatTest::TestRoundingPattern() { UErrorCode status = U_ZERO_ERROR; struct { UnicodeString pattern; double testCase; UnicodeString expected; } tests[] = { { (UnicodeString)"##0.65", 1.234, (UnicodeString)"1.30" }, { (UnicodeString)"#50", 1230, (UnicodeString)"1250" } }; int32_t numOfTests = UPRV_LENGTHOF(tests); UnicodeString result; DecimalFormat *df = (DecimalFormat*)NumberFormat::createCurrencyInstance(Locale::getEnglish(), status); if (U_FAILURE(status)) { dataerrln("Unable to create decimal formatter. - %s", u_errorName(status)); return; } for (int32_t i = 0; i < numOfTests; i++) { result.remove(); df->applyPattern(tests[i].pattern, status); if (U_FAILURE(status)) { errln("Unable to apply pattern to decimal formatter. - %s", u_errorName(status)); } df->format(tests[i].testCase, result); if (result != tests[i].expected) { errln("String Pattern Rounding Test Failed: Pattern: \"" + tests[i].pattern + "\" Number: " + tests[i].testCase + " - Got: " + result + " Expected: " + tests[i].expected); } } delete df; } void NumberFormatTest::checkRounding(DecimalFormat* df, double base, int iterations, double increment) { df->setRoundingIncrement(increment); double lastParsed=INT32_MIN; //Intger.MIN_VALUE for (int i=-iterations; i<=iterations;i++) { double iValue=base+(increment*(i*0.1)); double smallIncrement=0.00000001; if (iValue!=0) { smallIncrement*=iValue; } //we not only test the value, but some values in a small range around it lastParsed=checkRound(df, iValue-smallIncrement, lastParsed); lastParsed=checkRound(df, iValue, lastParsed); lastParsed=checkRound(df, iValue+smallIncrement, lastParsed); } } double NumberFormatTest::checkRound(DecimalFormat* df, double iValue, double lastParsed) { UErrorCode status=U_ZERO_ERROR; UnicodeString formattedDecimal; double parsed; Formattable result; df->format(iValue, formattedDecimal, status); if (U_FAILURE(status)) { errln("Error formatting number."); } df->parse(formattedDecimal, result, status); if (U_FAILURE(status)) { errln("Error parsing number."); } parsed=result.getDouble(); if (lastParsed>parsed) { errln("Rounding wrong direction! %d > %d", lastParsed, parsed); } return lastParsed; } void NumberFormatTest::TestNonpositiveMultiplier() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols US(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); DecimalFormat df(UnicodeString("0"), US, status); CHECK(status, "DecimalFormat(0)"); // test zero multiplier int32_t mult = df.getMultiplier(); df.setMultiplier(0); if (df.getMultiplier() != mult) { errln("DecimalFormat.setMultiplier(0) did not ignore its zero input"); } // test negative multiplier df.setMultiplier(-1); if (df.getMultiplier() != -1) { errln("DecimalFormat.setMultiplier(-1) ignored its negative input"); return; } expect(df, "1122.123", -1122.123); expect(df, "-1122.123", 1122.123); expect(df, "1.2", -1.2); expect(df, "-1.2", 1.2); // Note: the tests with the final parameter of FALSE will not round trip. // The initial numeric value will format correctly, after the multiplier. // Parsing the formatted text will be out-of-range for an int64, however. // The expect() function could be modified to detect this and fall back // to looking at the decimal parsed value, but it doesn't. expect(df, U_INT64_MIN, "9223372036854775808", FALSE); expect(df, U_INT64_MIN+1, "9223372036854775807"); expect(df, (int64_t)-123, "123"); expect(df, (int64_t)123, "-123"); expect(df, U_INT64_MAX-1, "-9223372036854775806"); expect(df, U_INT64_MAX, "-9223372036854775807"); df.setMultiplier(-2); expect(df, -(U_INT64_MIN/2)-1, "-9223372036854775806"); expect(df, -(U_INT64_MIN/2), "-9223372036854775808"); expect(df, -(U_INT64_MIN/2)+1, "-9223372036854775810", FALSE); df.setMultiplier(-7); expect(df, -(U_INT64_MAX/7)-1, "9223372036854775814", FALSE); expect(df, -(U_INT64_MAX/7), "9223372036854775807"); expect(df, -(U_INT64_MAX/7)+1, "9223372036854775800"); // TODO: uncomment (and fix up) all the following int64_t tests once BigInteger is ported // (right now the big numbers get turned into doubles and lose tons of accuracy) //expect2(df, U_INT64_MAX, Int64ToUnicodeString(-U_INT64_MAX)); //expect2(df, U_INT64_MIN, UnicodeString(Int64ToUnicodeString(U_INT64_MIN), 1)); //expect2(df, U_INT64_MAX / 2, Int64ToUnicodeString(-(U_INT64_MAX / 2))); //expect2(df, U_INT64_MIN / 2, Int64ToUnicodeString(-(U_INT64_MIN / 2))); // TODO: uncomment (and fix up) once BigDecimal is ported and DecimalFormat can handle it //expect2(df, BigDecimal.valueOf(Long.MAX_VALUE), BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); //expect2(df, BigDecimal.valueOf(Long.MIN_VALUE), BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); //expect2(df, java.math.BigDecimal.valueOf(Long.MAX_VALUE), java.math.BigDecimal.valueOf(Long.MAX_VALUE).negate().toString()); //expect2(df, java.math.BigDecimal.valueOf(Long.MIN_VALUE), java.math.BigDecimal.valueOf(Long.MIN_VALUE).negate().toString()); } typedef struct { const char * stringToParse; int parsedPos; int errorIndex; UBool lenient; } TestSpaceParsingItem; void NumberFormatTest::TestSpaceParsing() { // the data are: // the string to be parsed, parsed position, parsed error index const TestSpaceParsingItem DATA[] = { {"$124", 4, -1, FALSE}, {"$124 $124", 4, -1, FALSE}, {"$124 ", 4, -1, FALSE}, {"$ 124 ", 0, 1, FALSE}, {"$\\u00A0124 ", 5, -1, FALSE}, {" $ 124 ", 0, 0, FALSE}, {"124$", 0, 4, FALSE}, {"124 $", 0, 3, FALSE}, {"$124", 4, -1, TRUE}, {"$124 $124", 4, -1, TRUE}, {"$124 ", 4, -1, TRUE}, {"$ 124 ", 5, -1, TRUE}, {"$\\u00A0124 ", 5, -1, TRUE}, {" $ 124 ", 6, -1, TRUE}, {"124$", 4, -1, TRUE}, {"124$", 4, -1, TRUE}, {"124 $", 5, -1, TRUE}, {"124 $", 5, -1, TRUE}, }; UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); NumberFormat* foo = NumberFormat::createCurrencyInstance(locale, status); if (U_FAILURE(status)) { delete foo; return; } for (uint32_t i = 0; i < UPRV_LENGTHOF(DATA); ++i) { ParsePosition parsePosition(0); UnicodeString stringToBeParsed = ctou(DATA[i].stringToParse); int parsedPosition = DATA[i].parsedPos; int errorIndex = DATA[i].errorIndex; foo->setLenient(DATA[i].lenient); Formattable result; foo->parse(stringToBeParsed, result, parsePosition); logln("Parsing: " + stringToBeParsed); if (parsePosition.getIndex() != parsedPosition || parsePosition.getErrorIndex() != errorIndex) { errln("FAILED parse " + stringToBeParsed + "; lenient: " + DATA[i].lenient + "; wrong position, expected: (" + parsedPosition + ", " + errorIndex + "); got (" + parsePosition.getIndex() + ", " + parsePosition.getErrorIndex() + ")"); } if (parsePosition.getErrorIndex() == -1 && result.getType() == Formattable::kLong && result.getLong() != 124) { errln("FAILED parse " + stringToBeParsed + "; wrong number, expect: 124, got " + result.getLong()); } } delete foo; } /** * Test using various numbering systems and numbering system keyword. */ typedef struct { const char *localeName; double value; UBool isRBNF; const char *expectedResult; } TestNumberingSystemItem; void NumberFormatTest::TestNumberingSystems() { const TestNumberingSystemItem DATA[] = { { "en_US@numbers=thai", 1234.567, FALSE, "\\u0E51,\\u0E52\\u0E53\\u0E54.\\u0E55\\u0E56\\u0E57" }, { "en_US@numbers=hebr", 5678.0, TRUE, "\\u05D4\\u05F3\\u05EA\\u05E8\\u05E2\\u05F4\\u05D7" }, { "en_US@numbers=arabext", 1234.567, FALSE, "\\u06F1\\u066c\\u06F2\\u06F3\\u06F4\\u066b\\u06F5\\u06F6\\u06F7" }, { "ar_EG", 1234.567, FALSE, "\\u0661\\u066C\\u0662\\u0663\\u0664\\u066b\\u0665\\u0666\\u0667" }, { "th_TH@numbers=traditional", 1234.567, FALSE, "\\u0E51,\\u0E52\\u0E53\\u0E54.\\u0E55\\u0E56\\u0E57" }, // fall back to native per TR35 { "ar_MA", 1234.567, FALSE, "1.234,567" }, { "en_US@numbers=hanidec", 1234.567, FALSE, "\\u4e00,\\u4e8c\\u4e09\\u56db.\\u4e94\\u516d\\u4e03" }, { "ta_IN@numbers=native", 1234.567, FALSE, "\\u0BE7,\\u0BE8\\u0BE9\\u0BEA.\\u0BEB\\u0BEC\\u0BED" }, { "ta_IN@numbers=traditional", 1235.0, TRUE, "\\u0BF2\\u0BE8\\u0BF1\\u0BE9\\u0BF0\\u0BEB" }, { "ta_IN@numbers=finance", 1234.567, FALSE, "1,234.567" }, // fall back to default per TR35 { "zh_TW@numbers=native", 1234.567, FALSE, "\\u4e00,\\u4e8c\\u4e09\\u56db.\\u4e94\\u516d\\u4e03" }, { "zh_TW@numbers=traditional", 1234.567, TRUE, "\\u4E00\\u5343\\u4E8C\\u767E\\u4E09\\u5341\\u56DB\\u9EDE\\u4E94\\u516D\\u4E03" }, { "zh_TW@numbers=finance", 1234.567, TRUE, "\\u58F9\\u4EDF\\u8CB3\\u4F70\\u53C3\\u62FE\\u8086\\u9EDE\\u4F0D\\u9678\\u67D2" }, { NULL, 0, FALSE, NULL } }; UErrorCode ec; const TestNumberingSystemItem *item; for (item = DATA; item->localeName != NULL; item++) { ec = U_ZERO_ERROR; Locale loc = Locale::createFromName(item->localeName); NumberFormat *origFmt = NumberFormat::createInstance(loc,ec); if (U_FAILURE(ec)) { dataerrln("FAIL: getInstance(%s) - %s", item->localeName, u_errorName(ec)); continue; } // Clone to test ticket #10682 NumberFormat *fmt = (NumberFormat *) origFmt->clone(); delete origFmt; if (item->isRBNF) { expect3(*fmt,item->value,CharsToUnicodeString(item->expectedResult)); } else { expect2(*fmt,item->value,CharsToUnicodeString(item->expectedResult)); } delete fmt; } // Test bogus keyword value ec = U_ZERO_ERROR; Locale loc4 = Locale::createFromName("en_US@numbers=foobar"); NumberFormat* fmt4= NumberFormat::createInstance(loc4, ec); if ( ec != U_UNSUPPORTED_ERROR ) { errln("FAIL: getInstance(en_US@numbers=foobar) should have returned U_UNSUPPORTED_ERROR"); delete fmt4; } ec = U_ZERO_ERROR; NumberingSystem *ns = NumberingSystem::createInstance(ec); if (U_FAILURE(ec)) { dataerrln("FAIL: NumberingSystem::createInstance(ec); - %s", u_errorName(ec)); } if ( ns != NULL ) { ns->getDynamicClassID(); ns->getStaticClassID(); } else { errln("FAIL: getInstance() returned NULL."); } NumberingSystem *ns1 = new NumberingSystem(*ns); if (ns1 == NULL) { errln("FAIL: NumberSystem copy constructor returned NULL."); } delete ns1; delete ns; } void NumberFormatTest::TestMultiCurrencySign() { const char* DATA[][6] = { // the fields in the following test are: // locale, // currency pattern (with negative pattern), // currency number to be formatted, // currency format using currency symbol name, such as "$" for USD, // currency format using currency ISO name, such as "USD", // currency format using plural name, such as "US dollars". // for US locale {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "1234.56", "$1,234.56", "USD\\u00A01,234.56", "US dollars\\u00A01,234.56"}, {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "-1234.56", "-$1,234.56", "-USD\\u00A01,234.56", "-US dollars\\u00A01,234.56"}, {"en_US", "\\u00A4#,##0.00;-\\u00A4#,##0.00", "1", "$1.00", "USD\\u00A01.00", "US dollars\\u00A01.00"}, // for CHINA locale {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "1234.56", "\\uFFE51,234.56", "CNY\\u00A01,234.56", "\\u4EBA\\u6C11\\u5E01\\u00A01,234.56"}, {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "-1234.56", "(\\uFFE51,234.56)", "(CNY\\u00A01,234.56)", "(\\u4EBA\\u6C11\\u5E01\\u00A01,234.56)"}, {"zh_CN", "\\u00A4#,##0.00;(\\u00A4#,##0.00)", "1", "\\uFFE51.00", "CNY\\u00A01.00", "\\u4EBA\\u6C11\\u5E01\\u00A01.00"} }; const UChar doubleCurrencySign[] = {0xA4, 0xA4, 0}; UnicodeString doubleCurrencyStr(doubleCurrencySign); const UChar tripleCurrencySign[] = {0xA4, 0xA4, 0xA4, 0}; UnicodeString tripleCurrencyStr(tripleCurrencySign); for (uint32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { const char* locale = DATA[i][0]; UnicodeString pat = ctou(DATA[i][1]); double numberToBeFormat = atof(DATA[i][2]); UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale(locale), status); if (U_FAILURE(status)) { delete sym; continue; } for (int j=1; j<=3; ++j) { // j represents the number of currency sign in the pattern. if (j == 2) { pat = pat.findAndReplace(ctou("\\u00A4"), doubleCurrencyStr); } else if (j == 3) { pat = pat.findAndReplace(ctou("\\u00A4\\u00A4"), tripleCurrencyStr); } DecimalFormat* fmt = new DecimalFormat(pat, new DecimalFormatSymbols(*sym), status); if (U_FAILURE(status)) { errln("FAILED init DecimalFormat "); delete fmt; continue; } UnicodeString s; ((NumberFormat*) fmt)->format(numberToBeFormat, s); // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. // DATA[i][j+2] is the currency format result using // 'j' number of currency sign. UnicodeString currencyFormatResult = ctou(DATA[i][2+j]); if (s.compare(currencyFormatResult)) { errln("FAIL format: Expected " + currencyFormatResult + "; Got " + s); } // mix style parsing for (int k=3; k<=5; ++k) { // DATA[i][3] is the currency format result using a // single currency sign. // DATA[i][4] is the currency format result using // double currency sign. // DATA[i][5] is the currency format result using // triple currency sign. UnicodeString oneCurrencyFormat = ctou(DATA[i][k]); UErrorCode status = U_ZERO_ERROR; Formattable parseRes; fmt->parse(oneCurrencyFormat, parseRes, status); if (U_FAILURE(status) || (parseRes.getType() == Formattable::kDouble && parseRes.getDouble() != numberToBeFormat) || (parseRes.getType() == Formattable::kLong && parseRes.getLong() != numberToBeFormat)) { errln("FAILED parse " + oneCurrencyFormat + "; (i, j, k): " + i + ", " + j + ", " + k); } } delete fmt; } delete sym; } } void NumberFormatTest::TestCurrencyFormatForMixParsing() { UErrorCode status = U_ZERO_ERROR; MeasureFormat* curFmt = MeasureFormat::createCurrencyFormat(Locale("en_US"), status); if (U_FAILURE(status)) { delete curFmt; return; } const char* formats[] = { "$1,234.56", // string to be parsed "USD1,234.56", "US dollars1,234.56", // "1,234.56 US dollars" // Fails in 62 because currency format is not compatible with pattern. }; const CurrencyAmount* curramt = NULL; for (uint32_t i = 0; i < UPRV_LENGTHOF(formats); ++i) { UnicodeString stringToBeParsed = ctou(formats[i]); logln(UnicodeString("stringToBeParsed: ") + stringToBeParsed); Formattable result; UErrorCode status = U_ZERO_ERROR; curFmt->parseObject(stringToBeParsed, result, status); if (U_FAILURE(status)) { errln("FAIL: measure format parsing: '%s' ec: %s", formats[i], u_errorName(status)); } else if (result.getType() != Formattable::kObject || (curramt = dynamic_cast<const CurrencyAmount*>(result.getObject())) == NULL || curramt->getNumber().getDouble() != 1234.56 || UnicodeString(curramt->getISOCurrency()).compare(ISO_CURRENCY_USD) ) { errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number "); if (curramt->getNumber().getDouble() != 1234.56) { errln((UnicodeString)"wong number, expect: 1234.56" + ", got: " + curramt->getNumber().getDouble()); } if (curramt->getISOCurrency() != ISO_CURRENCY_USD) { errln((UnicodeString)"wong currency, expect: USD" + ", got: " + curramt->getISOCurrency()); } } } delete curFmt; } /** Starting in ICU 62, strict mode is actually strict with currency formats. */ void NumberFormatTest::TestMismatchedCurrencyFormatFail() { IcuTestErrorCode status(*this, "TestMismatchedCurrencyFormatFail"); LocalPointer<DecimalFormat> df( dynamic_cast<DecimalFormat*>(DecimalFormat::createCurrencyInstance("en", status)), status); if (!assertSuccess("createCurrencyInstance() failed.", status, true, __FILE__, __LINE__)) {return;} UnicodeString pattern; assertEquals("Test assumes that currency sign is at the beginning", u"\u00A4#,##0.00", df->toPattern(pattern)); // Should round-trip on the correct currency format: expect2(*df, 1.23, u"\u00A41.23"); df->setCurrency(u"EUR", status); expect2(*df, 1.23, u"\u20AC1.23"); // Should parse with currency in the wrong place in lenient mode df->setLenient(TRUE); expect(*df, u"1.23\u20AC", 1.23); expectParseCurrency(*df, u"EUR", 1.23, "1.23\\u20AC"); // Should NOT parse with currency in the wrong place in STRICT mode df->setLenient(FALSE); { Formattable result; ErrorCode failStatus; df->parse(u"1.23\u20AC", result, failStatus); assertEquals("Should fail to parse", U_INVALID_FORMAT_ERROR, failStatus); } { ParsePosition ppos; df->parseCurrency(u"1.23\u20AC", ppos); assertEquals("Should fail to parse currency", 0, ppos.getIndex()); } } void NumberFormatTest::TestDecimalFormatCurrencyParse() { // Locale.US UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols* sym = new DecimalFormatSymbols(Locale("en_US"), status); if (U_FAILURE(status)) { delete sym; return; } UnicodeString pat; UChar currency = 0x00A4; // "\xA4#,##0.00;-\xA4#,##0.00" pat.append(currency).append(currency).append(currency).append("#,##0.00;-").append(currency).append(currency).append(currency).append("#,##0.00"); DecimalFormat* fmt = new DecimalFormat(pat, sym, status); if (U_FAILURE(status)) { delete fmt; errln("failed to new DecimalFormat in TestDecimalFormatCurrencyParse"); return; } const char* DATA[][2] = { // the data are: // string to be parsed, the parsed result (number) {"$1.00", "1"}, {"USD1.00", "1"}, {"1.00 US dollar", "1"}, {"$1,234.56", "1234.56"}, {"USD1,234.56", "1234.56"}, {"1,234.56 US dollar", "1234.56"}, }; // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. fmt->setLenient(TRUE); for (uint32_t i = 0; i < UPRV_LENGTHOF(DATA); ++i) { UnicodeString stringToBeParsed = ctou(DATA[i][0]); double parsedResult = atof(DATA[i][1]); UErrorCode status = U_ZERO_ERROR; Formattable result; fmt->parse(stringToBeParsed, result, status); logln((UnicodeString)"Input: " + stringToBeParsed + "; output: " + result.getDouble(status)); if (U_FAILURE(status) || (result.getType() == Formattable::kDouble && result.getDouble() != parsedResult) || (result.getType() == Formattable::kLong && result.getLong() != parsedResult)) { errln((UnicodeString)"FAIL parse: Expected " + parsedResult); } } delete fmt; } void NumberFormatTest::TestCurrencyIsoPluralFormat() { static const char* DATA[][6] = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00 US dollars"}, {"en_US", "1234.56", "USD", "$1,234.56", "USD\\u00A01,234.56", "1,234.56 US dollars"}, {"en_US", "-1234.56", "USD", "-$1,234.56", "-USD\\u00A01,234.56", "-1,234.56 US dollars"}, {"zh_CN", "1", "USD", "US$1.00", "USD\\u00A01.00", "1.00\\u00A0\\u7F8E\\u5143"}, {"zh_CN", "1234.56", "USD", "US$1,234.56", "USD\\u00A01,234.56", "1,234.56\\u00A0\\u7F8E\\u5143"}, {"zh_CN", "1", "CNY", "\\uFFE51.00", "CNY\\u00A01.00", "1.00\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"zh_CN", "1234.56", "CNY", "\\uFFE51,234.56", "CNY\\u00A01,234.56", "1,234.56\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"ru_RU", "1", "RUB", "1,00\\u00A0\\u20BD", "1,00\\u00A0RUB", "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, {"ru_RU", "2", "RUB", "2,00\\u00A0\\u20BD", "2,00\\u00A0RUB", "2,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, {"ru_RU", "5", "RUB", "5,00\\u00A0\\u20BD", "5,00\\u00A0RUB", "5,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"}, // test locale without currency information {"root", "-1.23", "USD", "-US$\\u00A01.23", "-USD\\u00A01.23", "-1.23 USD"}, // test choice format {"es_AR", "1", "INR", "INR\\u00A01,00", "INR\\u00A01,00", "1,00 rupia india"}, }; static const UNumberFormatStyle currencyStyles[] = { UNUM_CURRENCY, UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL }; for (int32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { const char* localeString = DATA[i][0]; double numberToBeFormat = atof(DATA[i][1]); const char* currencyISOCode = DATA[i][2]; logln(UnicodeString(u"Locale: ") + localeString + "; amount: " + numberToBeFormat); Locale locale(localeString); for (int32_t kIndex = 0; kIndex < UPRV_LENGTHOF(currencyStyles); ++kIndex) { UNumberFormatStyle k = currencyStyles[kIndex]; logln(UnicodeString(u"UNumberFormatStyle: ") + k); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, k, status); if (U_FAILURE(status)) { delete numFmt; dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } UChar currencyCode[4]; u_charsToUChars(currencyISOCode, currencyCode, 4); numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; errln((UnicodeString)"can not set currency:" + currencyISOCode); continue; } UnicodeString strBuf; numFmt->format(numberToBeFormat, strBuf); int resultDataIndex = 3 + kIndex; // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. UnicodeString formatResult = ctou(DATA[i][resultDataIndex]); if (strBuf.compare(formatResult)) { errln("FAIL: Expected " + formatResult + " actual: " + strBuf); } // test parsing, and test parsing for all currency formats. // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. UnicodeString oneCurrencyFormatResult = ctou(DATA[i][j]); UErrorCode status = U_ZERO_ERROR; Formattable parseResult; numFmt->parse(oneCurrencyFormatResult, parseResult, status); if (U_FAILURE(status) || (parseResult.getType() == Formattable::kDouble && parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { errln((UnicodeString)"FAIL: getCurrencyFormat of locale " + localeString + " failed roundtripping the number"); if (parseResult.getType() == Formattable::kDouble) { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getDouble()); } else { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual: " +parseResult.getLong()); } } } delete numFmt; } } } void NumberFormatTest::TestCurrencyParsing() { static const char* DATA[][6] = { // the data are: // locale, // currency amount to be formatted, // currency ISO code to be formatted, // format result using CURRENCYSTYLE, // format result using ISOCURRENCYSTYLE, // format result using PLURALCURRENCYSTYLE, {"en_US", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00 US dollars"}, {"pa_IN", "1", "USD", "US$\\u00A01.00", "USD\\u00A01.00", "1.00 \\u0a2f\\u0a42.\\u0a10\\u0a38. \\u0a21\\u0a3e\\u0a32\\u0a30"}, {"es_AR", "1", "USD", "US$\\u00A01,00", "USD\\u00A01,00", "1,00 d\\u00f3lar estadounidense"}, {"ar_EG", "1", "USD", "\\u0661\\u066b\\u0660\\u0660\\u00a0US$", "\\u0661\\u066b\\u0660\\u0660\\u00a0USD", "\\u0661\\u066b\\u0660\\u0660 \\u062f\\u0648\\u0644\\u0627\\u0631 \\u0623\\u0645\\u0631\\u064a\\u0643\\u064a"}, {"fa_CA", "1", "USD", "\\u200e$\\u06f1\\u066b\\u06f0\\u06f0", "\\u200eUSD\\u06f1\\u066b\\u06f0\\u06f0", "\\u06f1\\u066b\\u06f0\\u06f0 \\u062f\\u0644\\u0627\\u0631 \\u0627\\u0645\\u0631\\u06cc\\u06a9\\u0627"}, {"he_IL", "1", "USD", "\\u200f1.00\\u00a0$", "\\u200f1.00\\u00a0USD", "1.00 \\u05d3\\u05d5\\u05dc\\u05e8 \\u05d0\\u05de\\u05e8\\u05d9\\u05e7\\u05d0\\u05d9"}, {"hr_HR", "1", "USD", "1,00\\u00a0USD", "1,00\\u00a0USD", "1,00 ameri\\u010Dkih dolara"}, {"id_ID", "1", "USD", "US$\\u00A01,00", "USD\\u00A01,00", "1,00 Dolar Amerika Serikat"}, {"it_IT", "1", "USD", "1,00\\u00a0USD", "1,00\\u00a0USD", "1,00 dollari statunitensi"}, {"ko_KR", "1", "USD", "US$\\u00A01.00", "USD\\u00A01.00", "1.00 \\ubbf8\\uad6d \\ub2ec\\ub7ec"}, {"ja_JP", "1", "USD", "$1.00", "USD\\u00A01.00", "1.00\\u00A0\\u7c73\\u30c9\\u30eb"}, {"zh_CN", "1", "CNY", "\\uFFE51.00", "CNY\\u00A001.00", "1.00\\u00A0\\u4EBA\\u6C11\\u5E01"}, {"zh_TW", "1", "CNY", "CN\\u00A51.00", "CNY\\u00A01.00", "1.00 \\u4eba\\u6c11\\u5e63"}, {"zh_Hant", "1", "CNY", "CN\\u00A51.00", "CNY\\u00A01.00", "1.00 \\u4eba\\u6c11\\u5e63"}, {"zh_Hant", "1", "JPY", "\\u00A51.00", "JPY\\u00A01.00", "1 \\u65E5\\u5713"}, {"ja_JP", "1", "JPY", "\\uFFE51.00", "JPY\\u00A01.00", "1\\u00A0\\u5186"}, // ICU 62 requires #parseCurrency() to recognize variants when parsing // {"ja_JP", "1", "JPY", "\\u00A51.00", "JPY\\u00A01.00", "1\\u00A0\\u5186"}, {"ru_RU", "1", "RUB", "1,00\\u00A0\\u00A0\\u20BD", "1,00\\u00A0\\u00A0RUB", "1,00 \\u0440\\u043E\\u0441\\u0441\\u0438\\u0439\\u0441\\u043A\\u043E\\u0433\\u043E \\u0440\\u0443\\u0431\\u043B\\u044F"} }; static const UNumberFormatStyle currencyStyles[] = { UNUM_CURRENCY, UNUM_CURRENCY_ISO, UNUM_CURRENCY_PLURAL }; static const char* currencyStyleNames[] = { "UNUM_CURRENCY", "UNUM_CURRENCY_ISO", "UNUM_CURRENCY_PLURAL" }; #ifdef NUMFMTST_CACHE_DEBUG int deadloop = 0; for (;;) { printf("loop: %d\n", deadloop++); #endif for (uint32_t i=0; i< UPRV_LENGTHOF(DATA); ++i) { /* i = test case # - should be i=0*/ for (int32_t kIndex = 2; kIndex < UPRV_LENGTHOF(currencyStyles); ++kIndex) { UNumberFormatStyle k = currencyStyles[kIndex]; /* k = style */ const char* localeString = DATA[i][0]; double numberToBeFormat = atof(DATA[i][1]); const char* currencyISOCode = DATA[i][2]; Locale locale(localeString); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, k, status); logln("#%d NumberFormat(%s, %s) Currency=%s\n", i, localeString, currencyStyleNames[kIndex], currencyISOCode); if (U_FAILURE(status)) { delete numFmt; dataerrln((UnicodeString)"can not create instance, locale:" + localeString + ", style: " + k + " - " + u_errorName(status)); continue; } UChar currencyCode[4]; u_charsToUChars(currencyISOCode, currencyCode, 4); numFmt->setCurrency(currencyCode, status); if (U_FAILURE(status)) { delete numFmt; errln((UnicodeString)"can not set currency:" + currencyISOCode); continue; } UnicodeString strBuf; numFmt->format(numberToBeFormat, strBuf); int resultDataIndex = 3 + kIndex; // DATA[i][resultDataIndex] is the currency format result // using 'k' currency style. UnicodeString formatResult = ctou(DATA[i][resultDataIndex]); if (strBuf.compare(formatResult)) { errln("FAIL: Expected " + formatResult + " actual: " + strBuf); } // test parsing, and test parsing for all currency formats. // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); for (int j = 3; j < 6; ++j) { // DATA[i][3] is the currency format result using // CURRENCYSTYLE formatter. // DATA[i][4] is the currency format result using // ISOCURRENCYSTYLE formatter. // DATA[i][5] is the currency format result using // PLURALCURRENCYSTYLE formatter. UnicodeString oneCurrencyFormatResult = ctou(DATA[i][j]); UErrorCode status = U_ZERO_ERROR; Formattable parseResult; logln("parse(%s)", DATA[i][j]); numFmt->parse(oneCurrencyFormatResult, parseResult, status); if (U_FAILURE(status) || (parseResult.getType() == Formattable::kDouble && parseResult.getDouble() != numberToBeFormat) || (parseResult.getType() == Formattable::kLong && parseResult.getLong() != numberToBeFormat)) { errln((UnicodeString)"FAIL: NumberFormat(" + localeString +", " + currencyStyleNames[kIndex] + "), Currency="+currencyISOCode+", parse("+DATA[i][j]+") returned error " + (UnicodeString)u_errorName(status)+". Testcase: data[" + i + "][" + currencyStyleNames[j-3] +"="+j+"]"); if (parseResult.getType() == Formattable::kDouble) { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (double): " +parseResult.getDouble()); } else { errln((UnicodeString)"expected: " + numberToBeFormat + "; actual (long): " +parseResult.getLong()); } errln((UnicodeString)" round-trip would be: " + strBuf); } } delete numFmt; } } #ifdef NUMFMTST_CACHE_DEBUG } #endif } void NumberFormatTest::TestParseCurrencyInUCurr() { const char* DATA[] = { "1.00 US DOLLAR", // case in-sensitive "$1.00", "USD1.00", "usd1.00", // case in-sensitive: #13696 "US dollar1.00", "US dollars1.00", "$1.00", "A$1.00", "ADP1.00", "ADP1.00", "AED1.00", "AED1.00", "AFA1.00", "AFA1.00", "AFN1.00", "ALL1.00", "AMD1.00", "ANG1.00", "AOA1.00", "AOK1.00", "AOK1.00", "AON1.00", "AON1.00", "AOR1.00", "AOR1.00", "ARS1.00", "ARA1.00", "ARA1.00", "ARP1.00", "ARP1.00", "ARS1.00", "ATS1.00", "ATS1.00", "AUD1.00", "AWG1.00", "AZM1.00", "AZM1.00", "AZN1.00", "Afghan Afghani (1927\\u20132002)1.00", "Afghan afghani (1927\\u20132002)1.00", "Afghan Afghani1.00", "Afghan Afghanis1.00", "Albanian Lek1.00", "Albanian lek1.00", "Albanian lek\\u00eb1.00", "Algerian Dinar1.00", "Algerian dinar1.00", "Algerian dinars1.00", "Andorran Peseta1.00", "Andorran peseta1.00", "Andorran pesetas1.00", "Angolan Kwanza (1977\\u20131991)1.00", "Angolan Readjusted Kwanza (1995\\u20131999)1.00", "Angolan Kwanza1.00", "Angolan New Kwanza (1990\\u20132000)1.00", "Angolan kwanza (1977\\u20131991)1.00", "Angolan readjusted kwanza (1995\\u20131999)1.00", "Angolan kwanza1.00", "Angolan kwanzas (1977\\u20131991)1.00", "Angolan readjusted kwanzas (1995\\u20131999)1.00", "Angolan kwanzas1.00", "Angolan new kwanza (1990\\u20132000)1.00", "Angolan new kwanzas (1990\\u20132000)1.00", "Argentine Austral1.00", "Argentine Peso (1983\\u20131985)1.00", "Argentine Peso1.00", "Argentine austral1.00", "Argentine australs1.00", "Argentine peso (1983\\u20131985)1.00", "Argentine peso1.00", "Argentine pesos (1983\\u20131985)1.00", "Argentine pesos1.00", "Armenian Dram1.00", "Armenian dram1.00", "Armenian drams1.00", "Aruban Florin1.00", "Aruban florin1.00", "Australian Dollar1.00", "Australian dollar1.00", "Australian dollars1.00", "Austrian Schilling1.00", "Austrian schilling1.00", "Austrian schillings1.00", "Azerbaijani Manat (1993\\u20132006)1.00", "Azerbaijani Manat1.00", "Azerbaijani manat (1993\\u20132006)1.00", "Azerbaijani manat1.00", "Azerbaijani manats (1993\\u20132006)1.00", "Azerbaijani manats1.00", "BAD1.00", "BAD1.00", "BAM1.00", "BBD1.00", "BDT1.00", "BEC1.00", "BEC1.00", "BEF1.00", "BEL1.00", "BEL1.00", "BGL1.00", "BGN1.00", "BGN1.00", "BHD1.00", "BIF1.00", "BMD1.00", "BND1.00", "BOB1.00", "BOP1.00", "BOP1.00", "BOV1.00", "BOV1.00", "BRB1.00", "BRB1.00", "BRC1.00", "BRC1.00", "BRE1.00", "BRE1.00", "BRL1.00", "BRN1.00", "BRN1.00", "BRR1.00", "BRR1.00", "BSD1.00", "BSD1.00", "BTN1.00", "BUK1.00", "BUK1.00", "BWP1.00", "BYB1.00", "BYB1.00", "BYR1.00", "BZD1.00", "Bahamian Dollar1.00", "Bahamian dollar1.00", "Bahamian dollars1.00", "Bahraini Dinar1.00", "Bahraini dinar1.00", "Bahraini dinars1.00", "Bangladeshi Taka1.00", "Bangladeshi taka1.00", "Bangladeshi takas1.00", "Barbadian Dollar1.00", "Barbadian dollar1.00", "Barbadian dollars1.00", "Belarusian Ruble (1994\\u20131999)1.00", "Belarusian Ruble1.00", "Belarusian ruble (1994\\u20131999)1.00", "Belarusian rubles (1994\\u20131999)1.00", "Belarusian ruble1.00", "Belarusian rubles1.00", "Belgian Franc (convertible)1.00", "Belgian Franc (financial)1.00", "Belgian Franc1.00", "Belgian franc (convertible)1.00", "Belgian franc (financial)1.00", "Belgian franc1.00", "Belgian francs (convertible)1.00", "Belgian francs (financial)1.00", "Belgian francs1.00", "Belize Dollar1.00", "Belize dollar1.00", "Belize dollars1.00", "Bermudan Dollar1.00", "Bermudan dollar1.00", "Bermudan dollars1.00", "Bhutanese Ngultrum1.00", "Bhutanese ngultrum1.00", "Bhutanese ngultrums1.00", "Bolivian Mvdol1.00", "Bolivian Peso1.00", "Bolivian mvdol1.00", "Bolivian mvdols1.00", "Bolivian peso1.00", "Bolivian pesos1.00", "Bolivian Boliviano1.00", "Bolivian Boliviano1.00", "Bolivian Bolivianos1.00", "Bosnia-Herzegovina Convertible Mark1.00", "Bosnia-Herzegovina Dinar (1992\\u20131994)1.00", "Bosnia-Herzegovina convertible mark1.00", "Bosnia-Herzegovina convertible marks1.00", "Bosnia-Herzegovina dinar (1992\\u20131994)1.00", "Bosnia-Herzegovina dinars (1992\\u20131994)1.00", "Botswanan Pula1.00", "Botswanan pula1.00", "Botswanan pulas1.00", "Brazilian New Cruzado (1989\\u20131990)1.00", "Brazilian Cruzado (1986\\u20131989)1.00", "Brazilian Cruzeiro (1990\\u20131993)1.00", "Brazilian New Cruzeiro (1967\\u20131986)1.00", "Brazilian Cruzeiro (1993\\u20131994)1.00", "Brazilian Real1.00", "Brazilian new cruzado (1989\\u20131990)1.00", "Brazilian new cruzados (1989\\u20131990)1.00", "Brazilian cruzado (1986\\u20131989)1.00", "Brazilian cruzados (1986\\u20131989)1.00", "Brazilian cruzeiro (1990\\u20131993)1.00", "Brazilian new cruzeiro (1967\\u20131986)1.00", "Brazilian cruzeiro (1993\\u20131994)1.00", "Brazilian cruzeiros (1990\\u20131993)1.00", "Brazilian new cruzeiros (1967\\u20131986)1.00", "Brazilian cruzeiros (1993\\u20131994)1.00", "Brazilian real1.00", "Brazilian reals1.00", "British Pound1.00", "British pound1.00", "British pounds1.00", "Brunei Dollar1.00", "Brunei dollar1.00", "Brunei dollars1.00", "Bulgarian Hard Lev1.00", "Bulgarian Lev1.00", "Bulgarian Leva1.00", "Bulgarian hard lev1.00", "Bulgarian hard leva1.00", "Bulgarian lev1.00", "Burmese Kyat1.00", "Burmese kyat1.00", "Burmese kyats1.00", "Burundian Franc1.00", "Burundian franc1.00", "Burundian francs1.00", "CA$1.00", "CAD1.00", "CDF1.00", "CDF1.00", "West African CFA Franc1.00", "Central African CFA Franc1.00", "West African CFA franc1.00", "Central African CFA franc1.00", "West African CFA francs1.00", "Central African CFA francs1.00", "CFP Franc1.00", "CFP franc1.00", "CFP francs1.00", "CFPF1.00", "CHE1.00", "CHE1.00", "CHF1.00", "CHW1.00", "CHW1.00", "CLF1.00", "CLF1.00", "CLP1.00", "CNY1.00", "COP1.00", "COU1.00", "COU1.00", "CRC1.00", "CSD1.00", "CSD1.00", "CSK1.00", "CSK1.00", "CUP1.00", "CUP1.00", "CVE1.00", "CYP1.00", "CZK1.00", "Cambodian Riel1.00", "Cambodian riel1.00", "Cambodian riels1.00", "Canadian Dollar1.00", "Canadian dollar1.00", "Canadian dollars1.00", "Cape Verdean Escudo1.00", "Cape Verdean escudo1.00", "Cape Verdean escudos1.00", "Cayman Islands Dollar1.00", "Cayman Islands dollar1.00", "Cayman Islands dollars1.00", "Chilean Peso1.00", "Chilean Unit of Account (UF)1.00", "Chilean peso1.00", "Chilean pesos1.00", "Chilean unit of account (UF)1.00", "Chilean units of account (UF)1.00", "Chinese Yuan1.00", "Chinese yuan1.00", "Colombian Peso1.00", "Colombian peso1.00", "Colombian pesos1.00", "Comorian Franc1.00", "Comorian franc1.00", "Comorian francs1.00", "Congolese Franc1.00", "Congolese franc1.00", "Congolese francs1.00", "Costa Rican Col\\u00f3n1.00", "Costa Rican col\\u00f3n1.00", "Costa Rican col\\u00f3ns1.00", "Croatian Dinar1.00", "Croatian Kuna1.00", "Croatian dinar1.00", "Croatian dinars1.00", "Croatian kuna1.00", "Croatian kunas1.00", "Cuban Peso1.00", "Cuban peso1.00", "Cuban pesos1.00", "Cypriot Pound1.00", "Cypriot pound1.00", "Cypriot pounds1.00", "Czech Koruna1.00", "Czech koruna1.00", "Czech korunas1.00", "Czechoslovak Hard Koruna1.00", "Czechoslovak hard koruna1.00", "Czechoslovak hard korunas1.00", "DDM1.00", "DDM1.00", "DEM1.00", "DEM1.00", "DJF1.00", "DKK1.00", "DOP1.00", "DZD1.00", "Danish Krone1.00", "Danish krone1.00", "Danish kroner1.00", "German Mark1.00", "German mark1.00", "German marks1.00", "Djiboutian Franc1.00", "Djiboutian franc1.00", "Djiboutian francs1.00", "Dominican Peso1.00", "Dominican peso1.00", "Dominican pesos1.00", "EC$1.00", "ECS1.00", "ECS1.00", "ECV1.00", "ECV1.00", "EEK1.00", "EEK1.00", "EGP1.00", "EGP1.00", "ERN1.00", "ERN1.00", "ESA1.00", "ESA1.00", "ESB1.00", "ESB1.00", "ESP1.00", "ETB1.00", "EUR1.00", "East Caribbean Dollar1.00", "East Caribbean dollar1.00", "East Caribbean dollars1.00", "East German Mark1.00", "East German mark1.00", "East German marks1.00", "Ecuadorian Sucre1.00", "Ecuadorian Unit of Constant Value1.00", "Ecuadorian sucre1.00", "Ecuadorian sucres1.00", "Ecuadorian unit of constant value1.00", "Ecuadorian units of constant value1.00", "Egyptian Pound1.00", "Egyptian pound1.00", "Egyptian pounds1.00", "Salvadoran Col\\u00f3n1.00", "Salvadoran col\\u00f3n1.00", "Salvadoran colones1.00", "Equatorial Guinean Ekwele1.00", "Equatorial Guinean ekwele1.00", "Eritrean Nakfa1.00", "Eritrean nakfa1.00", "Eritrean nakfas1.00", "Estonian Kroon1.00", "Estonian kroon1.00", "Estonian kroons1.00", "Ethiopian Birr1.00", "Ethiopian birr1.00", "Ethiopian birrs1.00", "Euro1.00", "European Composite Unit1.00", "European Currency Unit1.00", "European Monetary Unit1.00", "European Unit of Account (XBC)1.00", "European Unit of Account (XBD)1.00", "European composite unit1.00", "European composite units1.00", "European currency unit1.00", "European currency units1.00", "European monetary unit1.00", "European monetary units1.00", "European unit of account (XBC)1.00", "European unit of account (XBD)1.00", "European units of account (XBC)1.00", "European units of account (XBD)1.00", "FIM1.00", "FIM1.00", "FJD1.00", "FKP1.00", "FKP1.00", "FRF1.00", "FRF1.00", "Falkland Islands Pound1.00", "Falkland Islands pound1.00", "Falkland Islands pounds1.00", "Fijian Dollar1.00", "Fijian dollar1.00", "Fijian dollars1.00", "Finnish Markka1.00", "Finnish markka1.00", "Finnish markkas1.00", "CHF1.00", "French Franc1.00", "French Gold Franc1.00", "French UIC-Franc1.00", "French UIC-franc1.00", "French UIC-francs1.00", "French franc1.00", "French francs1.00", "French gold franc1.00", "French gold francs1.00", "GBP1.00", "GEK1.00", "GEK1.00", "GEL1.00", "GHC1.00", "GHC1.00", "GHS1.00", "GIP1.00", "GIP1.00", "GMD1.00", "GMD1.00", "GNF1.00", "GNS1.00", "GNS1.00", "GQE1.00", "GQE1.00", "GRD1.00", "GRD1.00", "GTQ1.00", "GWE1.00", "GWE1.00", "GWP1.00", "GWP1.00", "GYD1.00", "Gambian Dalasi1.00", "Gambian dalasi1.00", "Gambian dalasis1.00", "Georgian Kupon Larit1.00", "Georgian Lari1.00", "Georgian kupon larit1.00", "Georgian kupon larits1.00", "Georgian lari1.00", "Georgian laris1.00", "Ghanaian Cedi (1979\\u20132007)1.00", "Ghanaian Cedi1.00", "Ghanaian cedi (1979\\u20132007)1.00", "Ghanaian cedi1.00", "Ghanaian cedis (1979\\u20132007)1.00", "Ghanaian cedis1.00", "Gibraltar Pound1.00", "Gibraltar pound1.00", "Gibraltar pounds1.00", "Gold1.00", "Gold1.00", "Greek Drachma1.00", "Greek drachma1.00", "Greek drachmas1.00", "Guatemalan Quetzal1.00", "Guatemalan quetzal1.00", "Guatemalan quetzals1.00", "Guinean Franc1.00", "Guinean Syli1.00", "Guinean franc1.00", "Guinean francs1.00", "Guinean syli1.00", "Guinean sylis1.00", "Guinea-Bissau Peso1.00", "Guinea-Bissau peso1.00", "Guinea-Bissau pesos1.00", "Guyanaese Dollar1.00", "Guyanaese dollar1.00", "Guyanaese dollars1.00", "HK$1.00", "HKD1.00", "HNL1.00", "HRD1.00", "HRD1.00", "HRK1.00", "HRK1.00", "HTG1.00", "HTG1.00", "HUF1.00", "Haitian Gourde1.00", "Haitian gourde1.00", "Haitian gourdes1.00", "Honduran Lempira1.00", "Honduran lempira1.00", "Honduran lempiras1.00", "Hong Kong Dollar1.00", "Hong Kong dollar1.00", "Hong Kong dollars1.00", "Hungarian Forint1.00", "Hungarian forint1.00", "Hungarian forints1.00", "IDR1.00", "IEP1.00", "ILP1.00", "ILP1.00", "ILS1.00", "INR1.00", "IQD1.00", "IRR1.00", "ISK1.00", "ISK1.00", "ITL1.00", "Icelandic Kr\\u00f3na1.00", "Icelandic kr\\u00f3na1.00", "Icelandic kr\\u00f3nur1.00", "Indian Rupee1.00", "Indian rupee1.00", "Indian rupees1.00", "Indonesian Rupiah1.00", "Indonesian rupiah1.00", "Indonesian rupiahs1.00", "Iranian Rial1.00", "Iranian rial1.00", "Iranian rials1.00", "Iraqi Dinar1.00", "Iraqi dinar1.00", "Iraqi dinars1.00", "Irish Pound1.00", "Irish pound1.00", "Irish pounds1.00", "Israeli Pound1.00", "Israeli new shekel1.00", "Israeli pound1.00", "Israeli pounds1.00", "Italian Lira1.00", "Italian lira1.00", "Italian liras1.00", "JMD1.00", "JOD1.00", "JPY1.00", "Jamaican Dollar1.00", "Jamaican dollar1.00", "Jamaican dollars1.00", "Japanese Yen1.00", "Japanese yen1.00", "Jordanian Dinar1.00", "Jordanian dinar1.00", "Jordanian dinars1.00", "KES1.00", "KGS1.00", "KHR1.00", "KMF1.00", "KPW1.00", "KPW1.00", "KRW1.00", "KWD1.00", "KYD1.00", "KYD1.00", "KZT1.00", "Kazakhstani Tenge1.00", "Kazakhstani tenge1.00", "Kazakhstani tenges1.00", "Kenyan Shilling1.00", "Kenyan shilling1.00", "Kenyan shillings1.00", "Kuwaiti Dinar1.00", "Kuwaiti dinar1.00", "Kuwaiti dinars1.00", "Kyrgystani Som1.00", "Kyrgystani som1.00", "Kyrgystani soms1.00", "HNL1.00", "LAK1.00", "LAK1.00", "LBP1.00", "LKR1.00", "LRD1.00", "LRD1.00", "LSL1.00", "LTL1.00", "LTL1.00", "LTT1.00", "LTT1.00", "LUC1.00", "LUC1.00", "LUF1.00", "LUF1.00", "LUL1.00", "LUL1.00", "LVL1.00", "LVL1.00", "LVR1.00", "LVR1.00", "LYD1.00", "Laotian Kip1.00", "Laotian kip1.00", "Laotian kips1.00", "Latvian Lats1.00", "Latvian Ruble1.00", "Latvian lats1.00", "Latvian lati1.00", "Latvian ruble1.00", "Latvian rubles1.00", "Lebanese Pound1.00", "Lebanese pound1.00", "Lebanese pounds1.00", "Lesotho Loti1.00", "Lesotho loti1.00", "Lesotho lotis1.00", "Liberian Dollar1.00", "Liberian dollar1.00", "Liberian dollars1.00", "Libyan Dinar1.00", "Libyan dinar1.00", "Libyan dinars1.00", "Lithuanian Litas1.00", "Lithuanian Talonas1.00", "Lithuanian litas1.00", "Lithuanian litai1.00", "Lithuanian talonas1.00", "Lithuanian talonases1.00", "Luxembourgian Convertible Franc1.00", "Luxembourg Financial Franc1.00", "Luxembourgian Franc1.00", "Luxembourgian convertible franc1.00", "Luxembourgian convertible francs1.00", "Luxembourg financial franc1.00", "Luxembourg financial francs1.00", "Luxembourgian franc1.00", "Luxembourgian francs1.00", "MAD1.00", "MAD1.00", "MAF1.00", "MAF1.00", "MDL1.00", "MDL1.00", "MX$1.00", "MGA1.00", "MGA1.00", "MGF1.00", "MGF1.00", "MKD1.00", "MLF1.00", "MLF1.00", "MMK1.00", "MMK1.00", "MNT1.00", "MOP1.00", "MOP1.00", "MRO1.00", "MTL1.00", "MTP1.00", "MTP1.00", "MUR1.00", "MUR1.00", "MVR1.00", "MVR1.00", "MWK1.00", "MXN1.00", "MXP1.00", "MXP1.00", "MXV1.00", "MXV1.00", "MYR1.00", "MZE1.00", "MZE1.00", "MZM1.00", "MZN1.00", "Macanese Pataca1.00", "Macanese pataca1.00", "Macanese patacas1.00", "Macedonian Denar1.00", "Macedonian denar1.00", "Macedonian denari1.00", "Malagasy Ariaries1.00", "Malagasy Ariary1.00", "Malagasy Ariary1.00", "Malagasy Franc1.00", "Malagasy franc1.00", "Malagasy francs1.00", "Malawian Kwacha1.00", "Malawian Kwacha1.00", "Malawian Kwachas1.00", "Malaysian Ringgit1.00", "Malaysian ringgit1.00", "Malaysian ringgits1.00", "Maldivian Rufiyaa1.00", "Maldivian rufiyaa1.00", "Maldivian rufiyaas1.00", "Malian Franc1.00", "Malian franc1.00", "Malian francs1.00", "Maltese Lira1.00", "Maltese Pound1.00", "Maltese lira1.00", "Maltese lira1.00", "Maltese pound1.00", "Maltese pounds1.00", "Mauritanian Ouguiya1.00", "Mauritanian ouguiya1.00", "Mauritanian ouguiyas1.00", "Mauritian Rupee1.00", "Mauritian rupee1.00", "Mauritian rupees1.00", "Mexican Peso1.00", "Mexican Silver Peso (1861\\u20131992)1.00", "Mexican Investment Unit1.00", "Mexican peso1.00", "Mexican pesos1.00", "Mexican silver peso (1861\\u20131992)1.00", "Mexican silver pesos (1861\\u20131992)1.00", "Mexican investment unit1.00", "Mexican investment units1.00", "Moldovan Leu1.00", "Moldovan leu1.00", "Moldovan lei1.00", "Mongolian Tugrik1.00", "Mongolian tugrik1.00", "Mongolian tugriks1.00", "Moroccan Dirham1.00", "Moroccan Franc1.00", "Moroccan dirham1.00", "Moroccan dirhams1.00", "Moroccan franc1.00", "Moroccan francs1.00", "Mozambican Escudo1.00", "Mozambican Metical1.00", "Mozambican escudo1.00", "Mozambican escudos1.00", "Mozambican metical1.00", "Mozambican meticals1.00", "Myanmar Kyat1.00", "Myanmar kyat1.00", "Myanmar kyats1.00", "NAD1.00", "NGN1.00", "NIC1.00", "NIO1.00", "NIO1.00", "NLG1.00", "NLG1.00", "NOK1.00", "NPR1.00", "NT$1.00", "NZ$1.00", "NZD1.00", "Namibian Dollar1.00", "Namibian dollar1.00", "Namibian dollars1.00", "Nepalese Rupee1.00", "Nepalese rupee1.00", "Nepalese rupees1.00", "Netherlands Antillean Guilder1.00", "Netherlands Antillean guilder1.00", "Netherlands Antillean guilders1.00", "Dutch Guilder1.00", "Dutch guilder1.00", "Dutch guilders1.00", "Israeli New Shekel1.00", "Israeli New Shekels1.00", "New Zealand Dollar1.00", "New Zealand dollar1.00", "New Zealand dollars1.00", "Nicaraguan C\\u00f3rdoba1.00", "Nicaraguan C\\u00f3rdoba (1988\\u20131991)1.00", "Nicaraguan c\\u00f3rdoba1.00", "Nicaraguan c\\u00f3rdobas1.00", "Nicaraguan c\\u00f3rdoba (1988\\u20131991)1.00", "Nicaraguan c\\u00f3rdobas (1988\\u20131991)1.00", "Nigerian Naira1.00", "Nigerian naira1.00", "Nigerian nairas1.00", "North Korean Won1.00", "North Korean won1.00", "North Korean won1.00", "Norwegian Krone1.00", "Norwegian krone1.00", "Norwegian kroner1.00", "OMR1.00", "Mozambican Metical (1980\\u20132006)1.00", "Mozambican metical (1980\\u20132006)1.00", "Mozambican meticals (1980\\u20132006)1.00", "Romanian Lei (1952\\u20132006)1.00", "Romanian Leu (1952\\u20132006)1.00", "Romanian leu (1952\\u20132006)1.00", "Serbian Dinar (2002\\u20132006)1.00", "Serbian dinar (2002\\u20132006)1.00", "Serbian dinars (2002\\u20132006)1.00", "Sudanese Dinar (1992\\u20132007)1.00", "Sudanese Pound (1957\\u20131998)1.00", "Sudanese dinar (1992\\u20132007)1.00", "Sudanese dinars (1992\\u20132007)1.00", "Sudanese pound (1957\\u20131998)1.00", "Sudanese pounds (1957\\u20131998)1.00", "Turkish Lira (1922\\u20132005)1.00", "Turkish Lira (1922\\u20132005)1.00", "Omani Rial1.00", "Omani rial1.00", "Omani rials1.00", "PAB1.00", "PAB1.00", "PEI1.00", "PEI1.00", "PEN1.00", "PEN1.00", "PES1.00", "PES1.00", "PGK1.00", "PGK1.00", "PHP1.00", "PKR1.00", "PLN1.00", "PLZ1.00", "PLZ1.00", "PTE1.00", "PTE1.00", "PYG1.00", "Pakistani Rupee1.00", "Pakistani rupee1.00", "Pakistani rupees1.00", "Palladium1.00", "Palladium1.00", "Panamanian Balboa1.00", "Panamanian balboa1.00", "Panamanian balboas1.00", "Papua New Guinean Kina1.00", "Papua New Guinean kina1.00", "Papua New Guinean kina1.00", "Paraguayan Guarani1.00", "Paraguayan guarani1.00", "Paraguayan guaranis1.00", "Peruvian Inti1.00", "Peruvian Sol1.00", "Peruvian Sol (1863\\u20131965)1.00", "Peruvian inti1.00", "Peruvian intis1.00", "Peruvian sol1.00", "Peruvian soles1.00", "Peruvian sol (1863\\u20131965)1.00", "Peruvian soles (1863\\u20131965)1.00", "Philippine Piso1.00", "Philippine piso1.00", "Philippine pisos1.00", "Platinum1.00", "Platinum1.00", "Polish Zloty (1950\\u20131995)1.00", "Polish Zloty1.00", "Polish zlotys1.00", "Polish zloty (PLZ)1.00", "Polish zloty1.00", "Polish zlotys (PLZ)1.00", "Portuguese Escudo1.00", "Portuguese Guinea Escudo1.00", "Portuguese Guinea escudo1.00", "Portuguese Guinea escudos1.00", "Portuguese escudo1.00", "Portuguese escudos1.00", "GTQ1.00", "QAR1.00", "Qatari Rial1.00", "Qatari rial1.00", "Qatari rials1.00", "RHD1.00", "RHD1.00", "RINET Funds1.00", "RINET Funds1.00", "CN\\u00a51.00", "ROL1.00", "ROL1.00", "RON1.00", "RON1.00", "RSD1.00", "RSD1.00", "RUB1.00", "RUR1.00", "RUR1.00", "RWF1.00", "RWF1.00", "Rhodesian Dollar1.00", "Rhodesian dollar1.00", "Rhodesian dollars1.00", "Romanian Leu1.00", "Romanian lei1.00", "Romanian leu1.00", "Russian Ruble (1991\\u20131998)1.00", "Russian Ruble1.00", "Russian ruble (1991\\u20131998)1.00", "Russian ruble1.00", "Russian rubles (1991\\u20131998)1.00", "Russian rubles1.00", "Rwandan Franc1.00", "Rwandan franc1.00", "Rwandan francs1.00", "SAR1.00", "SBD1.00", "SCR1.00", "SDD1.00", "SDD1.00", "SDG1.00", "SDG1.00", "SDP1.00", "SDP1.00", "SEK1.00", "SGD1.00", "SHP1.00", "SHP1.00", "SIT1.00", "SIT1.00", "SKK1.00", "SLL1.00", "SLL1.00", "SOS1.00", "SRD1.00", "SRD1.00", "SRG1.00", "STD1.00", "SUR1.00", "SUR1.00", "SVC1.00", "SVC1.00", "SYP1.00", "SZL1.00", "St. Helena Pound1.00", "St. Helena pound1.00", "St. Helena pounds1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobra1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobra1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobras1.00", "Saudi Riyal1.00", "Saudi riyal1.00", "Saudi riyals1.00", "Serbian Dinar1.00", "Serbian dinar1.00", "Serbian dinars1.00", "Seychellois Rupee1.00", "Seychellois rupee1.00", "Seychellois rupees1.00", "Sierra Leonean Leone1.00", "Sierra Leonean leone1.00", "Sierra Leonean leones1.00", "Silver1.00", "Silver1.00", "Singapore Dollar1.00", "Singapore dollar1.00", "Singapore dollars1.00", "Slovak Koruna1.00", "Slovak koruna1.00", "Slovak korunas1.00", "Slovenian Tolar1.00", "Slovenian tolar1.00", "Slovenian tolars1.00", "Solomon Islands Dollar1.00", "Solomon Islands dollar1.00", "Solomon Islands dollars1.00", "Somali Shilling1.00", "Somali shilling1.00", "Somali shillings1.00", "South African Rand (financial)1.00", "South African Rand1.00", "South African rand (financial)1.00", "South African rand1.00", "South African rands (financial)1.00", "South African rand1.00", "South Korean Won1.00", "South Korean won1.00", "South Korean won1.00", "Soviet Rouble1.00", "Soviet rouble1.00", "Soviet roubles1.00", "Spanish Peseta (A account)1.00", "Spanish Peseta (convertible account)1.00", "Spanish Peseta1.00", "Spanish peseta (A account)1.00", "Spanish peseta (convertible account)1.00", "Spanish peseta1.00", "Spanish pesetas (A account)1.00", "Spanish pesetas (convertible account)1.00", "Spanish pesetas1.00", "Special Drawing Rights1.00", "Sri Lankan Rupee1.00", "Sri Lankan rupee1.00", "Sri Lankan rupees1.00", "Sudanese Pound1.00", "Sudanese pound1.00", "Sudanese pounds1.00", "Surinamese Dollar1.00", "Surinamese dollar1.00", "Surinamese dollars1.00", "Surinamese Guilder1.00", "Surinamese guilder1.00", "Surinamese guilders1.00", "Swazi Lilangeni1.00", "Swazi lilangeni1.00", "Swazi emalangeni1.00", "Swedish Krona1.00", "Swedish krona1.00", "Swedish kronor1.00", "Swiss Franc1.00", "Swiss franc1.00", "Swiss francs1.00", "Syrian Pound1.00", "Syrian pound1.00", "Syrian pounds1.00", "THB1.00", "TJR1.00", "TJR1.00", "TJS1.00", "TJS1.00", "TMM1.00", "TMM1.00", "TND1.00", "TND1.00", "TOP1.00", "TPE1.00", "TPE1.00", "TRL1.00", "TRY1.00", "TRY1.00", "TTD1.00", "TWD1.00", "TZS1.00", "New Taiwan Dollar1.00", "New Taiwan dollar1.00", "New Taiwan dollars1.00", "Tajikistani Ruble1.00", "Tajikistani Somoni1.00", "Tajikistani ruble1.00", "Tajikistani rubles1.00", "Tajikistani somoni1.00", "Tajikistani somonis1.00", "Tanzanian Shilling1.00", "Tanzanian shilling1.00", "Tanzanian shillings1.00", "Testing Currency Code1.00", "Testing Currency Code1.00", "Thai Baht1.00", "Thai baht1.00", "Thai baht1.00", "Timorese Escudo1.00", "Timorese escudo1.00", "Timorese escudos1.00", "Tongan Pa\\u02bbanga1.00", "Tongan pa\\u02bbanga1.00", "Tongan pa\\u02bbanga1.00", "Trinidad & Tobago Dollar1.00", "Trinidad & Tobago dollar1.00", "Trinidad & Tobago dollars1.00", "Tunisian Dinar1.00", "Tunisian dinar1.00", "Tunisian dinars1.00", "Turkish Lira1.00", "Turkish Lira1.00", "Turkish lira1.00", "Turkmenistani Manat1.00", "Turkmenistani manat1.00", "Turkmenistani manat1.00", "UAE dirham1.00", "UAE dirhams1.00", "UAH1.00", "UAK1.00", "UAK1.00", "UGS1.00", "UGS1.00", "UGX1.00", "US Dollar (Next day)1.00", "US Dollar (Same day)1.00", "US Dollar1.00", "US dollar (next day)1.00", "US dollar (same day)1.00", "US dollar1.00", "US dollars (next day)1.00", "US dollars (same day)1.00", "US dollars1.00", "USD1.00", "USN1.00", "USN1.00", "USS1.00", "USS1.00", "UYI1.00", "UYI1.00", "UYP1.00", "UYP1.00", "UYU1.00", "UZS1.00", "UZS1.00", "Ugandan Shilling (1966\\u20131987)1.00", "Ugandan Shilling1.00", "Ugandan shilling (1966\\u20131987)1.00", "Ugandan shilling1.00", "Ugandan shillings (1966\\u20131987)1.00", "Ugandan shillings1.00", "Ukrainian Hryvnia1.00", "Ukrainian Karbovanets1.00", "Ukrainian hryvnia1.00", "Ukrainian hryvnias1.00", "Ukrainian karbovanets1.00", "Ukrainian karbovantsiv1.00", "Colombian Real Value Unit1.00", "United Arab Emirates Dirham1.00", "Unknown Currency1.00", "Uruguayan Peso (1975\\u20131993)1.00", "Uruguayan Peso1.00", "Uruguayan Peso (Indexed Units)1.00", "Uruguayan peso (1975\\u20131993)1.00", "Uruguayan peso (indexed units)1.00", "Uruguayan peso1.00", "Uruguayan pesos (1975\\u20131993)1.00", "Uruguayan pesos (indexed units)1.00", "Uruguayan pesos1.00", "Uzbekistani Som1.00", "Uzbekistani som1.00", "Uzbekistani som1.00", "VEB1.00", "VEF1.00", "VND1.00", "VUV1.00", "Vanuatu Vatu1.00", "Vanuatu vatu1.00", "Vanuatu vatus1.00", "Venezuelan Bol\\u00edvar1.00", "Venezuelan Bol\\u00edvar (1871\\u20132008)1.00", "Venezuelan bol\\u00edvar1.00", "Venezuelan bol\\u00edvars1.00", "Venezuelan bol\\u00edvar (1871\\u20132008)1.00", "Venezuelan bol\\u00edvars (1871\\u20132008)1.00", "Vietnamese Dong1.00", "Vietnamese dong1.00", "Vietnamese dong1.00", "WIR Euro1.00", "WIR Franc1.00", "WIR euro1.00", "WIR euros1.00", "WIR franc1.00", "WIR francs1.00", "WST1.00", "WST1.00", "Samoan Tala1.00", "Samoan tala1.00", "Samoan tala1.00", "XAF1.00", "XAF1.00", "XAG1.00", "XAG1.00", "XAU1.00", "XAU1.00", "XBA1.00", "XBA1.00", "XBB1.00", "XBB1.00", "XBC1.00", "XBC1.00", "XBD1.00", "XBD1.00", "XCD1.00", "XDR1.00", "XDR1.00", "XEU1.00", "XEU1.00", "XFO1.00", "XFO1.00", "XFU1.00", "XFU1.00", "XOF1.00", "XOF1.00", "XPD1.00", "XPD1.00", "XPF1.00", "XPT1.00", "XPT1.00", "XRE1.00", "XRE1.00", "XTS1.00", "XTS1.00", "XXX1.00", "XXX1.00", "YDD1.00", "YDD1.00", "YER1.00", "YUD1.00", "YUD1.00", "YUM1.00", "YUM1.00", "YUN1.00", "YUN1.00", "Yemeni Dinar1.00", "Yemeni Rial1.00", "Yemeni dinar1.00", "Yemeni dinars1.00", "Yemeni rial1.00", "Yemeni rials1.00", "Yugoslavian Convertible Dinar (1990\\u20131992)1.00", "Yugoslavian Hard Dinar (1966\\u20131990)1.00", "Yugoslavian New Dinar (1994\\u20132002)1.00", "Yugoslavian convertible dinar (1990\\u20131992)1.00", "Yugoslavian convertible dinars (1990\\u20131992)1.00", "Yugoslavian hard dinar (1966\\u20131990)1.00", "Yugoslavian hard dinars (1966\\u20131990)1.00", "Yugoslavian new dinar (1994\\u20132002)1.00", "Yugoslavian new dinars (1994\\u20132002)1.00", "ZAL1.00", "ZAL1.00", "ZAR1.00", "ZMK1.00", "ZMK1.00", "ZRN1.00", "ZRN1.00", "ZRZ1.00", "ZRZ1.00", "ZWD1.00", "Zairean New Zaire (1993\\u20131998)1.00", "Zairean Zaire (1971\\u20131993)1.00", "Zairean new zaire (1993\\u20131998)1.00", "Zairean new zaires (1993\\u20131998)1.00", "Zairean zaire (1971\\u20131993)1.00", "Zairean zaires (1971\\u20131993)1.00", "Zambian Kwacha1.00", "Zambian kwacha1.00", "Zambian kwachas1.00", "Zimbabwean Dollar (1980\\u20132008)1.00", "Zimbabwean dollar (1980\\u20132008)1.00", "Zimbabwean dollars (1980\\u20132008)1.00", "euro1.00", "euros1.00", "Turkish lira (1922\\u20132005)1.00", "special drawing rights1.00", "Colombian real value unit1.00", "Colombian real value units1.00", "unknown currency1.00", "\\u00a31.00", "\\u00a51.00", "\\u20ab1.00", "\\u20aa1.00", "\\u20ac1.00", "\\u20b91.00", // // Following has extra text, should be parsed correctly too "$1.00 random", "USD1.00 random", "1.00 US dollar random", "1.00 US dollars random", "1.00 Afghan Afghani random", "1.00 Afghan Afghani random", "1.00 Afghan Afghanis (1927\\u20131992) random", "1.00 Afghan Afghanis random", "1.00 Albanian Lek random", "1.00 Albanian lek random", "1.00 Albanian lek\\u00eb random", "1.00 Algerian Dinar random", "1.00 Algerian dinar random", "1.00 Algerian dinars random", "1.00 Andorran Peseta random", "1.00 Andorran peseta random", "1.00 Andorran pesetas random", "1.00 Angolan Kwanza (1977\\u20131990) random", "1.00 Angolan Readjusted Kwanza (1995\\u20131999) random", "1.00 Angolan Kwanza random", "1.00 Angolan New Kwanza (1990\\u20132000) random", "1.00 Angolan kwanza (1977\\u20131991) random", "1.00 Angolan readjusted kwanza (1995\\u20131999) random", "1.00 Angolan kwanza random", "1.00 Angolan kwanzas (1977\\u20131991) random", "1.00 Angolan readjusted kwanzas (1995\\u20131999) random", "1.00 Angolan kwanzas random", "1.00 Angolan new kwanza (1990\\u20132000) random", "1.00 Angolan new kwanzas (1990\\u20132000) random", "1.00 Argentine Austral random", "1.00 Argentine Peso (1983\\u20131985) random", "1.00 Argentine Peso random", "1.00 Argentine austral random", "1.00 Argentine australs random", "1.00 Argentine peso (1983\\u20131985) random", "1.00 Argentine peso random", "1.00 Argentine pesos (1983\\u20131985) random", "1.00 Argentine pesos random", "1.00 Armenian Dram random", "1.00 Armenian dram random", "1.00 Armenian drams random", "1.00 Aruban Florin random", "1.00 Aruban florin random", "1.00 Australian Dollar random", "1.00 Australian dollar random", "1.00 Australian dollars random", "1.00 Austrian Schilling random", "1.00 Austrian schilling random", "1.00 Austrian schillings random", "1.00 Azerbaijani Manat (1993\\u20132006) random", "1.00 Azerbaijani Manat random", "1.00 Azerbaijani manat (1993\\u20132006) random", "1.00 Azerbaijani manat random", "1.00 Azerbaijani manats (1993\\u20132006) random", "1.00 Azerbaijani manats random", "1.00 Bahamian Dollar random", "1.00 Bahamian dollar random", "1.00 Bahamian dollars random", "1.00 Bahraini Dinar random", "1.00 Bahraini dinar random", "1.00 Bahraini dinars random", "1.00 Bangladeshi Taka random", "1.00 Bangladeshi taka random", "1.00 Bangladeshi takas random", "1.00 Barbadian Dollar random", "1.00 Barbadian dollar random", "1.00 Barbadian dollars random", "1.00 Belarusian Ruble (1994\\u20131999) random", "1.00 Belarusian Ruble random", "1.00 Belarusian ruble (1994\\u20131999) random", "1.00 Belarusian rubles (1994\\u20131999) random", "1.00 Belarusian ruble random", "1.00 Belarusian rubles random", "1.00 Belgian Franc (convertible) random", "1.00 Belgian Franc (financial) random", "1.00 Belgian Franc random", "1.00 Belgian franc (convertible) random", "1.00 Belgian franc (financial) random", "1.00 Belgian franc random", "1.00 Belgian francs (convertible) random", "1.00 Belgian francs (financial) random", "1.00 Belgian francs random", "1.00 Belize Dollar random", "1.00 Belize dollar random", "1.00 Belize dollars random", "1.00 Bermudan Dollar random", "1.00 Bermudan dollar random", "1.00 Bermudan dollars random", "1.00 Bhutanese Ngultrum random", "1.00 Bhutanese ngultrum random", "1.00 Bhutanese ngultrums random", "1.00 Bolivian Mvdol random", "1.00 Bolivian Peso random", "1.00 Bolivian mvdol random", "1.00 Bolivian mvdols random", "1.00 Bolivian peso random", "1.00 Bolivian pesos random", "1.00 Bolivian Boliviano random", "1.00 Bolivian Boliviano random", "1.00 Bolivian Bolivianos random", "1.00 Bosnia-Herzegovina Convertible Mark random", "1.00 Bosnia-Herzegovina Dinar (1992\\u20131994) random", "1.00 Bosnia-Herzegovina convertible mark random", "1.00 Bosnia-Herzegovina convertible marks random", "1.00 Bosnia-Herzegovina dinar (1992\\u20131994) random", "1.00 Bosnia-Herzegovina dinars (1992\\u20131994) random", "1.00 Botswanan Pula random", "1.00 Botswanan pula random", "1.00 Botswanan pulas random", "1.00 Brazilian New Cruzado (1989\\u20131990) random", "1.00 Brazilian Cruzado (1986\\u20131989) random", "1.00 Brazilian Cruzeiro (1990\\u20131993) random", "1.00 Brazilian New Cruzeiro (1967\\u20131986) random", "1.00 Brazilian Cruzeiro (1993\\u20131994) random", "1.00 Brazilian Real random", "1.00 Brazilian new cruzado (1989\\u20131990) random", "1.00 Brazilian new cruzados (1989\\u20131990) random", "1.00 Brazilian cruzado (1986\\u20131989) random", "1.00 Brazilian cruzados (1986\\u20131989) random", "1.00 Brazilian cruzeiro (1990\\u20131993) random", "1.00 Brazilian new cruzeiro (1967\\u20131986) random", "1.00 Brazilian cruzeiro (1993\\u20131994) random", "1.00 Brazilian cruzeiros (1990\\u20131993) random", "1.00 Brazilian new cruzeiros (1967\\u20131986) random", "1.00 Brazilian cruzeiros (1993\\u20131994) random", "1.00 Brazilian real random", "1.00 Brazilian reals random", "1.00 British Pound random", "1.00 British pound random", "1.00 British pounds random", "1.00 Brunei Dollar random", "1.00 Brunei dollar random", "1.00 Brunei dollars random", "1.00 Bulgarian Hard Lev random", "1.00 Bulgarian Lev random", "1.00 Bulgarian Leva random", "1.00 Bulgarian hard lev random", "1.00 Bulgarian hard leva random", "1.00 Bulgarian lev random", "1.00 Burmese Kyat random", "1.00 Burmese kyat random", "1.00 Burmese kyats random", "1.00 Burundian Franc random", "1.00 Burundian franc random", "1.00 Burundian francs random", "1.00 Cambodian Riel random", "1.00 Cambodian riel random", "1.00 Cambodian riels random", "1.00 Canadian Dollar random", "1.00 Canadian dollar random", "1.00 Canadian dollars random", "1.00 Cape Verdean Escudo random", "1.00 Cape Verdean escudo random", "1.00 Cape Verdean escudos random", "1.00 Cayman Islands Dollar random", "1.00 Cayman Islands dollar random", "1.00 Cayman Islands dollars random", "1.00 Chilean Peso random", "1.00 Chilean Unit of Account (UF) random", "1.00 Chilean peso random", "1.00 Chilean pesos random", "1.00 Chilean unit of account (UF) random", "1.00 Chilean units of account (UF) random", "1.00 Chinese Yuan random", "1.00 Chinese yuan random", "1.00 Colombian Peso random", "1.00 Colombian peso random", "1.00 Colombian pesos random", "1.00 Comorian Franc random", "1.00 Comorian franc random", "1.00 Comorian francs random", "1.00 Congolese Franc Congolais random", "1.00 Congolese franc Congolais random", "1.00 Congolese francs Congolais random", "1.00 Costa Rican Col\\u00f3n random", "1.00 Costa Rican col\\u00f3n random", "1.00 Costa Rican col\\u00f3ns random", "1.00 Croatian Dinar random", "1.00 Croatian Kuna random", "1.00 Croatian dinar random", "1.00 Croatian dinars random", "1.00 Croatian kuna random", "1.00 Croatian kunas random", "1.00 Cuban Peso random", "1.00 Cuban peso random", "1.00 Cuban pesos random", "1.00 Cypriot Pound random", "1.00 Cypriot pound random", "1.00 Cypriot pounds random", "1.00 Czech Koruna random", "1.00 Czech koruna random", "1.00 Czech korunas random", "1.00 Czechoslovak Hard Koruna random", "1.00 Czechoslovak hard koruna random", "1.00 Czechoslovak hard korunas random", "1.00 Danish Krone random", "1.00 Danish krone random", "1.00 Danish kroner random", "1.00 German Mark random", "1.00 German mark random", "1.00 German marks random", "1.00 Djiboutian Franc random", "1.00 Djiboutian franc random", "1.00 Djiboutian francs random", "1.00 Dominican Peso random", "1.00 Dominican peso random", "1.00 Dominican pesos random", "1.00 East Caribbean Dollar random", "1.00 East Caribbean dollar random", "1.00 East Caribbean dollars random", "1.00 East German Mark random", "1.00 East German mark random", "1.00 East German marks random", "1.00 Ecuadorian Sucre random", "1.00 Ecuadorian Unit of Constant Value random", "1.00 Ecuadorian sucre random", "1.00 Ecuadorian sucres random", "1.00 Ecuadorian unit of constant value random", "1.00 Ecuadorian units of constant value random", "1.00 Egyptian Pound random", "1.00 Egyptian pound random", "1.00 Egyptian pounds random", "1.00 Salvadoran Col\\u00f3n random", "1.00 Salvadoran col\\u00f3n random", "1.00 Salvadoran colones random", "1.00 Equatorial Guinean Ekwele random", "1.00 Equatorial Guinean ekwele random", "1.00 Eritrean Nakfa random", "1.00 Eritrean nakfa random", "1.00 Eritrean nakfas random", "1.00 Estonian Kroon random", "1.00 Estonian kroon random", "1.00 Estonian kroons random", "1.00 Ethiopian Birr random", "1.00 Ethiopian birr random", "1.00 Ethiopian birrs random", "1.00 European Composite Unit random", "1.00 European Currency Unit random", "1.00 European Monetary Unit random", "1.00 European Unit of Account (XBC) random", "1.00 European Unit of Account (XBD) random", "1.00 European composite unit random", "1.00 European composite units random", "1.00 European currency unit random", "1.00 European currency units random", "1.00 European monetary unit random", "1.00 European monetary units random", "1.00 European unit of account (XBC) random", "1.00 European unit of account (XBD) random", "1.00 European units of account (XBC) random", "1.00 European units of account (XBD) random", "1.00 Falkland Islands Pound random", "1.00 Falkland Islands pound random", "1.00 Falkland Islands pounds random", "1.00 Fijian Dollar random", "1.00 Fijian dollar random", "1.00 Fijian dollars random", "1.00 Finnish Markka random", "1.00 Finnish markka random", "1.00 Finnish markkas random", "1.00 French Franc random", "1.00 French Gold Franc random", "1.00 French UIC-Franc random", "1.00 French UIC-franc random", "1.00 French UIC-francs random", "1.00 French franc random", "1.00 French francs random", "1.00 French gold franc random", "1.00 French gold francs random", "1.00 Gambian Dalasi random", "1.00 Gambian dalasi random", "1.00 Gambian dalasis random", "1.00 Georgian Kupon Larit random", "1.00 Georgian Lari random", "1.00 Georgian kupon larit random", "1.00 Georgian kupon larits random", "1.00 Georgian lari random", "1.00 Georgian laris random", "1.00 Ghanaian Cedi (1979\\u20132007) random", "1.00 Ghanaian Cedi random", "1.00 Ghanaian cedi (1979\\u20132007) random", "1.00 Ghanaian cedi random", "1.00 Ghanaian cedis (1979\\u20132007) random", "1.00 Ghanaian cedis random", "1.00 Gibraltar Pound random", "1.00 Gibraltar pound random", "1.00 Gibraltar pounds random", "1.00 Gold random", "1.00 Gold random", "1.00 Greek Drachma random", "1.00 Greek drachma random", "1.00 Greek drachmas random", "1.00 Guatemalan Quetzal random", "1.00 Guatemalan quetzal random", "1.00 Guatemalan quetzals random", "1.00 Guinean Franc random", "1.00 Guinean Syli random", "1.00 Guinean franc random", "1.00 Guinean francs random", "1.00 Guinean syli random", "1.00 Guinean sylis random", "1.00 Guinea-Bissau Peso random", "1.00 Guinea-Bissau peso random", "1.00 Guinea-Bissau pesos random", "1.00 Guyanaese Dollar random", "1.00 Guyanaese dollar random", "1.00 Guyanaese dollars random", "1.00 Haitian Gourde random", "1.00 Haitian gourde random", "1.00 Haitian gourdes random", "1.00 Honduran Lempira random", "1.00 Honduran lempira random", "1.00 Honduran lempiras random", "1.00 Hong Kong Dollar random", "1.00 Hong Kong dollar random", "1.00 Hong Kong dollars random", "1.00 Hungarian Forint random", "1.00 Hungarian forint random", "1.00 Hungarian forints random", "1.00 Icelandic Kr\\u00f3na random", "1.00 Icelandic kr\\u00f3na random", "1.00 Icelandic kr\\u00f3nur random", "1.00 Indian Rupee random", "1.00 Indian rupee random", "1.00 Indian rupees random", "1.00 Indonesian Rupiah random", "1.00 Indonesian rupiah random", "1.00 Indonesian rupiahs random", "1.00 Iranian Rial random", "1.00 Iranian rial random", "1.00 Iranian rials random", "1.00 Iraqi Dinar random", "1.00 Iraqi dinar random", "1.00 Iraqi dinars random", "1.00 Irish Pound random", "1.00 Irish pound random", "1.00 Irish pounds random", "1.00 Israeli Pound random", "1.00 Israeli new shekel random", "1.00 Israeli pound random", "1.00 Israeli pounds random", "1.00 Italian Lira random", "1.00 Italian lira random", "1.00 Italian liras random", "1.00 Jamaican Dollar random", "1.00 Jamaican dollar random", "1.00 Jamaican dollars random", "1.00 Japanese Yen random", "1.00 Japanese yen random", "1.00 Jordanian Dinar random", "1.00 Jordanian dinar random", "1.00 Jordanian dinars random", "1.00 Kazakhstani Tenge random", "1.00 Kazakhstani tenge random", "1.00 Kazakhstani tenges random", "1.00 Kenyan Shilling random", "1.00 Kenyan shilling random", "1.00 Kenyan shillings random", "1.00 Kuwaiti Dinar random", "1.00 Kuwaiti dinar random", "1.00 Kuwaiti dinars random", "1.00 Kyrgystani Som random", "1.00 Kyrgystani som random", "1.00 Kyrgystani soms random", "1.00 Laotian Kip random", "1.00 Laotian kip random", "1.00 Laotian kips random", "1.00 Latvian Lats random", "1.00 Latvian Ruble random", "1.00 Latvian lats random", "1.00 Latvian lati random", "1.00 Latvian ruble random", "1.00 Latvian rubles random", "1.00 Lebanese Pound random", "1.00 Lebanese pound random", "1.00 Lebanese pounds random", "1.00 Lesotho Loti random", "1.00 Lesotho loti random", "1.00 Lesotho lotis random", "1.00 Liberian Dollar random", "1.00 Liberian dollar random", "1.00 Liberian dollars random", "1.00 Libyan Dinar random", "1.00 Libyan dinar random", "1.00 Libyan dinars random", "1.00 Lithuanian Litas random", "1.00 Lithuanian Talonas random", "1.00 Lithuanian litas random", "1.00 Lithuanian litai random", "1.00 Lithuanian talonas random", "1.00 Lithuanian talonases random", "1.00 Luxembourgian Convertible Franc random", "1.00 Luxembourg Financial Franc random", "1.00 Luxembourgian Franc random", "1.00 Luxembourgian convertible franc random", "1.00 Luxembourgian convertible francs random", "1.00 Luxembourg financial franc random", "1.00 Luxembourg financial francs random", "1.00 Luxembourgian franc random", "1.00 Luxembourgian francs random", "1.00 Macanese Pataca random", "1.00 Macanese pataca random", "1.00 Macanese patacas random", "1.00 Macedonian Denar random", "1.00 Macedonian denar random", "1.00 Macedonian denari random", "1.00 Malagasy Ariaries random", "1.00 Malagasy Ariary random", "1.00 Malagasy Ariary random", "1.00 Malagasy Franc random", "1.00 Malagasy franc random", "1.00 Malagasy francs random", "1.00 Malawian Kwacha random", "1.00 Malawian Kwacha random", "1.00 Malawian Kwachas random", "1.00 Malaysian Ringgit random", "1.00 Malaysian ringgit random", "1.00 Malaysian ringgits random", "1.00 Maldivian Rufiyaa random", "1.00 Maldivian rufiyaa random", "1.00 Maldivian rufiyaas random", "1.00 Malian Franc random", "1.00 Malian franc random", "1.00 Malian francs random", "1.00 Maltese Lira random", "1.00 Maltese Pound random", "1.00 Maltese lira random", "1.00 Maltese liras random", "1.00 Maltese pound random", "1.00 Maltese pounds random", "1.00 Mauritanian Ouguiya random", "1.00 Mauritanian ouguiya random", "1.00 Mauritanian ouguiyas random", "1.00 Mauritian Rupee random", "1.00 Mauritian rupee random", "1.00 Mauritian rupees random", "1.00 Mexican Peso random", "1.00 Mexican Silver Peso (1861\\u20131992) random", "1.00 Mexican Investment Unit random", "1.00 Mexican peso random", "1.00 Mexican pesos random", "1.00 Mexican silver peso (1861\\u20131992) random", "1.00 Mexican silver pesos (1861\\u20131992) random", "1.00 Mexican investment unit random", "1.00 Mexican investment units random", "1.00 Moldovan Leu random", "1.00 Moldovan leu random", "1.00 Moldovan lei random", "1.00 Mongolian Tugrik random", "1.00 Mongolian tugrik random", "1.00 Mongolian tugriks random", "1.00 Moroccan Dirham random", "1.00 Moroccan Franc random", "1.00 Moroccan dirham random", "1.00 Moroccan dirhams random", "1.00 Moroccan franc random", "1.00 Moroccan francs random", "1.00 Mozambican Escudo random", "1.00 Mozambican Metical random", "1.00 Mozambican escudo random", "1.00 Mozambican escudos random", "1.00 Mozambican metical random", "1.00 Mozambican meticals random", "1.00 Myanmar Kyat random", "1.00 Myanmar kyat random", "1.00 Myanmar kyats random", "1.00 Namibian Dollar random", "1.00 Namibian dollar random", "1.00 Namibian dollars random", "1.00 Nepalese Rupee random", "1.00 Nepalese rupee random", "1.00 Nepalese rupees random", "1.00 Netherlands Antillean Guilder random", "1.00 Netherlands Antillean guilder random", "1.00 Netherlands Antillean guilders random", "1.00 Dutch Guilder random", "1.00 Dutch guilder random", "1.00 Dutch guilders random", "1.00 Israeli New Shekel random", "1.00 Israeli new shekels random", "1.00 New Zealand Dollar random", "1.00 New Zealand dollar random", "1.00 New Zealand dollars random", "1.00 Nicaraguan C\\u00f3rdoba random", "1.00 Nicaraguan C\\u00f3rdoba (1988\\u20131991) random", "1.00 Nicaraguan c\\u00f3rdoba random", "1.00 Nicaraguan c\\u00f3rdoba random", "1.00 Nicaraguan c\\u00f3rdoba (1988\\u20131991) random", "1.00 Nicaraguan c\\u00f3rdobas (1988\\u20131991) random", "1.00 Nigerian Naira random", "1.00 Nigerian naira random", "1.00 Nigerian nairas random", "1.00 North Korean Won random", "1.00 North Korean won random", "1.00 North Korean won random", "1.00 Norwegian Krone random", "1.00 Norwegian krone random", "1.00 Norwegian kroner random", "1.00 Mozambican Metical (1980\\u20132006) random", "1.00 Mozambican metical (1980\\u20132006) random", "1.00 Mozambican meticals (1980\\u20132006) random", "1.00 Romanian Lei (1952\\u20132006) random", "1.00 Romanian Leu (1952\\u20132006) random", "1.00 Romanian leu (1952\\u20132006) random", "1.00 Serbian Dinar (2002\\u20132006) random", "1.00 Serbian dinar (2002\\u20132006) random", "1.00 Serbian dinars (2002\\u20132006) random", "1.00 Sudanese Dinar (1992\\u20132007) random", "1.00 Sudanese Pound (1957\\u20131998) random", "1.00 Sudanese dinar (1992\\u20132007) random", "1.00 Sudanese dinars (1992\\u20132007) random", "1.00 Sudanese pound (1957\\u20131998) random", "1.00 Sudanese pounds (1957\\u20131998) random", "1.00 Turkish Lira (1922\\u20132005) random", "1.00 Turkish Lira (1922\\u20132005) random", "1.00 Omani Rial random", "1.00 Omani rial random", "1.00 Omani rials random", "1.00 Pakistani Rupee random", "1.00 Pakistani rupee random", "1.00 Pakistani rupees random", "1.00 Palladium random", "1.00 Palladium random", "1.00 Panamanian Balboa random", "1.00 Panamanian balboa random", "1.00 Panamanian balboas random", "1.00 Papua New Guinean Kina random", "1.00 Papua New Guinean kina random", "1.00 Papua New Guinean kina random", "1.00 Paraguayan Guarani random", "1.00 Paraguayan guarani random", "1.00 Paraguayan guaranis random", "1.00 Peruvian Inti random", "1.00 Peruvian Sol random", "1.00 Peruvian Sol (1863\\u20131965) random", "1.00 Peruvian inti random", "1.00 Peruvian intis random", "1.00 Peruvian sol random", "1.00 Peruvian soles random", "1.00 Peruvian sol (1863\\u20131965) random", "1.00 Peruvian soles (1863\\u20131965) random", "1.00 Philippine Piso random", "1.00 Philippine piso random", "1.00 Philippine pisos random", "1.00 Platinum random", "1.00 Platinum random", "1.00 Polish Zloty (1950\\u20131995) random", "1.00 Polish Zloty random", "1.00 Polish zlotys random", "1.00 Polish zloty (PLZ) random", "1.00 Polish zloty random", "1.00 Polish zlotys (PLZ) random", "1.00 Portuguese Escudo random", "1.00 Portuguese Guinea Escudo random", "1.00 Portuguese Guinea escudo random", "1.00 Portuguese Guinea escudos random", "1.00 Portuguese escudo random", "1.00 Portuguese escudos random", "1.00 Qatari Rial random", "1.00 Qatari rial random", "1.00 Qatari rials random", "1.00 RINET Funds random", "1.00 RINET Funds random", "1.00 Rhodesian Dollar random", "1.00 Rhodesian dollar random", "1.00 Rhodesian dollars random", "1.00 Romanian Leu random", "1.00 Romanian lei random", "1.00 Romanian leu random", "1.00 Russian Ruble (1991\\u20131998) random", "1.00 Russian Ruble random", "1.00 Russian ruble (1991\\u20131998) random", "1.00 Russian ruble random", "1.00 Russian rubles (1991\\u20131998) random", "1.00 Russian rubles random", "1.00 Rwandan Franc random", "1.00 Rwandan franc random", "1.00 Rwandan francs random", "1.00 St. Helena Pound random", "1.00 St. Helena pound random", "1.00 St. Helena pounds random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobra random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobra random", "1.00 S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe dobras random", "1.00 Saudi Riyal random", "1.00 Saudi riyal random", "1.00 Saudi riyals random", "1.00 Serbian Dinar random", "1.00 Serbian dinar random", "1.00 Serbian dinars random", "1.00 Seychellois Rupee random", "1.00 Seychellois rupee random", "1.00 Seychellois rupees random", "1.00 Sierra Leonean Leone random", "1.00 Sierra Leonean leone random", "1.00 Sierra Leonean leones random", "1.00 Singapore Dollar random", "1.00 Singapore dollar random", "1.00 Singapore dollars random", "1.00 Slovak Koruna random", "1.00 Slovak koruna random", "1.00 Slovak korunas random", "1.00 Slovenian Tolar random", "1.00 Slovenian tolar random", "1.00 Slovenian tolars random", "1.00 Solomon Islands Dollar random", "1.00 Solomon Islands dollar random", "1.00 Solomon Islands dollars random", "1.00 Somali Shilling random", "1.00 Somali shilling random", "1.00 Somali shillings random", "1.00 South African Rand (financial) random", "1.00 South African Rand random", "1.00 South African rand (financial) random", "1.00 South African rand random", "1.00 South African rands (financial) random", "1.00 South African rand random", "1.00 South Korean Won random", "1.00 South Korean won random", "1.00 South Korean won random", "1.00 Soviet Rouble random", "1.00 Soviet rouble random", "1.00 Soviet roubles random", "1.00 Spanish Peseta (A account) random", "1.00 Spanish Peseta (convertible account) random", "1.00 Spanish Peseta random", "1.00 Spanish peseta (A account) random", "1.00 Spanish peseta (convertible account) random", "1.00 Spanish peseta random", "1.00 Spanish pesetas (A account) random", "1.00 Spanish pesetas (convertible account) random", "1.00 Spanish pesetas random", "1.00 Special Drawing Rights random", "1.00 Sri Lankan Rupee random", "1.00 Sri Lankan rupee random", "1.00 Sri Lankan rupees random", "1.00 Sudanese Pound random", "1.00 Sudanese pound random", "1.00 Sudanese pounds random", "1.00 Surinamese Dollar random", "1.00 Surinamese dollar random", "1.00 Surinamese dollars random", "1.00 Surinamese Guilder random", "1.00 Surinamese guilder random", "1.00 Surinamese guilders random", "1.00 Swazi Lilangeni random", "1.00 Swazi lilangeni random", "1.00 Swazi emalangeni random", "1.00 Swedish Krona random", "1.00 Swedish krona random", "1.00 Swedish kronor random", "1.00 Swiss Franc random", "1.00 Swiss franc random", "1.00 Swiss francs random", "1.00 Syrian Pound random", "1.00 Syrian pound random", "1.00 Syrian pounds random", "1.00 New Taiwan Dollar random", "1.00 New Taiwan dollar random", "1.00 New Taiwan dollars random", "1.00 Tajikistani Ruble random", "1.00 Tajikistani Somoni random", "1.00 Tajikistani ruble random", "1.00 Tajikistani rubles random", "1.00 Tajikistani somoni random", "1.00 Tajikistani somonis random", "1.00 Tanzanian Shilling random", "1.00 Tanzanian shilling random", "1.00 Tanzanian shillings random", "1.00 Testing Currency Code random", "1.00 Testing Currency Code random", "1.00 Thai Baht random", "1.00 Thai baht random", "1.00 Thai baht random", "1.00 Timorese Escudo random", "1.00 Timorese escudo random", "1.00 Timorese escudos random", "1.00 Trinidad & Tobago Dollar random", "1.00 Trinidad & Tobago dollar random", "1.00 Trinidad & Tobago dollars random", "1.00 Tunisian Dinar random", "1.00 Tunisian dinar random", "1.00 Tunisian dinars random", "1.00 Turkish Lira random", "1.00 Turkish Lira random", "1.00 Turkish lira random", "1.00 Turkmenistani Manat random", "1.00 Turkmenistani manat random", "1.00 Turkmenistani manat random", "1.00 US Dollar (Next day) random", "1.00 US Dollar (Same day) random", "1.00 US Dollar random", "1.00 US dollar (next day) random", "1.00 US dollar (same day) random", "1.00 US dollar random", "1.00 US dollars (next day) random", "1.00 US dollars (same day) random", "1.00 US dollars random", "1.00 Ugandan Shilling (1966\\u20131987) random", "1.00 Ugandan Shilling random", "1.00 Ugandan shilling (1966\\u20131987) random", "1.00 Ugandan shilling random", "1.00 Ugandan shillings (1966\\u20131987) random", "1.00 Ugandan shillings random", "1.00 Ukrainian Hryvnia random", "1.00 Ukrainian Karbovanets random", "1.00 Ukrainian hryvnia random", "1.00 Ukrainian hryvnias random", "1.00 Ukrainian karbovanets random", "1.00 Ukrainian karbovantsiv random", "1.00 Colombian Real Value Unit random", "1.00 United Arab Emirates Dirham random", "1.00 Unknown Currency random", "1.00 Uruguayan Peso (1975\\u20131993) random", "1.00 Uruguayan Peso random", "1.00 Uruguayan Peso (Indexed Units) random", "1.00 Uruguayan peso (1975\\u20131993) random", "1.00 Uruguayan peso (indexed units) random", "1.00 Uruguayan peso random", "1.00 Uruguayan pesos (1975\\u20131993) random", "1.00 Uruguayan pesos (indexed units) random", "1.00 Uzbekistani Som random", "1.00 Uzbekistani som random", "1.00 Uzbekistani som random", "1.00 Vanuatu Vatu random", "1.00 Vanuatu vatu random", "1.00 Vanuatu vatus random", "1.00 Venezuelan Bol\\u00edvar random", "1.00 Venezuelan Bol\\u00edvar (1871\\u20132008) random", "1.00 Venezuelan bol\\u00edvar random", "1.00 Venezuelan bol\\u00edvars random", "1.00 Venezuelan bol\\u00edvar (1871\\u20132008) random", "1.00 Venezuelan bol\\u00edvars (1871\\u20132008) random", "1.00 Vietnamese Dong random", "1.00 Vietnamese dong random", "1.00 Vietnamese dong random", "1.00 WIR Euro random", "1.00 WIR Franc random", "1.00 WIR euro random", "1.00 WIR euros random", "1.00 WIR franc random", "1.00 WIR francs random", "1.00 Samoan Tala random", "1.00 Samoan tala random", "1.00 Samoan tala random", "1.00 Yemeni Dinar random", "1.00 Yemeni Rial random", "1.00 Yemeni dinar random", "1.00 Yemeni dinars random", "1.00 Yemeni rial random", "1.00 Yemeni rials random", "1.00 Yugoslavian Convertible Dinar (1990\\u20131992) random", "1.00 Yugoslavian Hard Dinar (1966\\u20131990) random", "1.00 Yugoslavian New Dinar (1994\\u20132002) random", "1.00 Yugoslavian convertible dinar (1990\\u20131992) random", "1.00 Yugoslavian convertible dinars (1990\\u20131992) random", "1.00 Yugoslavian hard dinar (1966\\u20131990) random", "1.00 Yugoslavian hard dinars (1966\\u20131990) random", "1.00 Yugoslavian new dinar (1994\\u20132002) random", "1.00 Yugoslavian new dinars (1994\\u20132002) random", "1.00 Zairean New Zaire (1993\\u20131998) random", "1.00 Zairean Zaire (1971\\u20131993) random", "1.00 Zairean new zaire (1993\\u20131998) random", "1.00 Zairean new zaires (1993\\u20131998) random", "1.00 Zairean zaire (1971\\u20131993) random", "1.00 Zairean zaires (1971\\u20131993) random", "1.00 Zambian Kwacha random", "1.00 Zambian kwacha random", "1.00 Zambian kwachas random", "1.00 Zimbabwean Dollar (1980\\u20132008) random", "1.00 Zimbabwean dollar (1980\\u20132008) random", "1.00 Zimbabwean dollars (1980\\u20132008) random", "1.00 euro random", "1.00 euros random", "1.00 Turkish lira (1922\\u20132005) random", "1.00 special drawing rights random", "1.00 Colombian real value unit random", "1.00 Colombian real value units random", "1.00 unknown currency random", }; const char* WRONG_DATA[] = { // Following are missing one last char in the currency name "1.00 Nicaraguan Cordob", "1.00 Namibian Dolla", "1.00 Namibian dolla", "1.00 Nepalese Rupe", "1.00 Nepalese rupe", "1.00 Netherlands Antillean Guilde", "1.00 Netherlands Antillean guilde", "1.00 Dutch Guilde", "1.00 Dutch guilde", "1.00 Israeli New Sheqe", "1.00 New Zealand Dolla", "1.00 New Zealand dolla", "1.00 Nicaraguan cordob", "1.00 Nigerian Nair", "1.00 Nigerian nair", "1.00 North Korean Wo", "1.00 North Korean wo", "1.00 Norwegian Kron", "1.00 Norwegian kron", "1.00 US dolla", "1.00", "A1.00", "AD1.00", "AE1.00", "AF1.00", "AL1.00", "AM1.00", "AN1.00", "AO1.00", "AR1.00", "AT1.00", "AU1.00", "AW1.00", "AZ1.00", "Afghan Afghan1.00", "Afghan Afghani (1927\\u201320021.00", "Afl1.00", "Albanian Le1.00", "Algerian Dina1.00", "Andorran Peset1.00", "Angolan Kwanz1.00", "Angolan Kwanza (1977\\u201319901.00", "Angolan Readjusted Kwanza (1995\\u201319991.00", "Angolan New Kwanza (1990\\u201320001.00", "Argentine Austra1.00", "Argentine Pes1.00", "Argentine Peso (1983\\u201319851.00", "Armenian Dra1.00", "Aruban Flori1.00", "Australian Dolla1.00", "Austrian Schillin1.00", "Azerbaijani Mana1.00", "Azerbaijani Manat (1993\\u201320061.00", "B1.00", "BA1.00", "BB1.00", "BE1.00", "BG1.00", "BH1.00", "BI1.00", "BM1.00", "BN1.00", "BO1.00", "BR1.00", "BS1.00", "BT1.00", "BU1.00", "BW1.00", "BY1.00", "BZ1.00", "Bahamian Dolla1.00", "Bahraini Dina1.00", "Bangladeshi Tak1.00", "Barbadian Dolla1.00", "Bds1.00", "Belarusian Ruble (1994\\u201319991.00", "Belarusian Rubl1.00", "Belgian Fran1.00", "Belgian Franc (convertible1.00", "Belgian Franc (financial1.00", "Belize Dolla1.00", "Bermudan Dolla1.00", "Bhutanese Ngultru1.00", "Bolivian Mvdo1.00", "Bolivian Pes1.00", "Bolivian Bolivian1.00", "Bosnia-Herzegovina Convertible Mar1.00", "Bosnia-Herzegovina Dina1.00", "Botswanan Pul1.00", "Brazilian Cruzad1.00", "Brazilian Cruzado Nov1.00", "Brazilian Cruzeir1.00", "Brazilian Cruzeiro (1990\\u201319931.00", "Brazilian New Cruzeiro (1967\\u201319861.00", "Brazilian Rea1.00", "British Pound Sterlin1.00", "Brunei Dolla1.00", "Bulgarian Hard Le1.00", "Bulgarian Le1.00", "Burmese Kya1.00", "Burundian Fran1.00", "C1.00", "CA1.00", "CD1.00", "CFP Fran1.00", "CFP1.00", "CH1.00", "CL1.00", "CN1.00", "CO1.00", "CS1.00", "CU1.00", "CV1.00", "CY1.00", "CZ1.00", "Cambodian Rie1.00", "Canadian Dolla1.00", "Cape Verdean Escud1.00", "Cayman Islands Dolla1.00", "Chilean Pes1.00", "Chilean Unit of Accoun1.00", "Chinese Yua1.00", "Colombian Pes1.00", "Comoro Fran1.00", "Congolese Fran1.00", "Costa Rican Col\\u00f31.00", "Croatian Dina1.00", "Croatian Kun1.00", "Cuban Pes1.00", "Cypriot Poun1.00", "Czech Republic Korun1.00", "Czechoslovak Hard Korun1.00", "D1.00", "DD1.00", "DE1.00", "DJ1.00", "DK1.00", "DO1.00", "DZ1.00", "Danish Kron1.00", "German Mar1.00", "Djiboutian Fran1.00", "Dk1.00", "Dominican Pes1.00", "EC1.00", "EE1.00", "EG1.00", "EQ1.00", "ER1.00", "ES1.00", "ET1.00", "EU1.00", "East Caribbean Dolla1.00", "East German Ostmar1.00", "Ecuadorian Sucr1.00", "Ecuadorian Unit of Constant Valu1.00", "Egyptian Poun1.00", "Ekwel1.00", "Salvadoran Col\\u00f31.00", "Equatorial Guinean Ekwel1.00", "Eritrean Nakf1.00", "Es1.00", "Estonian Kroo1.00", "Ethiopian Bir1.00", "Eur1.00", "European Composite Uni1.00", "European Currency Uni1.00", "European Monetary Uni1.00", "European Unit of Account (XBC1.00", "European Unit of Account (XBD1.00", "F1.00", "FB1.00", "FI1.00", "FJ1.00", "FK1.00", "FR1.00", "Falkland Islands Poun1.00", "Fd1.00", "Fijian Dolla1.00", "Finnish Markk1.00", "Fr1.00", "French Fran1.00", "French Gold Fran1.00", "French UIC-Fran1.00", "G1.00", "GB1.00", "GE1.00", "GH1.00", "GI1.00", "GM1.00", "GN1.00", "GQ1.00", "GR1.00", "GT1.00", "GW1.00", "GY1.00", "Gambian Dalas1.00", "Georgian Kupon Lari1.00", "Georgian Lar1.00", "Ghanaian Ced1.00", "Ghanaian Cedi (1979\\u201320071.00", "Gibraltar Poun1.00", "Gol1.00", "Greek Drachm1.00", "Guatemalan Quetza1.00", "Guinean Fran1.00", "Guinean Syl1.00", "Guinea-Bissau Pes1.00", "Guyanaese Dolla1.00", "HK1.00", "HN1.00", "HR1.00", "HT1.00", "HU1.00", "Haitian Gourd1.00", "Honduran Lempir1.00", "Hong Kong Dolla1.00", "Hungarian Forin1.00", "I1.00", "IE1.00", "IL1.00", "IN1.00", "IQ1.00", "IR1.00", "IS1.00", "IT1.00", "Icelandic Kron1.00", "Indian Rupe1.00", "Indonesian Rupia1.00", "Iranian Ria1.00", "Iraqi Dina1.00", "Irish Poun1.00", "Israeli Poun1.00", "Italian Lir1.00", "J1.00", "JM1.00", "JO1.00", "JP1.00", "Jamaican Dolla1.00", "Japanese Ye1.00", "Jordanian Dina1.00", "K S1.00", "K1.00", "KE1.00", "KG1.00", "KH1.00", "KP1.00", "KR1.00", "KW1.00", "KY1.00", "KZ1.00", "Kazakhstani Teng1.00", "Kenyan Shillin1.00", "Kuwaiti Dina1.00", "Kyrgystani So1.00", "LA1.00", "LB1.00", "LK1.00", "LR1.00", "LT1.00", "LU1.00", "LV1.00", "LY1.00", "Laotian Ki1.00", "Latvian Lat1.00", "Latvian Rubl1.00", "Lebanese Poun1.00", "Lesotho Lot1.00", "Liberian Dolla1.00", "Libyan Dina1.00", "Lithuanian Lit1.00", "Lithuanian Talona1.00", "Luxembourgian Convertible Fran1.00", "Luxembourg Financial Fran1.00", "Luxembourgian Fran1.00", "MA1.00", "MD1.00", "MDe1.00", "MEX1.00", "MG1.00", "ML1.00", "MM1.00", "MN1.00", "MO1.00", "MR1.00", "MT1.00", "MU1.00", "MV1.00", "MW1.00", "MX1.00", "MY1.00", "MZ1.00", "Macanese Patac1.00", "Macedonian Dena1.00", "Malagasy Ariar1.00", "Malagasy Fran1.00", "Malawian Kwach1.00", "Malaysian Ringgi1.00", "Maldivian Rufiya1.00", "Malian Fran1.00", "Malot1.00", "Maltese Lir1.00", "Maltese Poun1.00", "Mauritanian Ouguiy1.00", "Mauritian Rupe1.00", "Mexican Pes1.00", "Mexican Silver Peso (1861\\u201319921.00", "Mexican Investment Uni1.00", "Moldovan Le1.00", "Mongolian Tugri1.00", "Moroccan Dirha1.00", "Moroccan Fran1.00", "Mozambican Escud1.00", "Mozambican Metica1.00", "Myanmar Kya1.00", "N1.00", "NA1.00", "NAf1.00", "NG1.00", "NI1.00", "NK1.00", "NL1.00", "NO1.00", "NP1.00", "NT1.00", "Namibian Dolla1.00", "Nepalese Rupe1.00", "Netherlands Antillean Guilde1.00", "Dutch Guilde1.00", "Israeli New Sheqe1.00", "New Zealand Dolla1.00", "Nicaraguan C\\u00f3rdoba (1988\\u201319911.00", "Nicaraguan C\\u00f3rdob1.00", "Nigerian Nair1.00", "North Korean Wo1.00", "Norwegian Kron1.00", "Nr1.00", "OM1.00", "Old Mozambican Metica1.00", "Romanian Leu (1952\\u201320061.00", "Serbian Dinar (2002\\u201320061.00", "Sudanese Dinar (1992\\u201320071.00", "Sudanese Pound (1957\\u201319981.00", "Turkish Lira (1922\\u201320051.00", "Omani Ria1.00", "PA1.00", "PE1.00", "PG1.00", "PH1.00", "PK1.00", "PL1.00", "PT1.00", "PY1.00", "Pakistani Rupe1.00", "Palladiu1.00", "Panamanian Balbo1.00", "Papua New Guinean Kin1.00", "Paraguayan Guaran1.00", "Peruvian Int1.00", "Peruvian Sol (1863\\u201319651.00", "Peruvian Sol Nuev1.00", "Philippine Pes1.00", "Platinu1.00", "Polish Zlot1.00", "Polish Zloty (1950\\u201319951.00", "Portuguese Escud1.00", "Portuguese Guinea Escud1.00", "Pr1.00", "QA1.00", "Qatari Ria1.00", "RD1.00", "RH1.00", "RINET Fund1.00", "RS1.00", "RU1.00", "RW1.00", "Rb1.00", "Rhodesian Dolla1.00", "Romanian Le1.00", "Russian Rubl1.00", "Russian Ruble (1991\\u201319981.00", "Rwandan Fran1.00", "S1.00", "SA1.00", "SB1.00", "SC1.00", "SD1.00", "SE1.00", "SG1.00", "SH1.00", "SI1.00", "SK1.00", "SL R1.00", "SL1.00", "SO1.00", "ST1.00", "SU1.00", "SV1.00", "SY1.00", "SZ1.00", "St. Helena Poun1.00", "S\\u00e3o Tom\\u00e9 & Pr\\u00edncipe Dobr1.00", "Saudi Riya1.00", "Serbian Dina1.00", "Seychellois Rupe1.00", "Sh1.00", "Sierra Leonean Leon1.00", "Silve1.00", "Singapore Dolla1.00", "Slovak Korun1.00", "Slovenian Tola1.00", "Solomon Islands Dolla1.00", "Somali Shillin1.00", "South African Ran1.00", "South African Rand (financial1.00", "South Korean Wo1.00", "Soviet Roubl1.00", "Spanish Peset1.00", "Spanish Peseta (A account1.00", "Spanish Peseta (convertible account1.00", "Special Drawing Right1.00", "Sri Lankan Rupe1.00", "Sudanese Poun1.00", "Surinamese Dolla1.00", "Surinamese Guilde1.00", "Swazi Lilangen1.00", "Swedish Kron1.00", "Swiss Fran1.00", "Syrian Poun1.00", "T S1.00", "TH1.00", "TJ1.00", "TM1.00", "TN1.00", "TO1.00", "TP1.00", "TR1.00", "TT1.00", "TW1.00", "TZ1.00", "New Taiwan Dolla1.00", "Tajikistani Rubl1.00", "Tajikistani Somon1.00", "Tanzanian Shillin1.00", "Testing Currency Cod1.00", "Thai Bah1.00", "Timorese Escud1.00", "Tongan Pa\\u20bbang1.00", "Trinidad & Tobago Dolla1.00", "Tunisian Dina1.00", "Turkish Lir1.00", "Turkmenistani Mana1.00", "U S1.00", "U1.00", "UA1.00", "UG1.00", "US Dolla1.00", "US Dollar (Next day1.00", "US Dollar (Same day1.00", "US1.00", "UY1.00", "UZ1.00", "Ugandan Shillin1.00", "Ugandan Shilling (1966\\u201319871.00", "Ukrainian Hryvni1.00", "Ukrainian Karbovanet1.00", "Colombian Real Value Uni1.00", "United Arab Emirates Dirha1.00", "Unknown Currenc1.00", "Ur1.00", "Uruguay Peso (1975\\u201319931.00", "Uruguay Peso Uruguay1.00", "Uruguay Peso (Indexed Units1.00", "Uzbekistani So1.00", "V1.00", "VE1.00", "VN1.00", "VU1.00", "Vanuatu Vat1.00", "Venezuelan Bol\\u00edva1.00", "Venezuelan Bol\\u00edvar Fuert1.00", "Vietnamese Don1.00", "West African CFA Fran1.00", "Central African CFA Fran1.00", "WIR Eur1.00", "WIR Fran1.00", "WS1.00", "Samoa Tal1.00", "XA1.00", "XB1.00", "XC1.00", "XD1.00", "XE1.00", "XF1.00", "XO1.00", "XP1.00", "XR1.00", "XT1.00", "XX1.00", "YD1.00", "YE1.00", "YU1.00", "Yemeni Dina1.00", "Yemeni Ria1.00", "Yugoslavian Convertible Dina1.00", "Yugoslavian Hard Dinar (1966\\u201319901.00", "Yugoslavian New Dina1.00", "Z1.00", "ZA1.00", "ZM1.00", "ZR1.00", "ZW1.00", "Zairean New Zaire (1993\\u201319981.00", "Zairean Zair1.00", "Zambian Kwach1.00", "Zimbabwean Dollar (1980\\u201320081.00", "dra1.00", "lar1.00", "le1.00", "man1.00", "so1.00", }; Locale locale("en_US"); for (uint32_t i=0; i<UPRV_LENGTHOF(DATA); ++i) { UnicodeString formatted = ctou(DATA[i]); UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> numFmt(NumberFormat::createInstance(locale, UNUM_CURRENCY, status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } // NOTE: ICU 62 requires that the currency format match the pattern in strict mode. numFmt->setLenient(TRUE); ParsePosition parsePos; LocalPointer<CurrencyAmount> currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); if ( doubleVal != 1.0 ) { errln("Parsed as currency value other than 1.0: " + formatted + " -> " + doubleVal); } } else { errln("Failed to parse as currency: " + formatted); } } for (uint32_t i=0; i<UPRV_LENGTHOF(WRONG_DATA); ++i) { UnicodeString formatted = ctou(WRONG_DATA[i]); UErrorCode status = U_ZERO_ERROR; NumberFormat* numFmt = NumberFormat::createInstance(locale, UNUM_CURRENCY, status); if (numFmt != NULL && U_SUCCESS(status)) { ParsePosition parsePos; LocalPointer<CurrencyAmount> currAmt(numFmt->parseCurrency(formatted, parsePos)); if (parsePos.getIndex() > 0) { double doubleVal = currAmt->getNumber().getDouble(status); errln("Parsed as currency, should not have: " + formatted + " -> " + doubleVal); } } else { dataerrln("Unable to create NumberFormat. - %s", u_errorName(status)); delete numFmt; break; } delete numFmt; } } const char* attrString(int32_t); // UnicodeString s; // std::string ss; // std::cout << s.toUTF8String(ss) void NumberFormatTest::expectPositions(FieldPositionIterator& iter, int32_t *values, int32_t tupleCount, const UnicodeString& str) { UBool found[10]; FieldPosition fp; if (tupleCount > 10) { assertTrue("internal error, tupleCount too large", FALSE); } else { for (int i = 0; i < tupleCount; ++i) { found[i] = FALSE; } } logln(str); while (iter.next(fp)) { UBool ok = FALSE; int32_t id = fp.getField(); int32_t start = fp.getBeginIndex(); int32_t limit = fp.getEndIndex(); // is there a logln using printf? char buf[128]; sprintf(buf, "%24s %3d %3d %3d", attrString(id), id, start, limit); logln(buf); for (int i = 0; i < tupleCount; ++i) { if (found[i]) { continue; } if (values[i*3] == id && values[i*3+1] == start && values[i*3+2] == limit) { found[i] = ok = TRUE; break; } } assertTrue((UnicodeString)"found [" + id + "," + start + "," + limit + "]", ok); } // check that all were found UBool ok = TRUE; for (int i = 0; i < tupleCount; ++i) { if (!found[i]) { ok = FALSE; assertTrue((UnicodeString) "missing [" + values[i*3] + "," + values[i*3+1] + "," + values[i*3+2] + "]", found[i]); } } assertTrue("no expected values were missing", ok); } void NumberFormatTest::expectPosition(FieldPosition& pos, int32_t id, int32_t start, int32_t limit, const UnicodeString& str) { logln(str); assertTrue((UnicodeString)"id " + id + " == " + pos.getField(), id == pos.getField()); assertTrue((UnicodeString)"begin " + start + " == " + pos.getBeginIndex(), start == pos.getBeginIndex()); assertTrue((UnicodeString)"end " + limit + " == " + pos.getEndIndex(), limit == pos.getEndIndex()); } void NumberFormatTest::TestFieldPositionIterator() { // bug 7372 UErrorCode status = U_ZERO_ERROR; FieldPositionIterator iter1; FieldPositionIterator iter2; FieldPosition pos; DecimalFormat *decFmt = (DecimalFormat *) NumberFormat::createInstance(status); if (failure(status, "NumberFormat::createInstance", TRUE)) return; double num = 1234.56; UnicodeString str1; UnicodeString str2; assertTrue((UnicodeString)"self==", iter1 == iter1); assertTrue((UnicodeString)"iter1==iter2", iter1 == iter2); decFmt->format(num, str1, &iter1, status); assertTrue((UnicodeString)"iter1 != iter2", iter1 != iter2); decFmt->format(num, str2, &iter2, status); assertTrue((UnicodeString)"iter1 == iter2 (2)", iter1 == iter2); iter1.next(pos); assertTrue((UnicodeString)"iter1 != iter2 (2)", iter1 != iter2); iter2.next(pos); assertTrue((UnicodeString)"iter1 == iter2 (3)", iter1 == iter2); // should format ok with no iterator str2.remove(); decFmt->format(num, str2, NULL, status); assertEquals("null fpiter", str1, str2); delete decFmt; } void NumberFormatTest::TestFormatAttributes() { Locale locale("en_US"); UErrorCode status = U_ZERO_ERROR; DecimalFormat *decFmt = (DecimalFormat *) NumberFormat::createInstance(locale, UNUM_CURRENCY, status); if (failure(status, "NumberFormat::createInstance", TRUE)) return; double val = 12345.67; { int32_t expected[] = { UNUM_CURRENCY_FIELD, 0, 1, UNUM_GROUPING_SEPARATOR_FIELD, 3, 4, UNUM_INTEGER_FIELD, 1, 7, UNUM_DECIMAL_SEPARATOR_FIELD, 7, 8, UNUM_FRACTION_FIELD, 8, 10, }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; FieldPositionIterator posIter; UnicodeString result; decFmt->format(val, result, &posIter, status); expectPositions(posIter, expected, tupleCount, result); } { FieldPosition fp(UNUM_INTEGER_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_INTEGER_FIELD, 1, 7, result); } { FieldPosition fp(UNUM_FRACTION_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_FRACTION_FIELD, 8, 10, result); } delete decFmt; decFmt = (DecimalFormat *) NumberFormat::createInstance(locale, UNUM_SCIENTIFIC, status); val = -0.0000123; { int32_t expected[] = { UNUM_SIGN_FIELD, 0, 1, UNUM_INTEGER_FIELD, 1, 2, UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3, UNUM_FRACTION_FIELD, 3, 5, UNUM_EXPONENT_SYMBOL_FIELD, 5, 6, UNUM_EXPONENT_SIGN_FIELD, 6, 7, UNUM_EXPONENT_FIELD, 7, 8 }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; FieldPositionIterator posIter; UnicodeString result; decFmt->format(val, result, &posIter, status); expectPositions(posIter, expected, tupleCount, result); } { FieldPosition fp(UNUM_INTEGER_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_INTEGER_FIELD, 1, 2, result); } { FieldPosition fp(UNUM_FRACTION_FIELD); UnicodeString result; decFmt->format(val, result, fp); expectPosition(fp, UNUM_FRACTION_FIELD, 3, 5, result); } delete decFmt; fflush(stderr); } const char* attrString(int32_t attrId) { switch (attrId) { case UNUM_INTEGER_FIELD: return "integer"; case UNUM_FRACTION_FIELD: return "fraction"; case UNUM_DECIMAL_SEPARATOR_FIELD: return "decimal separator"; case UNUM_EXPONENT_SYMBOL_FIELD: return "exponent symbol"; case UNUM_EXPONENT_SIGN_FIELD: return "exponent sign"; case UNUM_EXPONENT_FIELD: return "exponent"; case UNUM_GROUPING_SEPARATOR_FIELD: return "grouping separator"; case UNUM_CURRENCY_FIELD: return "currency"; case UNUM_PERCENT_FIELD: return "percent"; case UNUM_PERMILL_FIELD: return "permille"; case UNUM_SIGN_FIELD: return "sign"; default: return ""; } } // // Test formatting & parsing of big decimals. // API test, not a comprehensive test. // See DecimalFormatTest/DataDrivenTests // #define ASSERT_SUCCESS(status) { \ assertSuccess(UnicodeString("file ") + __FILE__ + ", line " + __LINE__, (status)); \ } #define ASSERT_EQUALS(expected, actual) { \ assertEquals(UnicodeString("file ") + __FILE__ + ", line " + __LINE__, (expected), (actual)); \ } void NumberFormatTest::TestDecimal() { { UErrorCode status = U_ZERO_ERROR; Formattable f("12.345678999987654321E666", status); ASSERT_SUCCESS(status); StringPiece s = f.getDecimalNumber(status); ASSERT_SUCCESS(status); ASSERT_EQUALS("1.2345678999987654321E+667", s.data()); //printf("%s\n", s.data()); } { UErrorCode status = U_ZERO_ERROR; Formattable f1("this is not a number", status); ASSERT_EQUALS(U_DECIMAL_NUMBER_SYNTAX_ERROR, status); } { UErrorCode status = U_ZERO_ERROR; Formattable f; f.setDecimalNumber("123.45", status); ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kDouble, f.getType()); ASSERT_EQUALS(123.45, f.getDouble()); ASSERT_EQUALS(123.45, f.getDouble(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("123.45", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); f.setDecimalNumber("4.5678E7", status); int32_t n; n = f.getLong(); ASSERT_EQUALS(45678000, n); status = U_ZERO_ERROR; f.setDecimalNumber("-123", status); ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kLong, f.getType()); ASSERT_EQUALS(-123, f.getLong()); ASSERT_EQUALS(-123, f.getLong(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("-123", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); status = U_ZERO_ERROR; f.setDecimalNumber("1234567890123", status); // Number too big for 32 bits ASSERT_SUCCESS(status); ASSERT_EQUALS( Formattable::kInt64, f.getType()); ASSERT_EQUALS(1234567890123LL, f.getInt64()); ASSERT_EQUALS(1234567890123LL, f.getInt64(status)); ASSERT_SUCCESS(status); ASSERT_EQUALS("1.234567890123E+12", f.getDecimalNumber(status).data()); ASSERT_SUCCESS(status); } { UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString formattedResult; StringPiece num("244444444444444444444444444444444444446.4"); fmtr->format(num, formattedResult, NULL, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("244,444,444,444,444,444,444,444,444,444,444,444,446.4", formattedResult); //std::string ss; std::cout << formattedResult.toUTF8String(ss); delete fmtr; } } { // Check formatting a DigitList. DigitList is internal, but this is // a critical interface that must work. UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString formattedResult; DecimalQuantity dl; StringPiece num("123.4566666666666666666666666666666666621E+40"); dl.setToDecNumber(num, status); ASSERT_SUCCESS(status); fmtr->format(dl, formattedResult, NULL, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("1,234,566,666,666,666,666,666,666,666,666,666,666,621,000", formattedResult); status = U_ZERO_ERROR; num.set("666.666"); dl.setToDecNumber(num, status); FieldPosition pos(NumberFormat::FRACTION_FIELD); ASSERT_SUCCESS(status); formattedResult.remove(); fmtr->format(dl, formattedResult, pos, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("666.666", formattedResult); ASSERT_EQUALS(4, pos.getBeginIndex()); ASSERT_EQUALS(7, pos.getEndIndex()); delete fmtr; } } { // Check a parse with a formatter with a multiplier. UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_PERCENT, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString input = "1.84%"; Formattable result; fmtr->parse(input, result, status); ASSERT_SUCCESS(status); ASSERT_EQUALS("0.0184", result.getDecimalNumber(status).data()); //std::cout << result.getDecimalNumber(status).data(); delete fmtr; } } #if U_PLATFORM != U_PF_CYGWIN || defined(CYGWINMSVC) /* * This test fails on Cygwin (1.7.16) using GCC because of a rounding issue with strtod(). * See #9463 */ { // Check that a parse returns a decimal number with full accuracy UErrorCode status = U_ZERO_ERROR; NumberFormat *fmtr = NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, status); if (U_FAILURE(status) || fmtr == NULL) { dataerrln("Unable to create NumberFormat"); } else { UnicodeString input = "1.002200044400088880000070000"; Formattable result; fmtr->parse(input, result, status); ASSERT_SUCCESS(status); ASSERT_EQUALS(0, strcmp("1.00220004440008888000007", result.getDecimalNumber(status).data())); ASSERT_EQUALS(1.00220004440008888, result.getDouble()); //std::cout << result.getDecimalNumber(status).data(); delete fmtr; } } #endif } void NumberFormatTest::TestCurrencyFractionDigits() { UErrorCode status = U_ZERO_ERROR; UnicodeString text1, text2; double value = 99.12345; // Create currenct instance NumberFormat* fmt = NumberFormat::createCurrencyInstance("ja_JP", status); if (U_FAILURE(status) || fmt == NULL) { dataerrln("Unable to create NumberFormat"); } else { fmt->format(value, text1); // Reset the same currency and format the test value again fmt->setCurrency(fmt->getCurrency(), status); ASSERT_SUCCESS(status); fmt->format(value, text2); if (text1 != text2) { errln((UnicodeString)"NumberFormat::format() should return the same result - text1=" + text1 + " text2=" + text2); } } delete fmt; } void NumberFormatTest::TestExponentParse() { UErrorCode status = U_ZERO_ERROR; Formattable result; ParsePosition parsePos(0); // set the exponent symbol status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getDefault(), status); if(U_FAILURE(status)) { dataerrln((UnicodeString)"ERROR: Could not create DecimalFormatSymbols (Default)"); return; } // create format instance status = U_ZERO_ERROR; DecimalFormat fmt(u"#####", symbols, status); if(U_FAILURE(status)) { errln((UnicodeString)"ERROR: Could not create DecimalFormat (pattern, symbols*)"); } // parse the text fmt.parse("5.06e-27", result, parsePos); if(result.getType() != Formattable::kDouble && result.getDouble() != 5.06E-27 && parsePos.getIndex() != 8 ) { errln("ERROR: parse failed - expected 5.06E-27, 8 - returned %d, %i", result.getDouble(), parsePos.getIndex()); } } void NumberFormatTest::TestExplicitParents() { /* Test that number formats are properly inherited from es_419 */ /* These could be subject to change if the CLDR data changes */ static const char* parentLocaleTests[][2]= { /* locale ID */ /* expected */ {"es_CO", "1.250,75" }, {"es_ES", "1.250,75" }, {"es_GQ", "1.250,75" }, {"es_MX", "1,250.75" }, {"es_US", "1,250.75" }, {"es_VE", "1.250,75" }, }; UnicodeString s; for(int i=0; i < UPRV_LENGTHOF(parentLocaleTests); i++){ UErrorCode status = U_ZERO_ERROR; const char *localeID = parentLocaleTests[i][0]; UnicodeString expected(parentLocaleTests[i][1], -1, US_INV); expected = expected.unescape(); char loc[256]={0}; uloc_canonicalize(localeID, loc, 256, &status); NumberFormat *fmt= NumberFormat::createInstance(Locale(loc), status); if(U_FAILURE(status)){ dataerrln("Could not create number formatter for locale %s - %s",localeID, u_errorName(status)); continue; } s.remove(); fmt->format(1250.75, s); if(s!=expected){ errln(UnicodeString("FAIL: Expected: ")+expected + UnicodeString(" Got: ") + s + UnicodeString( " for locale: ")+ UnicodeString(localeID) ); } if (U_FAILURE(status)){ errln((UnicodeString)"FAIL: Status " + (int32_t)status); } delete fmt; } } /** * Test available numbering systems API. */ void NumberFormatTest::TestAvailableNumberingSystems() { UErrorCode status = U_ZERO_ERROR; StringEnumeration *availableNumberingSystems = NumberingSystem::getAvailableNames(status); CHECK_DATA(status, "NumberingSystem::getAvailableNames()") int32_t nsCount = availableNumberingSystems->count(status); if ( nsCount < 74 ) { errln("FAIL: Didn't get as many numbering systems as we had hoped for. Need at least 74, got %d",nsCount); } /* A relatively simple test of the API. We call getAvailableNames() and cycle through */ /* each name returned, attempting to create a numbering system based on that name and */ /* verifying that the name returned from the resulting numbering system is the same */ /* one that we initially thought. */ int32_t len; for ( int32_t i = 0 ; i < nsCount ; i++ ) { const char *nsname = availableNumberingSystems->next(&len,status); NumberingSystem* ns = NumberingSystem::createInstanceByName(nsname,status); logln("OK for ns = %s",nsname); if ( uprv_strcmp(nsname,ns->getName()) ) { errln("FAIL: Numbering system name didn't match for name = %s\n",nsname); } delete ns; } delete availableNumberingSystems; } void NumberFormatTest::Test9087(void) { U_STRING_DECL(pattern,"#",1); U_STRING_INIT(pattern,"#",1); U_STRING_DECL(infstr,"INF",3); U_STRING_INIT(infstr,"INF",3); U_STRING_DECL(nanstr,"NAN",3); U_STRING_INIT(nanstr,"NAN",3); UChar outputbuf[50] = {0}; UErrorCode status = U_ZERO_ERROR; UNumberFormat* fmt = unum_open(UNUM_PATTERN_DECIMAL,pattern,1,NULL,NULL,&status); if ( U_FAILURE(status) ) { dataerrln("FAIL: error in unum_open() - %s", u_errorName(status)); return; } unum_setSymbol(fmt,UNUM_INFINITY_SYMBOL,infstr,3,&status); unum_setSymbol(fmt,UNUM_NAN_SYMBOL,nanstr,3,&status); if ( U_FAILURE(status) ) { errln("FAIL: error setting symbols"); } double inf = uprv_getInfinity(); unum_setAttribute(fmt,UNUM_ROUNDING_MODE,UNUM_ROUND_HALFEVEN); unum_setDoubleAttribute(fmt,UNUM_ROUNDING_INCREMENT,0); UFieldPosition position = { 0, 0, 0}; unum_formatDouble(fmt,inf,outputbuf,50,&position,&status); if ( u_strcmp(infstr, outputbuf)) { errln((UnicodeString)"FAIL: unexpected result for infinity - expected " + infstr + " got " + outputbuf); } unum_close(fmt); } void NumberFormatTest::TestFormatFastpaths() { // get some additional case { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = 1; UnicodeString expect = "0001"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000000000000000000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MIN; // -9223372036854775808L; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "-9223372036854775808"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on -9223372036854775808", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on -9223372036854775808"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString(u"0000000000000000000"),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MAX; // -9223372036854775808L; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "9223372036854775807"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on U_INT64_MAX", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on U_INT64_MAX"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString("0000000000000000000",""),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = 0; // uint8_t bits[8]; // memcpy(bits,&long_number,8); // for(int i=0;i<8;i++) { // logln("bits: %02X", (unsigned int)bits[i]); // } UnicodeString expect = "0000000000000000000"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on 0", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on 0"); } } } { UErrorCode status=U_ZERO_ERROR; DecimalFormat df(UnicodeString("0000000000000000000",""),status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); } else { int64_t long_number = U_INT64_MIN + 1; UnicodeString expect = "-9223372036854775807"; UnicodeString result; FieldPosition pos; df.format(long_number, result, pos); if(U_FAILURE(status)||expect!=result) { dataerrln("%s:%d FAIL: expected '%s' got '%s' status %s on -9223372036854775807", __FILE__, __LINE__, CStr(expect)(), CStr(result)(), u_errorName(status)); } else { logln("OK: got expected '"+result+"' status "+UnicodeString(u_errorName(status),"")+" on -9223372036854775807"); } } } } void NumberFormatTest::TestFormattableSize(void) { if(sizeof(Formattable) > 112) { errln("Error: sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } else if(sizeof(Formattable) < 112) { logln("Warning: sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } else { logln("sizeof(Formattable)=%d, 112=%d\n", sizeof(Formattable), 112); } } UBool NumberFormatTest::testFormattableAsUFormattable(const char *file, int line, Formattable &f) { UnicodeString fileLine = UnicodeString(file)+UnicodeString(":")+line+UnicodeString(": "); UFormattable *u = f.toUFormattable(); logln(); if (u == NULL) { errln("%s:%d: Error: f.toUFormattable() retuned NULL."); return FALSE; } logln("%s:%d: comparing Formattable with UFormattable", file, line); logln(fileLine + toString(f)); UErrorCode status = U_ZERO_ERROR; UErrorCode valueStatus = U_ZERO_ERROR; UFormattableType expectUType = UFMT_COUNT; // invalid UBool triedExact = FALSE; // did we attempt an exact comparison? UBool exactMatch = FALSE; // was the exact comparison true? switch( f.getType() ) { case Formattable::kDate: expectUType = UFMT_DATE; exactMatch = (f.getDate()==ufmt_getDate(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kDouble: expectUType = UFMT_DOUBLE; exactMatch = (f.getDouble()==ufmt_getDouble(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kLong: expectUType = UFMT_LONG; exactMatch = (f.getLong()==ufmt_getLong(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kString: expectUType = UFMT_STRING; { UnicodeString str; f.getString(str); int32_t len; const UChar* uch = ufmt_getUChars(u, &len, &valueStatus); if(U_SUCCESS(valueStatus)) { UnicodeString str2(uch, len); assertTrue("UChar* NULL-terminated", uch[len]==0); exactMatch = (str == str2); } triedExact = TRUE; } break; case Formattable::kArray: expectUType = UFMT_ARRAY; triedExact = TRUE; { int32_t count = ufmt_getArrayLength(u, &valueStatus); int32_t count2; const Formattable *array2 = f.getArray(count2); exactMatch = assertEquals(fileLine + " array count", count, count2); if(exactMatch) { for(int i=0;U_SUCCESS(valueStatus) && i<count;i++) { UFormattable *uu = ufmt_getArrayItemByIndex(u, i, &valueStatus); if(*Formattable::fromUFormattable(uu) != (array2[i])) { errln("%s:%d: operator== did not match at index[%d] - %p vs %p", file, line, i, (const void*)Formattable::fromUFormattable(uu), (const void*)&(array2[i])); exactMatch = FALSE; } else { if(!testFormattableAsUFormattable("(sub item)",i,*Formattable::fromUFormattable(uu))) { exactMatch = FALSE; } } } } } break; case Formattable::kInt64: expectUType = UFMT_INT64; exactMatch = (f.getInt64()==ufmt_getInt64(u, &valueStatus)); triedExact = TRUE; break; case Formattable::kObject: expectUType = UFMT_OBJECT; exactMatch = (f.getObject()==ufmt_getObject(u, &valueStatus)); triedExact = TRUE; break; } UFormattableType uType = ufmt_getType(u, &status); if(U_FAILURE(status)) { errln("%s:%d: Error calling ufmt_getType - %s", file, line, u_errorName(status)); return FALSE; } if(uType != expectUType) { errln("%s:%d: got type (%d) expected (%d) from ufmt_getType", file, line, (int) uType, (int) expectUType); } if(triedExact) { if(U_FAILURE(valueStatus)) { errln("%s:%d: got err %s trying to ufmt_get...() for exact match check", file, line, u_errorName(valueStatus)); } else if(!exactMatch) { errln("%s:%d: failed exact match for the Formattable type", file, line); } else { logln("%s:%d: exact match OK", file, line); } } else { logln("%s:%d: note, did not attempt exact match for this formattable type", file, line); } if( assertEquals(fileLine + " isNumeric()", f.isNumeric(), ufmt_isNumeric(u)) && f.isNumeric()) { UErrorCode convStatus = U_ZERO_ERROR; if(uType != UFMT_INT64) { // may fail to compare assertTrue(fileLine + " as doubles ==", f.getDouble(convStatus)==ufmt_getDouble(u, &convStatus)); } if( assertSuccess(fileLine + " (numeric conversion status)", convStatus) ) { StringPiece fDecNum = f.getDecimalNumber(convStatus); #if 1 int32_t len; const char *decNumChars = ufmt_getDecNumChars(u, &len, &convStatus); #else // copy version char decNumChars[200]; int32_t len = ufmt_getDecNumChars(u, decNumChars, 200, &convStatus); #endif if( assertSuccess(fileLine + " (decNumbers conversion)", convStatus) ) { logln(fileLine + decNumChars); assertEquals(fileLine + " decNumChars length==", len, fDecNum.length()); assertEquals(fileLine + " decNumChars digits", decNumChars, fDecNum.data()); } UErrorCode int64ConversionF = U_ZERO_ERROR; int64_t l = f.getInt64(int64ConversionF); UErrorCode int64ConversionU = U_ZERO_ERROR; int64_t r = ufmt_getInt64(u, &int64ConversionU); if( (l==r) && ( uType != UFMT_INT64 ) // int64 better not overflow && (U_INVALID_FORMAT_ERROR==int64ConversionU) && (U_INVALID_FORMAT_ERROR==int64ConversionF) ) { logln("%s:%d: OK: 64 bit overflow", file, line); } else { assertEquals(fileLine + " as int64 ==", l, r); assertSuccess(fileLine + " Formattable.getnt64()", int64ConversionF); assertSuccess(fileLine + " ufmt_getInt64()", int64ConversionU); } } } return exactMatch || !triedExact; } void NumberFormatTest::TestUFormattable(void) { { // test that a default formattable is equal to Formattable() UErrorCode status = U_ZERO_ERROR; LocalUFormattablePointer defaultUFormattable(ufmt_open(&status)); assertSuccess("calling umt_open", status); Formattable defaultFormattable; assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); assertTrue((UnicodeString)"comparing ufmt_open() with Formattable()", (defaultFormattable == *(Formattable::fromUFormattable(defaultUFormattable.getAlias())))); assertTrue((UnicodeString)"comparing Formattable() round tripped through UFormattable", (defaultFormattable == *(Formattable::fromUFormattable(defaultFormattable.toUFormattable())))); assertTrue((UnicodeString)"comparing &Formattable() round tripped through UFormattable", ((&defaultFormattable) == Formattable::fromUFormattable(defaultFormattable.toUFormattable()))); assertFalse((UnicodeString)"comparing &Formattable() with ufmt_open()", ((&defaultFormattable) == Formattable::fromUFormattable(defaultUFormattable.getAlias()))); testFormattableAsUFormattable(__FILE__, __LINE__, defaultFormattable); } // test some random Formattables { Formattable f(ucal_getNow(), Formattable::kIsDate); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((double)1.61803398874989484820); // golden ratio testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((int64_t)80994231587905127LL); // weight of the moon, in kilotons http://solarsystem.nasa.gov/planets/profile.cfm?Display=Facts&Object=Moon testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f((int32_t)4); // random number, source: http://www.xkcd.com/221/ testFormattableAsUFormattable(__FILE__, __LINE__, f); } { Formattable f("Hello world."); // should be invariant? testFormattableAsUFormattable(__FILE__, __LINE__, f); } { UErrorCode status2 = U_ZERO_ERROR; Formattable f(StringPiece("73476730924573500000000.0"), status2); // weight of the moon, kg assertSuccess("Constructing a StringPiece", status2); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { UErrorCode status2 = U_ZERO_ERROR; UObject *obj = new Locale(); Formattable f(obj); assertSuccess("Constructing a Formattable from a default constructed Locale()", status2); testFormattableAsUFormattable(__FILE__, __LINE__, f); } { const Formattable array[] = { Formattable(ucal_getNow(), Formattable::kIsDate), Formattable((int32_t)4), Formattable((double)1.234), }; Formattable fa(array, 3); testFormattableAsUFormattable(__FILE__, __LINE__, fa); } } void NumberFormatTest::TestSignificantDigits(void) { double input[] = { 0, 0, 0.1, -0.1, 123, -123, 12345, -12345, 123.45, -123.45, 123.44501, -123.44501, 0.001234, -0.001234, 0.00000000123, -0.00000000123, 0.0000000000000000000123, -0.0000000000000000000123, 1.2, -1.2, 0.0000000012344501, -0.0000000012344501, 123445.01, -123445.01, 12344501000000000000000000000000000.0, -12344501000000000000000000000000000.0, }; const char* expected[] = { "0.00", "0.00", "0.100", "-0.100", "123", "-123", "12345", "-12345", "123.45", "-123.45", "123.45", "-123.45", "0.001234", "-0.001234", "0.00000000123", "-0.00000000123", "0.0000000000000000000123", "-0.0000000000000000000123", "1.20", "-1.20", "0.0000000012345", "-0.0000000012345", "123450", "-123450", "12345000000000000000000000000000000", "-12345000000000000000000000000000000", }; UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); CHECK_DATA(status,"NumberFormat::createInstance") numberFormat->setSignificantDigitsUsed(TRUE); numberFormat->setMinimumSignificantDigits(3); numberFormat->setMaximumSignificantDigits(5); numberFormat->setGroupingUsed(false); UnicodeString result; UnicodeString expectedResult; for (unsigned int i = 0; i < UPRV_LENGTHOF(input); ++i) { numberFormat->format(input[i], result); UnicodeString expectedResult(expected[i]); if (result != expectedResult) { errln((UnicodeString)"Expected: '" + expectedResult + "' got '" + result); } result.remove(); } // Test for ICU-20063 { DecimalFormat df({"en-us", status}, status); df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.87654"); df.setMaximumSignificantDigits(3); expect(df, 9.87654321, u"9.88"); // setSignificantDigitsUsed with maxSig only df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.88"); df.setMinimumSignificantDigits(2); expect(df, 9, u"9.0"); // setSignificantDigitsUsed with both minSig and maxSig df.setSignificantDigitsUsed(TRUE); expect(df, 9, u"9.0"); // setSignificantDigitsUsed to false: should revert to fraction rounding df.setSignificantDigitsUsed(FALSE); expect(df, 9.87654321, u"9.876543"); expect(df, 9, u"9"); df.setSignificantDigitsUsed(TRUE); df.setMinimumSignificantDigits(2); expect(df, 9.87654321, u"9.87654"); expect(df, 9, u"9.0"); // setSignificantDigitsUsed with minSig only df.setSignificantDigitsUsed(TRUE); expect(df, 9.87654321, u"9.87654"); expect(df, 9, u"9.0"); } } void NumberFormatTest::TestShowZero() { UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); CHECK_DATA(status, "NumberFormat::createInstance") numberFormat->setSignificantDigitsUsed(TRUE); numberFormat->setMaximumSignificantDigits(3); UnicodeString result; numberFormat->format(0.0, result); if (result != "0") { errln((UnicodeString)"Expected: 0, got " + result); } } void NumberFormatTest::TestBug9936() { UErrorCode status = U_ZERO_ERROR; Locale locale("en_US"); LocalPointer<DecimalFormat> numberFormat(static_cast<DecimalFormat*>( NumberFormat::createInstance(locale, status))); if (U_FAILURE(status)) { dataerrln("File %s, Line %d: status = %s.\n", __FILE__, __LINE__, u_errorName(status)); return; } if (numberFormat->areSignificantDigitsUsed() == TRUE) { errln("File %s, Line %d: areSignificantDigitsUsed() was TRUE, expected FALSE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(TRUE); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(FALSE); if (numberFormat->areSignificantDigitsUsed() == TRUE) { errln("File %s, Line %d: areSignificantDigitsUsed() was TRUE, expected FALSE.\n", __FILE__, __LINE__); } numberFormat->setMinimumSignificantDigits(3); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } numberFormat->setSignificantDigitsUsed(FALSE); numberFormat->setMaximumSignificantDigits(6); if (numberFormat->areSignificantDigitsUsed() == FALSE) { errln("File %s, Line %d: areSignificantDigitsUsed() was FALSE, expected TRUE.\n", __FILE__, __LINE__); } } void NumberFormatTest::TestParseNegativeWithFaLocale() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *test = (DecimalFormat *) NumberFormat::createInstance("fa", status); CHECK_DATA(status, "NumberFormat::createInstance") test->setLenient(TRUE); Formattable af; ParsePosition ppos; UnicodeString value("\\u200e-0,5"); value = value.unescape(); test->parse(value, af, ppos); if (ppos.getIndex() == 0) { errln("Expected -0,5 to parse for Farsi."); } delete test; } void NumberFormatTest::TestParseNegativeWithAlternateMinusSign() { UErrorCode status = U_ZERO_ERROR; DecimalFormat *test = (DecimalFormat *) NumberFormat::createInstance("en", status); CHECK_DATA(status, "NumberFormat::createInstance") test->setLenient(TRUE); Formattable af; ParsePosition ppos; UnicodeString value("\\u208B0.5"); value = value.unescape(); test->parse(value, af, ppos); if (ppos.getIndex() == 0) { errln(UnicodeString("Expected ") + value + UnicodeString(" to parse.")); } delete test; } void NumberFormatTest::TestCustomCurrencySignAndSeparator() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols custom(Locale::getUS(), status); CHECK(status, "DecimalFormatSymbols constructor"); custom.setSymbol(DecimalFormatSymbols::kCurrencySymbol, "*"); custom.setSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol, "^"); custom.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, ":"); UnicodeString pat(" #,##0.00"); pat.insert(0, (UChar)0x00A4); DecimalFormat fmt(pat, custom, status); CHECK(status, "DecimalFormat constructor"); UnicodeString numstr("* 1^234:56"); expect2(fmt, (Formattable)((double)1234.56), numstr); } typedef struct { const char * locale; UBool lenient; UnicodeString numString; double value; } SignsAndMarksItem; void NumberFormatTest::TestParseSignsAndMarks() { const SignsAndMarksItem items[] = { // locale lenient numString value { "en", FALSE, CharsToUnicodeString("12"), 12 }, { "en", TRUE, CharsToUnicodeString("12"), 12 }, { "en", FALSE, CharsToUnicodeString("-23"), -23 }, { "en", TRUE, CharsToUnicodeString("-23"), -23 }, { "en", TRUE, CharsToUnicodeString("- 23"), -23 }, { "en", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "en", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "en", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("- \\u0664\\u0665"), -45 }, { "en@numbers=arab", FALSE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "en@numbers=arab", TRUE, CharsToUnicodeString("\\u200F- \\u0664\\u0665"), -45 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("- \\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", FALSE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "en@numbers=arabext", TRUE, CharsToUnicodeString("\\u200E-\\u200E \\u06F6\\u06F7"), -67 }, { "he", FALSE, CharsToUnicodeString("12"), 12 }, { "he", TRUE, CharsToUnicodeString("12"), 12 }, { "he", FALSE, CharsToUnicodeString("-23"), -23 }, { "he", TRUE, CharsToUnicodeString("-23"), -23 }, { "he", TRUE, CharsToUnicodeString("- 23"), -23 }, { "he", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "he", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "he", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "ar", FALSE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "ar", TRUE, CharsToUnicodeString("\\u0663\\u0664"), 34 }, { "ar", FALSE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("- \\u0664\\u0665"), -45 }, { "ar", FALSE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("\\u200F-\\u0664\\u0665"), -45 }, { "ar", TRUE, CharsToUnicodeString("\\u200F- \\u0664\\u0665"), -45 }, { "ar_MA", FALSE, CharsToUnicodeString("12"), 12 }, { "ar_MA", TRUE, CharsToUnicodeString("12"), 12 }, { "ar_MA", FALSE, CharsToUnicodeString("-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("- 23"), -23 }, { "ar_MA", FALSE, CharsToUnicodeString("\\u200E-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("\\u200E-23"), -23 }, { "ar_MA", TRUE, CharsToUnicodeString("\\u200E- 23"), -23 }, { "fa", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "fa", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "fa", FALSE, CharsToUnicodeString("\\u2212\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u2212\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u2212 \\u06F6\\u06F7"), -67 }, { "fa", FALSE, CharsToUnicodeString("\\u200E\\u2212\\u200E\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u200E\\u2212\\u200E\\u06F6\\u06F7"), -67 }, { "fa", TRUE, CharsToUnicodeString("\\u200E\\u2212\\u200E \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "ps", TRUE, CharsToUnicodeString("\\u06F5\\u06F6"), 56 }, { "ps", FALSE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("- \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("\\u200E-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("\\u200E-\\u200E \\u06F6\\u06F7"), -67 }, { "ps", FALSE, CharsToUnicodeString("-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u200E\\u06F6\\u06F7"), -67 }, { "ps", TRUE, CharsToUnicodeString("-\\u200E \\u06F6\\u06F7"), -67 }, // terminator { NULL, 0, UnicodeString(""), 0 }, }; const SignsAndMarksItem * itemPtr; for (itemPtr = items; itemPtr->locale != NULL; itemPtr++ ) { UErrorCode status = U_ZERO_ERROR; NumberFormat *numfmt = NumberFormat::createInstance(Locale(itemPtr->locale), status); if (U_SUCCESS(status)) { numfmt->setLenient(itemPtr->lenient); Formattable fmtobj; ParsePosition ppos; numfmt->parse(itemPtr->numString, fmtobj, ppos); if (ppos.getIndex() == itemPtr->numString.length()) { double parsedValue = fmtobj.getDouble(status); if (U_FAILURE(status) || parsedValue != itemPtr->value) { errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives value " + parsedValue); } } else { errln((UnicodeString)"FAIL: locale " + itemPtr->locale + ", lenient " + itemPtr->lenient + ", parse of \"" + itemPtr->numString + "\" gives position " + ppos.getIndex()); } } else { dataerrln("FAIL: NumberFormat::createInstance for locale % gives error %s", itemPtr->locale, u_errorName(status)); } delete numfmt; } } typedef struct { DecimalFormat::ERoundingMode mode; double value; UnicodeString expected; } Test10419Data; // Tests that rounding works right when fractional digits is set to 0. void NumberFormatTest::Test10419RoundingWith0FractionDigits() { const Test10419Data items[] = { { DecimalFormat::kRoundCeiling, 1.488, "2"}, { DecimalFormat::kRoundDown, 1.588, "1"}, { DecimalFormat::kRoundFloor, 1.888, "1"}, { DecimalFormat::kRoundHalfDown, 1.5, "1"}, { DecimalFormat::kRoundHalfEven, 2.5, "2"}, { DecimalFormat::kRoundHalfUp, 2.5, "3"}, { DecimalFormat::kRoundUp, 1.5, "2"}, }; UErrorCode status = U_ZERO_ERROR; LocalPointer<DecimalFormat> decfmt((DecimalFormat *) NumberFormat::createInstance(Locale("en_US"), status)); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } for (int32_t i = 0; i < UPRV_LENGTHOF(items); ++i) { decfmt->setRoundingMode(items[i].mode); decfmt->setMaximumFractionDigits(0); UnicodeString actual; if (items[i].expected != decfmt->format(items[i].value, actual)) { errln("Expected " + items[i].expected + ", got " + actual); } } } void NumberFormatTest::Test10468ApplyPattern() { // Padding char of fmt is now 'a' UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("'I''ll'*a###.##", status); if (U_FAILURE(status)) { errcheckln(status, "DecimalFormat constructor failed - %s", u_errorName(status)); return; } assertEquals("Padding character should be 'a'.", u"a", fmt.getPadCharacterString()); // Padding char of fmt ought to be '*' since that is the default and no // explicit padding char is specified in the new pattern. fmt.applyPattern("AA#,##0.00ZZ", status); // Oops this still prints 'a' even though we changed the pattern. assertEquals("applyPattern did not clear padding character.", u" ", fmt.getPadCharacterString()); } void NumberFormatTest::TestRoundingScientific10542() { UErrorCode status = U_ZERO_ERROR; DecimalFormat format("0.00E0", status); if (U_FAILURE(status)) { errcheckln(status, "DecimalFormat constructor failed - %s", u_errorName(status)); return; } DecimalFormat::ERoundingMode roundingModes[] = { DecimalFormat::kRoundCeiling, DecimalFormat::kRoundDown, DecimalFormat::kRoundFloor, DecimalFormat::kRoundHalfDown, DecimalFormat::kRoundHalfEven, DecimalFormat::kRoundHalfUp, DecimalFormat::kRoundUp}; const char *descriptions[] = { "Round Ceiling", "Round Down", "Round Floor", "Round half down", "Round half even", "Round half up", "Round up"}; { double values[] = {-0.003006, -0.003005, -0.003004, 0.003014, 0.003015, 0.003016}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-3.00E-3", "-3.00E-3", "-3.00E-3", "3.02E-3", "3.02E-3", "3.02E-3", "-3.00E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.01E-3", "-3.01E-3", "-3.01E-3", "-3.01E-3", "3.01E-3", "3.01E-3", "3.01E-3", "-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.01E-3", "3.02E-3", "-3.01E-3", "-3.00E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3", "-3.01E-3", "-3.01E-3", "-3.00E-3", "3.01E-3", "3.02E-3", "3.02E-3", "-3.01E-3", "-3.01E-3", "-3.01E-3", "3.02E-3", "3.02E-3", "3.02E-3"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-3006.0, -3005, -3004, 3014, 3015, 3016}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-3.00E3", "-3.00E3", "-3.00E3", "3.02E3", "3.02E3", "3.02E3", "-3.00E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.01E3", "-3.01E3", "-3.01E3", "-3.01E3", "3.01E3", "3.01E3", "3.01E3", "-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.01E3", "3.02E3", "-3.01E3", "-3.00E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3", "-3.01E3", "-3.01E3", "-3.00E3", "3.01E3", "3.02E3", "3.02E3", "-3.01E3", "-3.01E3", "-3.01E3", "3.02E3", "3.02E3", "3.02E3"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } /* Commented out for now until we decide how rounding to zero should work, +0 vs. -0 { double values[] = {0.0, -0.0}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0", "0.00E0", "-0.00E0"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } */ { double values[] = {1e25, 1e25 + 1e15, 1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "1.00E25", "1.01E25", "1.00E25", "1.00E25", "1.00E25", "9.99E24", "1.00E25", "1.00E25", "9.99E24", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.00E25", "1.01E25", "1.00E25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-1e25, -1e25 + 1e15, -1e25 - 1e15}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-1.00E25", "-9.99E24", "-1.00E25", "-1.00E25", "-9.99E24", "-1.00E25", "-1.00E25", "-1.00E25", "-1.01E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.00E25", "-1.01E25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {1e-25, 1e-25 + 1e-35, 1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "1.00E-25", "1.01E-25", "1.00E-25", "1.00E-25", "1.00E-25", "9.99E-26", "1.00E-25", "1.00E-25", "9.99E-26", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.00E-25", "1.01E-25", "1.00E-25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } { double values[] = {-1e-25, -1e-25 + 1e-35, -1e-25 - 1e-35}; // The order of these expected values correspond to the order of roundingModes and the order of values. const char *expected[] = { "-1.00E-25", "-9.99E-26", "-1.00E-25", "-1.00E-25", "-9.99E-26", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.01E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.00E-25", "-1.01E-25"}; verifyRounding( format, values, expected, roundingModes, descriptions, UPRV_LENGTHOF(values), UPRV_LENGTHOF(roundingModes)); } } void NumberFormatTest::TestZeroScientific10547() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("0.00E0", status); if (!assertSuccess("Format creation", status)) { return; } UnicodeString out; fmt.format(-0.0, out); assertEquals("format", "-0.00E0", out, true); } void NumberFormatTest::verifyRounding( DecimalFormat& format, const double *values, const char * const *expected, const DecimalFormat::ERoundingMode *roundingModes, const char * const *descriptions, int32_t valueSize, int32_t roundingModeSize) { for (int32_t i = 0; i < roundingModeSize; ++i) { format.setRoundingMode(roundingModes[i]); for (int32_t j = 0; j < valueSize; j++) { UnicodeString currentExpected(expected[i * valueSize + j]); currentExpected = currentExpected.unescape(); UnicodeString actual; format.format(values[j], actual); if (currentExpected != actual) { dataerrln("For %s value %f, expected '%s', got '%s'", descriptions[i], values[j], CStr(currentExpected)(), CStr(actual)()); } } } } void NumberFormatTest::TestAccountingCurrency() { UErrorCode status = U_ZERO_ERROR; UNumberFormatStyle style = UNUM_CURRENCY_ACCOUNTING; expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)1234.5, "$1,234.50", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)-1234.5, "($1,234.50)", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)0, "$0.00", TRUE, status); expect(NumberFormat::createInstance("en_US", style, status), (Formattable)(double)-0.2, "($0.20)", TRUE, status); expect(NumberFormat::createInstance("ja_JP", style, status), (Formattable)(double)10000, UnicodeString("\\uFFE510,000").unescape(), TRUE, status); expect(NumberFormat::createInstance("ja_JP", style, status), (Formattable)(double)-1000.5, UnicodeString("(\\uFFE51,000)").unescape(), FALSE, status); expect(NumberFormat::createInstance("de_DE", style, status), (Formattable)(double)-23456.7, UnicodeString("-23.456,70\\u00A0\\u20AC").unescape(), TRUE, status); } // for #5186 void NumberFormatTest::TestEquality() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale("root"), status); if (U_FAILURE(status)) { dataerrln("Fail: can't create DecimalFormatSymbols for root"); return; } UnicodeString pattern("#,##0.###"); DecimalFormat fmtBase(pattern, symbols, status); if (U_FAILURE(status)) { dataerrln("Fail: can't create DecimalFormat using root symbols"); return; } DecimalFormat* fmtClone = (DecimalFormat*)fmtBase.clone(); fmtClone->setFormatWidth(fmtBase.getFormatWidth() + 32); if (*fmtClone == fmtBase) { errln("Error: DecimalFormat == does not distinguish objects that differ only in FormatWidth"); } delete fmtClone; } void NumberFormatTest::TestCurrencyUsage() { double agent = 123.567; UErrorCode status; DecimalFormat *fmt; // compare the Currency and Currency Cash Digits // Note that as of CLDR 26: // * TWD and PKR switched from 0 decimals to 2; ISK still has 0, so change test to that // * CAD rounds to .05 in cash mode only // 1st time for getter/setter, 2nd time for factory method Locale enUS_ISK("en_US@currency=ISK"); for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_ISK, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=ISK/CURRENCY", status, TRUE) == FALSE) { continue; } UnicodeString original; fmt->format(agent,original); assertEquals("Test Currency Usage 1", u"ISK\u00A0124", original); // test the getter here UCurrencyUsage curUsage = fmt->getCurrencyUsage(); assertEquals("Test usage getter - standard", (int32_t)curUsage, (int32_t)UCURR_USAGE_STANDARD); fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_ISK, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=ISK/CASH", status, TRUE) == FALSE) { continue; } } // must be usage = cash UCurrencyUsage curUsage = fmt->getCurrencyUsage(); assertEquals("Test usage getter - cash", (int32_t)curUsage, (int32_t)UCURR_USAGE_CASH); UnicodeString cash_currency; fmt->format(agent,cash_currency); assertEquals("Test Currency Usage 2", u"ISK\u00A0124", cash_currency); delete fmt; } // compare the Currency and Currency Cash Rounding // 1st time for getter/setter, 2nd time for factory method Locale enUS_CAD("en_US@currency=CAD"); for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CURRENCY", status, TRUE) == FALSE) { continue; } UnicodeString original_rounding; fmt->format(agent, original_rounding); assertEquals("Test Currency Usage 3", u"CA$123.57", original_rounding); fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CASH", status, TRUE) == FALSE) { continue; } } UnicodeString cash_rounding_currency; fmt->format(agent, cash_rounding_currency); assertEquals("Test Currency Usage 4", u"CA$123.55", cash_rounding_currency); delete fmt; } // Test the currency change // 1st time for getter/setter, 2nd time for factory method const UChar CUR_PKR[] = {0x50, 0x4B, 0x52, 0}; for(int i=0; i<2; i++){ status = U_ZERO_ERROR; if(i == 0){ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CURRENCY", status, TRUE) == FALSE) { continue; } fmt->setCurrencyUsage(UCURR_USAGE_CASH, &status); }else{ fmt = (DecimalFormat *) NumberFormat::createInstance(enUS_CAD, UNUM_CASH_CURRENCY, status); if (assertSuccess("en_US@currency=CAD/CASH", status, TRUE) == FALSE) { continue; } } UnicodeString cur_original; fmt->setCurrencyUsage(UCURR_USAGE_STANDARD, &status); fmt->format(agent, cur_original); assertEquals("Test Currency Usage 5", u"CA$123.57", cur_original); fmt->setCurrency(CUR_PKR, status); assertSuccess("Set currency to PKR", status); UnicodeString PKR_changed; fmt->format(agent, PKR_changed); assertEquals("Test Currency Usage 6", u"PKR\u00A0123.57", PKR_changed); delete fmt; } } // Check the constant MAX_INT64_IN_DOUBLE. // The value should convert to a double with no loss of precision. // A failure may indicate a platform with a different double format, requiring // a revision to the constant. // // Note that this is actually hard to test, because the language standard gives // compilers considerable flexibility to do unexpected things with rounding and // with overflow in simple int to/from float conversions. Some compilers will completely optimize // away a simple round-trip conversion from int64_t -> double -> int64_t. void NumberFormatTest::TestDoubleLimit11439() { char buf[50]; for (int64_t num = MAX_INT64_IN_DOUBLE-10; num<=MAX_INT64_IN_DOUBLE; num++) { sprintf(buf, "%lld", (long long)num); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast<int64_t>(fNum); if (num != rtNum) { errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); return; } } for (int64_t num = -MAX_INT64_IN_DOUBLE+10; num>=-MAX_INT64_IN_DOUBLE; num--) { sprintf(buf, "%lld", (long long)num); double fNum = 0.0; sscanf(buf, "%lf", &fNum); int64_t rtNum = static_cast<int64_t>(fNum); if (num != rtNum) { errln("%s:%d MAX_INT64_IN_DOUBLE test, %lld did not round trip. Got %lld", __FILE__, __LINE__, (long long)num, (long long)rtNum); return; } } } void NumberFormatTest::TestGetAffixes() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en_US", status); UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00 %\\u00a4\\u00a4"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } UnicodeString affixStr; assertEquals("", "US dollars ", fmt.getPositivePrefix(affixStr)); assertEquals("", " %USD", fmt.getPositiveSuffix(affixStr)); assertEquals("", "-US dollars ", fmt.getNegativePrefix(affixStr)); assertEquals("", " %USD", fmt.getNegativeSuffix(affixStr)); // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix(someAffix)); assertTrue("", fmt != fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString someAffix; fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix(someAffix)); assertTrue("", fmt != fmtCopy); } fmt.setPositivePrefix("Don't"); fmt.setPositiveSuffix("do"); UnicodeString someAffix("be''eet\\u00a4\\u00a4\\u00a4 it."); someAffix = someAffix.unescape(); fmt.setNegativePrefix(someAffix); fmt.setNegativeSuffix("%"); assertEquals("", "Don't", fmt.getPositivePrefix(affixStr)); assertEquals("", "do", fmt.getPositiveSuffix(affixStr)); assertEquals("", someAffix, fmt.getNegativePrefix(affixStr)); assertEquals("", "%", fmt.getNegativeSuffix(affixStr)); } void NumberFormatTest::TestToPatternScientific11648() { UErrorCode status = U_ZERO_ERROR; Locale en("en"); DecimalFormatSymbols sym(en, status); DecimalFormat fmt("0.00", sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } fmt.setScientificNotation(TRUE); UnicodeString pattern; assertEquals("", "0.00E0", fmt.toPattern(pattern)); DecimalFormat fmt2(pattern, sym, status); assertSuccess("", status); } void NumberFormatTest::TestBenchmark() { /* UErrorCode status = U_ZERO_ERROR; Locale en("en"); DecimalFormatSymbols sym(en, status); DecimalFormat fmt("0.0000000", new DecimalFormatSymbols(sym), status); // DecimalFormat fmt("0.00000E0", new DecimalFormatSymbols(sym), status); // DecimalFormat fmt("0", new DecimalFormatSymbols(sym), status); FieldPosition fpos(FieldPosition::DONT_CARE); clock_t start = clock(); for (int32_t i = 0; i < 1000000; ++i) { UnicodeString append; fmt.format(3.0, append, fpos, status); // fmt.format(4.6692016, append, fpos, status); // fmt.format(1234567.8901, append, fpos, status); // fmt.format(2.99792458E8, append, fpos, status); // fmt.format(31, append); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); UErrorCode status = U_ZERO_ERROR; MessageFormat fmt("{0, plural, one {I have # friend.} other {I have # friends.}}", status); FieldPosition fpos(FieldPosition::DONT_CARE); Formattable one(1.0); Formattable three(3.0); clock_t start = clock(); for (int32_t i = 0; i < 500000; ++i) { UnicodeString append; fmt.format(&one, 1, append, fpos, status); UnicodeString append2; fmt.format(&three, 1, append2, fpos, status); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); UErrorCode status = U_ZERO_ERROR; Locale en("en"); Measure measureC(23, MeasureUnit::createCelsius(status), status); MeasureFormat fmt(en, UMEASFMT_WIDTH_WIDE, status); FieldPosition fpos(FieldPosition::DONT_CARE); clock_t start = clock(); for (int32_t i = 0; i < 1000000; ++i) { UnicodeString appendTo; fmt.formatMeasures( &measureC, 1, appendTo, fpos, status); } errln("Took %f", (double) (clock() - start) / CLOCKS_PER_SEC); assertSuccess("", status); */ } void NumberFormatTest::TestFractionalDigitsForCurrency() { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt(NumberFormat::createCurrencyInstance("en", status)); if (U_FAILURE(status)) { dataerrln("Error creating NumberFormat - %s", u_errorName(status)); return; } UChar JPY[] = {0x4A, 0x50, 0x59, 0x0}; fmt->setCurrency(JPY, status); if (!assertSuccess("", status)) { return; } assertEquals("", 0, fmt->getMaximumFractionDigits()); } void NumberFormatTest::TestFormatCurrencyPlural() { UErrorCode status = U_ZERO_ERROR; Locale locale = Locale::createCanonical("en_US"); NumberFormat *fmt = NumberFormat::createInstance(locale, UNUM_CURRENCY_PLURAL, status); if (U_FAILURE(status)) { dataerrln("Error creating NumberFormat - %s", u_errorName(status)); return; } UnicodeString formattedNum; fmt->format(11234.567, formattedNum, NULL, status); assertEquals("", "11,234.57 US dollars", formattedNum); delete fmt; } void NumberFormatTest::TestCtorApplyPatternDifference() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en_US", status); UnicodeString pattern("\\u00a40"); DecimalFormat fmt(pattern.unescape(), sym, status); if (U_FAILURE(status)) { dataerrln("Error creating DecimalFormat - %s", u_errorName(status)); return; } UnicodeString result; assertEquals( "ctor favors precision of currency", "$5.00", fmt.format((double)5, result)); result.remove(); fmt.applyPattern(pattern.unescape(), status); assertEquals( "applyPattern favors precision of pattern", "$5", fmt.format((double)5, result)); } void NumberFormatTest::Test11868() { double posAmt = 34.567; double negAmt = -9876.543; Locale selectedLocale("en_US"); UErrorCode status = U_ZERO_ERROR; UnicodeString result; FieldPosition fpCurr(UNUM_CURRENCY_FIELD); LocalPointer<NumberFormat> fmt( NumberFormat::createInstance( selectedLocale, UNUM_CURRENCY_PLURAL, status)); if (!assertSuccess("Format creation", status)) { return; } fmt->format(posAmt, result, fpCurr, status); assertEquals("", "34.57 US dollars", result); assertEquals("begin index", 6, fpCurr.getBeginIndex()); assertEquals("end index", 16, fpCurr.getEndIndex()); // Test field position iterator { NumberFormatTest_Attributes attributes[] = { {UNUM_INTEGER_FIELD, 0, 2}, {UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3}, {UNUM_FRACTION_FIELD, 3, 5}, {UNUM_CURRENCY_FIELD, 6, 16}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt->format(posAmt, result, &iter, status); assertEquals("", "34.57 US dollars", result); verifyFieldPositionIterator(attributes, iter); } result.remove(); fmt->format(negAmt, result, fpCurr, status); assertEquals("", "-9,876.54 US dollars", result); assertEquals("begin index", 10, fpCurr.getBeginIndex()); assertEquals("end index", 20, fpCurr.getEndIndex()); // Test field position iterator { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_GROUPING_SEPARATOR_FIELD, 2, 3}, {UNUM_INTEGER_FIELD, 1, 6}, {UNUM_DECIMAL_SEPARATOR_FIELD, 6, 7}, {UNUM_FRACTION_FIELD, 7, 9}, {UNUM_CURRENCY_FIELD, 10, 20}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt->format(negAmt, result, &iter, status); assertEquals("", "-9,876.54 US dollars", result); verifyFieldPositionIterator(attributes, iter); } } void NumberFormatTest::Test10727_RoundingZero() { IcuTestErrorCode status(*this, "Test10727_RoundingZero"); DecimalQuantity dq; dq.setToDouble(-0.0); assertTrue("", dq.isNegative()); dq.roundToMagnitude(0, UNUM_ROUND_HALFEVEN, status); assertTrue("", dq.isNegative()); } void NumberFormatTest::Test11739_ParseLongCurrency() { IcuTestErrorCode status(*this, "Test11739_ParseLongCurrency"); LocalPointer<NumberFormat> nf(NumberFormat::createCurrencyInstance("sr_BA", status)); if (status.errDataIfFailureAndReset()) { return; } ((DecimalFormat*) nf.getAlias())->applyPattern(u"#,##0.0 ¤¤¤", status); ParsePosition ppos(0); LocalPointer<CurrencyAmount> result(nf->parseCurrency(u"1.500 амерички долар", ppos)); assertEquals("Should parse to 1500 USD", -1, ppos.getErrorIndex()); assertEquals("Should parse to 1500 USD", 1500LL, result->getNumber().getInt64(status)); assertEquals("Should parse to 1500 USD", u"USD", result->getISOCurrency()); } void NumberFormatTest::Test13035_MultiCodePointPaddingInPattern() { IcuTestErrorCode status(*this, "Test13035_MultiCodePointPaddingInPattern"); DecimalFormat df(u"a*'நி'###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } UnicodeString result; df.format(12, result.remove()); // TODO(13034): Re-enable this test when support is added in ICU4C. //assertEquals("Multi-codepoint padding should not be split", u"aநிநி12b", result); df = DecimalFormat(u"a*\U0001F601###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } result = df.format(12, result.remove()); assertEquals("Single-codepoint padding should not be split", u"a\U0001F601\U0001F60112b", result, true); df = DecimalFormat(u"a*''###0b", status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } result = df.format(12, result.remove()); assertEquals("Quote should be escapable in padding syntax", "a''12b", result, true); } void NumberFormatTest::Test13737_ParseScientificStrict() { IcuTestErrorCode status(*this, "Test13737_ParseScientificStrict"); LocalPointer<NumberFormat> df(NumberFormat::createScientificInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) {return;} df->setLenient(FALSE); // Parse Test expect(*df, u"1.2", 1.2); } void NumberFormatTest::Test11376_getAndSetPositivePrefix() { { const UChar USD[] = {0x55, 0x53, 0x44, 0x0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createCurrencyInstance("en", status)); if (!assertSuccess("", status)) { return; } DecimalFormat *dfmt = (DecimalFormat *) fmt.getAlias(); dfmt->setCurrency(USD); UnicodeString result; // This line should be a no-op. I am setting the positive prefix // to be the same thing it was before. dfmt->setPositivePrefix(dfmt->getPositivePrefix(result)); UnicodeString appendTo; assertEquals("", "$3.78", dfmt->format(3.78, appendTo, status)); assertSuccess("", status); } { const UChar USD[] = {0x55, 0x53, 0x44, 0x0}; UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> fmt( NumberFormat::createInstance("en", UNUM_CURRENCY_PLURAL, status)); if (!assertSuccess("", status)) { return; } DecimalFormat *dfmt = (DecimalFormat *) fmt.getAlias(); UnicodeString result; assertEquals("", u" (unknown currency)", dfmt->getPositiveSuffix(result)); dfmt->setCurrency(USD); // getPositiveSuffix() always returns the suffix for the // "other" plural category assertEquals("", " US dollars", dfmt->getPositiveSuffix(result)); UnicodeString appendTo; assertEquals("", "3.78 US dollars", dfmt->format(3.78, appendTo, status)); assertEquals("", " US dollars", dfmt->getPositiveSuffix(result)); dfmt->setPositiveSuffix("booya"); appendTo.remove(); assertEquals("", "3.78booya", dfmt->format(3.78, appendTo, status)); assertEquals("", "booya", dfmt->getPositiveSuffix(result)); } } void NumberFormatTest::Test11475_signRecognition() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym("en", status); UnicodeString result; { DecimalFormat fmt("+0.00", sym, status); if (!assertSuccess("", status)) { return; } NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_INTEGER_FIELD, 1, 2}, {UNUM_DECIMAL_SEPARATOR_FIELD, 2, 3}, {UNUM_FRACTION_FIELD, 3, 5}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(2.3, result, &iter, status); assertEquals("", "+2.30", result); verifyFieldPositionIterator(attributes, iter); } { DecimalFormat fmt("++0.00+;-(#)--", sym, status); if (!assertSuccess("", status)) { return; } { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 2}, {UNUM_INTEGER_FIELD, 2, 3}, {UNUM_DECIMAL_SEPARATOR_FIELD, 3, 4}, {UNUM_FRACTION_FIELD, 4, 6}, {UNUM_SIGN_FIELD, 6, 7}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(2.3, result, &iter, status); assertEquals("", "++2.30+", result); verifyFieldPositionIterator(attributes, iter); } { NumberFormatTest_Attributes attributes[] = { {UNUM_SIGN_FIELD, 0, 1}, {UNUM_INTEGER_FIELD, 2, 3}, {UNUM_DECIMAL_SEPARATOR_FIELD, 3, 4}, {UNUM_FRACTION_FIELD, 4, 6}, {UNUM_SIGN_FIELD, 7, 9}, {0, -1, 0}}; UnicodeString result; FieldPositionIterator iter; fmt.format(-2.3, result, &iter, status); assertEquals("", "-(2.30)--", result); verifyFieldPositionIterator(attributes, iter); } } } void NumberFormatTest::Test11640_getAffixes() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols("en_US", status); if (!assertSuccess("", status)) { return; } UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00 %\\u00a4\\u00a4"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, symbols, status); if (!assertSuccess("", status)) { return; } UnicodeString affixStr; assertEquals("", "US dollars ", fmt.getPositivePrefix(affixStr)); assertEquals("", " %USD", fmt.getPositiveSuffix(affixStr)); assertEquals("", "-US dollars ", fmt.getNegativePrefix(affixStr)); assertEquals("", " %USD", fmt.getNegativeSuffix(affixStr)); } void NumberFormatTest::Test11649_toPatternWithMultiCurrency() { UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00"); pattern = pattern.unescape(); UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt(pattern, status); if (!assertSuccess("", status)) { return; } static UChar USD[] = {0x55, 0x53, 0x44, 0x0}; fmt.setCurrency(USD); UnicodeString appendTo; assertEquals("", "US dollars 12.34", fmt.format(12.34, appendTo)); UnicodeString topattern; fmt.toPattern(topattern); DecimalFormat fmt2(topattern, status); if (!assertSuccess("", status)) { return; } fmt2.setCurrency(USD); appendTo.remove(); assertEquals("", "US dollars 12.34", fmt2.format(12.34, appendTo)); } void NumberFormatTest::Test13327_numberingSystemBufferOverflow() { UErrorCode status = U_ZERO_ERROR; for (int runId = 0; runId < 2; runId++) { // Construct a locale string with a very long "numbers" value. // The first time, make the value length exactly equal to ULOC_KEYWORDS_CAPACITY. // The second time, make it exceed ULOC_KEYWORDS_CAPACITY. int extraLength = (runId == 0) ? 0 : 5; CharString localeId("en@numbers=", status); for (int i = 0; i < ULOC_KEYWORDS_CAPACITY + extraLength; i++) { localeId.append('x', status); } assertSuccess("Constructing locale string", status); Locale locale(localeId.data()); LocalPointer<NumberingSystem> ns(NumberingSystem::createInstance(locale, status)); assertFalse("Should not be null", ns.getAlias() == nullptr); assertSuccess("Should create with no error", status); } } void NumberFormatTest::Test13391_chakmaParsing() { UErrorCode status = U_ZERO_ERROR; LocalPointer<DecimalFormat> df(dynamic_cast<DecimalFormat*>( NumberFormat::createInstance(Locale("ccp"), status))); if (df == nullptr) { dataerrln("%s %d Chakma df is null", __FILE__, __LINE__); return; } const UChar* expected = u"\U00011137\U00011138,\U00011139\U0001113A\U0001113B"; UnicodeString actual; df->format(12345, actual, status); assertSuccess("Should not fail when formatting in ccp", status); assertEquals("Should produce expected output in ccp", expected, actual); Formattable result; df->parse(expected, result, status); assertSuccess("Should not fail when parsing in ccp", status); assertEquals("Should parse to 12345 in ccp", 12345, result); const UChar* expectedScientific = u"\U00011137.\U00011139E\U00011138"; UnicodeString actualScientific; df.adoptInstead(static_cast<DecimalFormat*>( NumberFormat::createScientificInstance(Locale("ccp"), status))); df->format(130, actualScientific, status); assertSuccess("Should not fail when formatting scientific in ccp", status); assertEquals("Should produce expected scientific output in ccp", expectedScientific, actualScientific); Formattable resultScientific; df->parse(expectedScientific, resultScientific, status); assertSuccess("Should not fail when parsing scientific in ccp", status); assertEquals("Should parse scientific to 130 in ccp", 130, resultScientific); } void NumberFormatTest::verifyFieldPositionIterator( NumberFormatTest_Attributes *expected, FieldPositionIterator &iter) { int32_t idx = 0; FieldPosition fp; while (iter.next(fp)) { if (expected[idx].spos == -1) { errln("Iterator should have ended. got %d", fp.getField()); return; } assertEquals("id", expected[idx].id, fp.getField()); assertEquals("start", expected[idx].spos, fp.getBeginIndex()); assertEquals("end", expected[idx].epos, fp.getEndIndex()); ++idx; } if (expected[idx].spos != -1) { errln("Premature end of iterator. expected %d", expected[idx].id); } } void NumberFormatTest::Test11735_ExceptionIssue() { IcuTestErrorCode status(*this, "Test11735_ExceptionIssue"); Locale enLocale("en"); DecimalFormatSymbols symbols(enLocale, status); if (status.isSuccess()) { DecimalFormat fmt("0", symbols, status); assertSuccess("Fail: Construct DecimalFormat formatter", status, true, __FILE__, __LINE__); ParsePosition ppos(0); fmt.parseCurrency("53.45", ppos); // NPE thrown here in ICU4J. assertEquals("Issue11735 ppos", 0, ppos.getIndex()); } } void NumberFormatTest::Test11035_FormatCurrencyAmount() { UErrorCode status = U_ZERO_ERROR; double amount = 12345.67; const char16_t* expected = u"12,345$67 ​"; // Test two ways to set a currency via API Locale loc1 = Locale("pt_PT"); LocalPointer<NumberFormat> fmt1(NumberFormat::createCurrencyInstance("loc1", status), status); if (U_FAILURE(status)) { dataerrln("%s %d NumberFormat instance fmt1 is null", __FILE__, __LINE__); return; } fmt1->setCurrency(u"PTE", status); assertSuccess("Setting currency on fmt1", status); UnicodeString actualSetCurrency; fmt1->format(amount, actualSetCurrency); Locale loc2 = Locale("pt_PT@currency=PTE"); LocalPointer<NumberFormat> fmt2(NumberFormat::createCurrencyInstance(loc2, status)); assertSuccess("Creating fmt2", status); UnicodeString actualLocaleString; fmt2->format(amount, actualLocaleString); // TODO: The following test will fail until DecimalFormat wraps NumberFormatter. if (!logKnownIssue("13574")) { assertEquals("Custom Currency Pattern, Set Currency", expected, actualSetCurrency); } } void NumberFormatTest::Test11318_DoubleConversion() { IcuTestErrorCode status(*this, "Test11318_DoubleConversion"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (U_FAILURE(status)) { dataerrln("%s %d Error in NumberFormat instance creation", __FILE__, __LINE__); return; } nf->setMaximumFractionDigits(40); nf->setMaximumIntegerDigits(40); UnicodeString appendTo; nf->format(999999999999999.9, appendTo); assertEquals("Should render all digits", u"999,999,999,999,999.9", appendTo); } void NumberFormatTest::TestParsePercentRegression() { IcuTestErrorCode status(*this, "TestParsePercentRegression"); LocalPointer<DecimalFormat> df1((DecimalFormat*) NumberFormat::createInstance("en", status), status); LocalPointer<DecimalFormat> df2((DecimalFormat*) NumberFormat::createPercentInstance("en", status), status); if (status.isFailure()) {return; } df1->setLenient(TRUE); df2->setLenient(TRUE); { ParsePosition ppos; Formattable result; df1->parse("50%", result, ppos); assertEquals("df1 should accept a number but not the percent sign", 2, ppos.getIndex()); assertEquals("df1 should return the number as 50", 50.0, result.getDouble(status)); } { ParsePosition ppos; Formattable result; df2->parse("50%", result, ppos); assertEquals("df2 should accept the percent sign", 3, ppos.getIndex()); assertEquals("df2 should return the number as 0.5", 0.5, result.getDouble(status)); } { ParsePosition ppos; Formattable result; df2->parse("50", result, ppos); assertEquals("df2 should return the number as 0.5 even though the percent sign is missing", 0.5, result.getDouble(status)); } } void NumberFormatTest::TestMultiplierWithScale() { IcuTestErrorCode status(*this, "TestMultiplierWithScale"); // Test magnitude combined with multiplier, as shown in API docs DecimalFormat df("0", {"en", status}, status); if (status.isSuccess()) { df.setMultiplier(5); df.setMultiplierScale(-1); expect2(df, 100, u"50"); // round-trip test } } void NumberFormatTest::TestFastFormatInt32() { IcuTestErrorCode status(*this, "TestFastFormatInt32"); // The two simplest formatters, old API and new API. // Old API should use the fastpath for ints. LocalizedNumberFormatter lnf = NumberFormatter::withLocale("en"); LocalPointer<NumberFormat> df(NumberFormat::createInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) {return;} double nums[] = { 0.0, -0.0, NAN, INFINITY, 0.1, 1.0, 1.1, 2.0, 3.0, 9.0, 10.0, 99.0, 100.0, 999.0, 1000.0, 9999.0, 10000.0, 99999.0, 100000.0, 999999.0, 1000000.0, static_cast<double>(INT32_MAX) - 1, static_cast<double>(INT32_MAX), static_cast<double>(INT32_MAX) + 1, static_cast<double>(INT32_MIN) - 1, static_cast<double>(INT32_MIN), static_cast<double>(INT32_MIN) + 1}; for (auto num : nums) { UnicodeString expected = lnf.formatDouble(num, status).toString(); UnicodeString actual; df->format(num, actual); assertEquals(UnicodeString("d = ") + num, expected, actual); } } void NumberFormatTest::Test11646_Equality() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getEnglish(), status); UnicodeString pattern(u"\u00a4\u00a4\u00a4 0.00 %\u00a4\u00a4"); DecimalFormat fmt(pattern, symbols, status); if (!assertSuccess("", status)) return; // Test equality with affixes. set affix methods can't capture special // characters which is why equality should fail. { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString positivePrefix; fmtCopy.setPositivePrefix(fmtCopy.getPositivePrefix(positivePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy = DecimalFormat(fmt); assertTrue("", fmt == fmtCopy); UnicodeString positivePrefix; fmtCopy.setPositiveSuffix(fmtCopy.getPositiveSuffix(positivePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString negativePrefix; fmtCopy.setNegativePrefix(fmtCopy.getNegativePrefix(negativePrefix)); assertFalse("", fmt == fmtCopy); } { DecimalFormat fmtCopy(fmt); assertTrue("", fmt == fmtCopy); UnicodeString negativePrefix; fmtCopy.setNegativeSuffix(fmtCopy.getNegativeSuffix(negativePrefix)); assertFalse("", fmt == fmtCopy); } } void NumberFormatTest::TestParseNaN() { IcuTestErrorCode status(*this, "TestParseNaN"); DecimalFormat df("0", { "en", status }, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } Formattable parseResult; df.parse(u"NaN", parseResult, status); assertEquals("NaN should parse successfully", NAN, parseResult.getDouble()); assertFalse("Result NaN should be positive", std::signbit(parseResult.getDouble())); UnicodeString formatResult; df.format(parseResult.getDouble(), formatResult); assertEquals("NaN should round-trip", u"NaN", formatResult); } void NumberFormatTest::Test11897_LocalizedPatternSeparator() { IcuTestErrorCode status(*this, "Test11897_LocalizedPatternSeparator"); // In a locale with a different <list> symbol, like arabic, // kPatternSeparatorSymbol should still be ';' { DecimalFormatSymbols dfs("ar", status); assertEquals("pattern separator symbol should be ;", u";", dfs.getSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol)); } // However, the custom symbol should be used in localized notation // when set manually via API { DecimalFormatSymbols dfs("en", status); dfs.setSymbol(DecimalFormatSymbols::kPatternSeparatorSymbol, u"!", FALSE); DecimalFormat df(u"0", dfs, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } df.applyPattern("a0;b0", status); // should not throw UnicodeString result; assertEquals("should apply the normal pattern", df.getNegativePrefix(result.remove()), "b"); df.applyLocalizedPattern(u"c0!d0", status); // should not throw assertEquals("should apply the localized pattern", df.getNegativePrefix(result.remove()), "d"); } } void NumberFormatTest::Test13055_PercentageRounding() { IcuTestErrorCode status(*this, "PercentageRounding"); UnicodeString actual; LocalPointer<NumberFormat>pFormat(NumberFormat::createPercentInstance("en_US", status)); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } pFormat->setMaximumFractionDigits(0); pFormat->setRoundingMode(DecimalFormat::kRoundHalfEven); pFormat->format(2.155, actual); assertEquals("Should round percent toward even number", "216%", actual); } void NumberFormatTest::Test11839() { IcuTestErrorCode errorCode(*this, "Test11839"); // Ticket #11839: DecimalFormat does not respect custom plus sign LocalPointer<DecimalFormatSymbols> dfs(new DecimalFormatSymbols(Locale::getEnglish(), errorCode), errorCode); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } dfs->setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u"a∸"); dfs->setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u"b∔"); // ∔ U+2214 DOT PLUS DecimalFormat df(u"0.00+;0.00-", dfs.orphan(), errorCode); UnicodeString result; df.format(-1.234, result, errorCode); assertEquals("Locale-specific minus sign should be used", u"1.23a∸", result); df.format(1.234, result.remove(), errorCode); assertEquals("Locale-specific plus sign should be used", u"1.23b∔", result); // Test round-trip with parse expect2(df, -456, u"456.00a∸"); expect2(df, 456, u"456.00b∔"); } void NumberFormatTest::Test10354() { IcuTestErrorCode errorCode(*this, "Test10354"); // Ticket #10354: invalid FieldPositionIterator when formatting with empty NaN DecimalFormatSymbols dfs(errorCode); UnicodeString empty; dfs.setSymbol(DecimalFormatSymbols::kNaNSymbol, empty); DecimalFormat df(errorCode); df.setDecimalFormatSymbols(dfs); UnicodeString result; FieldPositionIterator positions; df.format(NAN, result, &positions, errorCode); errorCode.errIfFailureAndReset("DecimalFormat.format(NAN, FieldPositionIterator) failed"); FieldPosition fp; while (positions.next(fp)) { // Should not loop forever } } void NumberFormatTest::Test11645_ApplyPatternEquality() { IcuTestErrorCode status(*this, "Test11645_ApplyPatternEquality"); const char16_t* pattern = u"#,##0.0#"; LocalPointer<DecimalFormat> fmt((DecimalFormat*) NumberFormat::createInstance(status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } fmt->applyPattern(pattern, status); LocalPointer<DecimalFormat> fmtCopy; static const int32_t newMultiplier = 37; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getMultiplier() == newMultiplier); fmtCopy->setMultiplier(newMultiplier); assertEquals("Value after setter", fmtCopy->getMultiplier(), newMultiplier); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getMultiplier(), newMultiplier); assertFalse("multiplier", *fmt == *fmtCopy); static const NumberFormat::ERoundingMode newRoundingMode = NumberFormat::ERoundingMode::kRoundCeiling; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getRoundingMode() == newRoundingMode); fmtCopy->setRoundingMode(newRoundingMode); assertEquals("Value after setter", fmtCopy->getRoundingMode(), newRoundingMode); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getRoundingMode(), newRoundingMode); assertFalse("roundingMode", *fmt == *fmtCopy); static const char16_t *const newCurrency = u"EAT"; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getCurrency() == newCurrency); fmtCopy->setCurrency(newCurrency); assertEquals("Value after setter", fmtCopy->getCurrency(), newCurrency); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getCurrency(), newCurrency); assertFalse("currency", *fmt == *fmtCopy); static const UCurrencyUsage newCurrencyUsage = UCurrencyUsage::UCURR_USAGE_CASH; fmtCopy.adoptInstead(new DecimalFormat(*fmt)); assertFalse("Value before setter", fmtCopy->getCurrencyUsage() == newCurrencyUsage); fmtCopy->setCurrencyUsage(newCurrencyUsage, status); assertEquals("Value after setter", fmtCopy->getCurrencyUsage(), newCurrencyUsage); fmtCopy->applyPattern(pattern, status); assertEquals("Value after applyPattern", fmtCopy->getCurrencyUsage(), newCurrencyUsage); assertFalse("currencyUsage", *fmt == *fmtCopy); } void NumberFormatTest::Test12567() { IcuTestErrorCode errorCode(*this, "Test12567"); // Ticket #12567: DecimalFormat.equals() may not be symmetric LocalPointer<DecimalFormat> df1((DecimalFormat *) NumberFormat::createInstance(Locale::getUS(), UNUM_CURRENCY, errorCode)); LocalPointer<DecimalFormat> df2((DecimalFormat *) NumberFormat::createInstance(Locale::getUS(), UNUM_DECIMAL, errorCode)); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } // NOTE: CurrencyPluralInfo equality not tested in C++ because its operator== is not defined. df1->applyPattern(u"0.00", errorCode); df2->applyPattern(u"0.00", errorCode); assertTrue("df1 == df2", *df1 == *df2); assertTrue("df2 == df1", *df2 == *df1); df2->setPositivePrefix(u"abc"); assertTrue("df1 != df2", *df1 != *df2); assertTrue("df2 != df1", *df2 != *df1); } void NumberFormatTest::Test11626_CustomizeCurrencyPluralInfo() { IcuTestErrorCode errorCode(*this, "Test11626_CustomizeCurrencyPluralInfo"); // Ticket #11626: No unit test demonstrating how to use CurrencyPluralInfo to // change formatting spelled out currencies // Use locale sr because it has interesting plural rules. Locale locale("sr"); LocalPointer<DecimalFormatSymbols> symbols(new DecimalFormatSymbols(locale, errorCode), errorCode); CurrencyPluralInfo info(locale, errorCode); if (!assertSuccess("", errorCode, true, __FILE__, __LINE__)) { return; } info.setCurrencyPluralPattern(u"one", u"0 qwerty", errorCode); info.setCurrencyPluralPattern(u"few", u"0 dvorak", errorCode); DecimalFormat df(u"#", symbols.orphan(), UNUM_CURRENCY_PLURAL, errorCode); df.setCurrencyPluralInfo(info); df.setCurrency(u"USD"); df.setMaximumFractionDigits(0); UnicodeString result; assertEquals("Plural one", u"1 qwerty", df.format(1, result, errorCode)); assertEquals("Plural few", u"3 dvorak", df.format(3, result.remove(), errorCode)); assertEquals("Plural other", u"99 америчких долара", df.format(99, result.remove(), errorCode)); info.setPluralRules(u"few: n is 1; one: n in 2..4", errorCode); df.setCurrencyPluralInfo(info); assertEquals("Plural one", u"1 dvorak", df.format(1, result.remove(), errorCode)); assertEquals("Plural few", u"3 qwerty", df.format(3, result.remove(), errorCode)); assertEquals("Plural other", u"99 америчких долара", df.format(99, result.remove(), errorCode)); } void NumberFormatTest::Test20073_StrictPercentParseErrorIndex() { IcuTestErrorCode status(*this, "Test20073_StrictPercentParseErrorIndex"); ParsePosition parsePosition(0); DecimalFormat df(u"0%", {"en-us", status}, status); if (U_FAILURE(status)) { dataerrln("Unable to create DecimalFormat instance."); return; } df.setLenient(FALSE); Formattable result; df.parse(u"%2%", result, parsePosition); assertEquals("", 0, parsePosition.getIndex()); assertEquals("", 0, parsePosition.getErrorIndex()); } void NumberFormatTest::Test13056_GroupingSize() { UErrorCode status = U_ZERO_ERROR; DecimalFormat df(u"#,##0", status); if (!assertSuccess("", status)) return; assertEquals("Primary grouping should return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should return 0", 0, df.getSecondaryGroupingSize()); df.setSecondaryGroupingSize(3); assertEquals("Primary grouping should still return 3", 3, df.getGroupingSize()); assertEquals("Secondary grouping should round-trip", 3, df.getSecondaryGroupingSize()); df.setGroupingSize(4); assertEquals("Primary grouping should return 4", 4, df.getGroupingSize()); assertEquals("Secondary should remember explicit setting and return 3", 3, df.getSecondaryGroupingSize()); } void NumberFormatTest::Test11025_CurrencyPadding() { UErrorCode status = U_ZERO_ERROR; UnicodeString pattern(u"¤¤ **####0.00"); DecimalFormatSymbols sym(Locale::getFrance(), status); if (!assertSuccess("", status)) return; DecimalFormat fmt(pattern, sym, status); if (!assertSuccess("", status)) return; UnicodeString result; fmt.format(433.0, result); assertEquals("Number should be padded to 11 characters", "EUR *433,00", result); } void NumberFormatTest::Test11648_ExpDecFormatMalPattern() { UErrorCode status = U_ZERO_ERROR; DecimalFormat fmt("0.00", {"en", status}, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } fmt.setScientificNotation(TRUE); UnicodeString pattern; assertEquals("A valid scientific notation pattern should be produced", "0.00E0", fmt.toPattern(pattern)); DecimalFormat fmt2(pattern, status); assertSuccess("", status); } void NumberFormatTest::Test11649_DecFmtCurrencies() { IcuTestErrorCode status(*this, "Test11649_DecFmtCurrencies"); UnicodeString pattern("\\u00a4\\u00a4\\u00a4 0.00"); pattern = pattern.unescape(); DecimalFormat fmt(pattern, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } static const UChar USD[] = u"USD"; fmt.setCurrency(USD); UnicodeString appendTo; assertEquals("", "US dollars 12.34", fmt.format(12.34, appendTo)); UnicodeString topattern; assertEquals("", pattern, fmt.toPattern(topattern)); DecimalFormat fmt2(topattern, status); fmt2.setCurrency(USD); appendTo.remove(); assertEquals("", "US dollars 12.34", fmt2.format(12.34, appendTo)); } void NumberFormatTest::Test13148_ParseGroupingSeparators() { IcuTestErrorCode status(*this, "Test13148"); LocalPointer<DecimalFormat> fmt( (DecimalFormat*)NumberFormat::createInstance("en-ZA", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } DecimalFormatSymbols symbols = *fmt->getDecimalFormatSymbols(); symbols.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u'.'); symbols.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u','); fmt->setDecimalFormatSymbols(symbols); Formattable number; fmt->parse(u"300,000", number, status); assertEquals("Should parse as 300000", 300000LL, number.getInt64(status)); } void NumberFormatTest::Test12753_PatternDecimalPoint() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols symbols(Locale::getUS(), status); symbols.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u"*", false); DecimalFormat df(u"0.00", symbols, status); if (!assertSuccess("", status)) return; df.setDecimalPatternMatchRequired(true); Formattable result; df.parse(u"123",result, status); assertEquals("Parsing integer succeeded even though setDecimalPatternMatchRequired was set", U_INVALID_FORMAT_ERROR, status); } void NumberFormatTest::Test11647_PatternCurrencySymbols() { UErrorCode status = U_ZERO_ERROR; DecimalFormat df(status); df.applyPattern(u"¤¤¤¤#", status); if (!assertSuccess("", status)) return; UnicodeString actual; df.format(123, actual); assertEquals("Should replace 4 currency signs with U+FFFD", u"\uFFFD123", actual); } void NumberFormatTest::Test11913_BigDecimal() { UErrorCode status = U_ZERO_ERROR; LocalPointer<NumberFormat> df(NumberFormat::createInstance(Locale::getEnglish(), status), status); if (!assertSuccess("", status)) return; UnicodeString result; df->format(StringPiece("1.23456789E400"), result, nullptr, status); assertSuccess("", status); assertEquals("Should format more than 309 digits", u"12,345,678", UnicodeString(result, 0, 10)); assertEquals("Should format more than 309 digits", 534, result.length()); } void NumberFormatTest::Test11020_RoundingInScientificNotation() { UErrorCode status = U_ZERO_ERROR; DecimalFormatSymbols sym(Locale::getFrance(), status); DecimalFormat fmt(u"0.05E0", sym, status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } assertSuccess("", status); UnicodeString result; fmt.format(12301.2, result); assertEquals("Rounding increment should be applied after magnitude scaling", u"1,25E4", result); } void NumberFormatTest::Test11640_TripleCurrencySymbol() { IcuTestErrorCode status(*this, "Test11640_TripleCurrencySymbol"); UnicodeString actual; DecimalFormat dFormat(u"¤¤¤ 0", status); if (U_FAILURE(status)) { dataerrln("Failure creating DecimalFormat %s", u_errorName(status)); return; } dFormat.setCurrency(u"USD"); UnicodeString result; dFormat.getPositivePrefix(result); assertEquals("Triple-currency should give long name on getPositivePrefix", "US dollars ", result); } void NumberFormatTest::Test13763_FieldPositionIteratorOffset() { IcuTestErrorCode status(*this, "Test13763_FieldPositionIteratorOffset"); FieldPositionIterator fpi; UnicodeString result(u"foo\U0001F4FBbar"); // 8 code units LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } nf->format(5142.3, result, &fpi, status); int32_t expected[] = { UNUM_GROUPING_SEPARATOR_FIELD, 9, 10, UNUM_INTEGER_FIELD, 8, 13, UNUM_DECIMAL_SEPARATOR_FIELD, 13, 14, UNUM_FRACTION_FIELD, 14, 15, }; int32_t tupleCount = UPRV_LENGTHOF(expected)/3; expectPositions(fpi, expected, tupleCount, result); } void NumberFormatTest::Test13777_ParseLongNameNonCurrencyMode() { IcuTestErrorCode status(*this, "Test13777_ParseLongNameNonCurrencyMode"); LocalPointer<NumberFormat> df( NumberFormat::createInstance("en-us", UNumberFormatStyle::UNUM_CURRENCY_PLURAL, status), status); if (!assertSuccess("", status, true, __FILE__, __LINE__)) { return; } expect2(*df, 1.5, u"1.50 US dollars"); } void NumberFormatTest::Test13804_EmptyStringsWhenParsing() { IcuTestErrorCode status(*this, "Test13804_EmptyStringsWhenParsing"); DecimalFormatSymbols dfs("en", status); if (status.errIfFailureAndReset()) { return; } dfs.setSymbol(DecimalFormatSymbols::kCurrencySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kZeroDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kOneDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kTwoDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kThreeDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kFourDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kFiveDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kSixDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kSevenDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kEightDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kNineDigitSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kExponentMultiplicationSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kInfinitySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kIntlCurrencySymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMinusSignSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kNaNSymbol, u"", FALSE); dfs.setPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, FALSE, u""); dfs.setPatternForCurrencySpacing(UNUM_CURRENCY_INSERT, TRUE, u""); dfs.setSymbol(DecimalFormatSymbols::kPercentSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kPerMillSymbol, u"", FALSE); dfs.setSymbol(DecimalFormatSymbols::kPlusSignSymbol, u"", FALSE); DecimalFormat df("0", dfs, status); if (status.errIfFailureAndReset()) { return; } df.setGroupingUsed(TRUE); df.setScientificNotation(TRUE); df.setLenient(TRUE); // enable all matchers { UnicodeString result; df.format(0, result); // should not crash or hit infinite loop } const char16_t* samples[] = { u"", u"123", u"$123", u"-", u"+", u"44%", u"1E+2.3" }; for (auto& sample : samples) { logln(UnicodeString(u"Attempting parse on: ") + sample); status.setScope(sample); // We don't care about the results, only that we don't crash and don't loop. Formattable result; ParsePosition ppos(0); df.parse(sample, result, ppos); ppos = ParsePosition(0); LocalPointer<CurrencyAmount> curramt(df.parseCurrency(sample, ppos)); status.errIfFailureAndReset(); } // Test with a nonempty exponent separator symbol to cover more code dfs.setSymbol(DecimalFormatSymbols::kExponentialSymbol, u"E", FALSE); df.setDecimalFormatSymbols(dfs); { Formattable result; ParsePosition ppos(0); df.parse(u"1E+2.3", result, ppos); } } void NumberFormatTest::Test20037_ScientificIntegerOverflow() { IcuTestErrorCode status(*this, "Test20037_ScientificIntegerOverflow"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance(status)); if (U_FAILURE(status)) { dataerrln("Unable to create NumberFormat instance."); return; } Formattable result; // Test overflow of exponent nf->parse(u"1E-2147483648", result, status); StringPiece sp = result.getDecimalNumber(status); assertEquals(u"Should snap to zero", u"0", {sp.data(), sp.length(), US_INV}); // Test edge case overflow of exponent result = Formattable(); nf->parse(u"1E-2147483647E-1", result, status); sp = result.getDecimalNumber(status); assertEquals(u"Should not overflow and should parse only the first exponent", u"1E-2147483647", {sp.data(), sp.length(), US_INV}); } void NumberFormatTest::Test13840_ParseLongStringCrash() { IcuTestErrorCode status(*this, "Test13840_ParseLongStringCrash"); LocalPointer<NumberFormat> nf(NumberFormat::createInstance("en", status), status); if (status.errIfFailureAndReset()) { return; } Formattable result; static const char16_t* bigString = u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111" u"111111111111111111111111111111111111111111111111111111111111111111111"; nf->parse(bigString, result, status); // Normalize the input string: CharString expectedChars; expectedChars.appendInvariantChars(bigString, status); DecimalQuantity expectedDQ; expectedDQ.setToDecNumber(expectedChars.toStringPiece(), status); UnicodeString expectedUString = expectedDQ.toScientificString(); // Get the output string: StringPiece actualChars = result.getDecimalNumber(status); UnicodeString actualUString = UnicodeString(actualChars.data(), actualChars.length(), US_INV); assertEquals("Should round-trip without crashing", expectedUString, actualUString); } void NumberFormatTest::Test13850_EmptyStringCurrency() { IcuTestErrorCode status(*this, "Test13840_EmptyStringCurrency"); struct TestCase { const char16_t* currencyArg; UErrorCode expectedError; } cases[] = { {u"", U_ZERO_ERROR}, {u"U", U_ILLEGAL_ARGUMENT_ERROR}, {u"Us", U_ILLEGAL_ARGUMENT_ERROR}, {nullptr, U_ZERO_ERROR}, {u"U$D", U_INVARIANT_CONVERSION_ERROR}, {u"Xxx", U_ZERO_ERROR} }; for (const auto& cas : cases) { UnicodeString message(u"with currency arg: "); if (cas.currencyArg == nullptr) { message += u"nullptr"; } else { message += UnicodeString(cas.currencyArg); } status.setScope(message); LocalPointer<NumberFormat> nf(NumberFormat::createCurrencyInstance("en-US", status), status); if (status.errIfFailureAndReset()) { return; } UnicodeString actual; nf->format(1, actual, status); status.errIfFailureAndReset(); assertEquals(u"Should format with US currency " + message, u"$1.00", actual); nf->setCurrency(cas.currencyArg, status); if (status.expectErrorAndReset(cas.expectedError)) { // If an error occurred, do not check formatting. continue; } nf->format(1, actual.remove(), status); assertEquals(u"Should unset the currency " + message, u"\u00A41.00", actual); status.errIfFailureAndReset(); } } #endif /* #if !UCONFIG_NO_FORMATTING */
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_434_2
crossvul-cpp_data_bad_434_0
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ******************************************************************************* * Copyright (C) 1997-2016, International Business Machines Corporation and * others. All Rights Reserved. ******************************************************************************* * * File FMTABLE.CPP * * Modification History: * * Date Name Description * 03/25/97 clhuang Initial Implementation. ******************************************************************************** */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include <cstdlib> #include <math.h> #include "unicode/fmtable.h" #include "unicode/ustring.h" #include "unicode/measure.h" #include "unicode/curramt.h" #include "unicode/uformattable.h" #include "charstr.h" #include "cmemory.h" #include "cstring.h" #include "fmtableimp.h" #include "number_decimalquantity.h" // ***************************************************************************** // class Formattable // ***************************************************************************** U_NAMESPACE_BEGIN UOBJECT_DEFINE_RTTI_IMPLEMENTATION(Formattable) using number::impl::DecimalQuantity; //-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. // NOTE: As of 3.0, there are limitations to the UObject API. It does // not (yet) support cloning, operator=, nor operator==. To // work around this, I implement some simple inlines here. Later // these can be modified or removed. [alan] // NOTE: These inlines assume that all fObjects are in fact instances // of the Measure class, which is true as of 3.0. [alan] // Return TRUE if *a == *b. static inline UBool objectEquals(const UObject* a, const UObject* b) { // LATER: return *a == *b; return *((const Measure*) a) == *((const Measure*) b); } // Return a clone of *a. static inline UObject* objectClone(const UObject* a) { // LATER: return a->clone(); return ((const Measure*) a)->clone(); } // Return TRUE if *a is an instance of Measure. static inline UBool instanceOfMeasure(const UObject* a) { return dynamic_cast<const Measure*>(a) != NULL; } /** * Creates a new Formattable array and copies the values from the specified * original. * @param array the original array * @param count the original array count * @return the new Formattable array. */ static Formattable* createArrayCopy(const Formattable* array, int32_t count) { Formattable *result = new Formattable[count]; if (result != NULL) { for (int32_t i=0; i<count; ++i) result[i] = array[i]; // Don't memcpy! } return result; } //-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-. /** * Set 'ec' to 'err' only if 'ec' is not already set to a failing UErrorCode. */ static void setError(UErrorCode& ec, UErrorCode err) { if (U_SUCCESS(ec)) { ec = err; } } // // Common initialization code, shared by constructors. // Put everything into a known state. // void Formattable::init() { fValue.fInt64 = 0; fType = kLong; fDecimalStr = NULL; fDecimalQuantity = NULL; fBogus.setToBogus(); } // ------------------------------------- // default constructor. // Creates a formattable object with a long value 0. Formattable::Formattable() { init(); } // ------------------------------------- // Creates a formattable object with a Date instance. Formattable::Formattable(UDate date, ISDATE /*isDate*/) { init(); fType = kDate; fValue.fDate = date; } // ------------------------------------- // Creates a formattable object with a double value. Formattable::Formattable(double value) { init(); fType = kDouble; fValue.fDouble = value; } // ------------------------------------- // Creates a formattable object with an int32_t value. Formattable::Formattable(int32_t value) { init(); fValue.fInt64 = value; } // ------------------------------------- // Creates a formattable object with an int64_t value. Formattable::Formattable(int64_t value) { init(); fType = kInt64; fValue.fInt64 = value; } // ------------------------------------- // Creates a formattable object with a decimal number value from a string. Formattable::Formattable(StringPiece number, UErrorCode &status) { init(); setDecimalNumber(number, status); } // ------------------------------------- // Creates a formattable object with a UnicodeString instance. Formattable::Formattable(const UnicodeString& stringToCopy) { init(); fType = kString; fValue.fString = new UnicodeString(stringToCopy); } // ------------------------------------- // Creates a formattable object with a UnicodeString* value. // (adopting symantics) Formattable::Formattable(UnicodeString* stringToAdopt) { init(); fType = kString; fValue.fString = stringToAdopt; } Formattable::Formattable(UObject* objectToAdopt) { init(); fType = kObject; fValue.fObject = objectToAdopt; } // ------------------------------------- Formattable::Formattable(const Formattable* arrayToCopy, int32_t count) : UObject(), fType(kArray) { init(); fType = kArray; fValue.fArrayAndCount.fArray = createArrayCopy(arrayToCopy, count); fValue.fArrayAndCount.fCount = count; } // ------------------------------------- // copy constructor Formattable::Formattable(const Formattable &source) : UObject(*this) { init(); *this = source; } // ------------------------------------- // assignment operator Formattable& Formattable::operator=(const Formattable& source) { if (this != &source) { // Disposes the current formattable value/setting. dispose(); // Sets the correct data type for this value. fType = source.fType; switch (fType) { case kArray: // Sets each element in the array one by one and records the array count. fValue.fArrayAndCount.fCount = source.fValue.fArrayAndCount.fCount; fValue.fArrayAndCount.fArray = createArrayCopy(source.fValue.fArrayAndCount.fArray, source.fValue.fArrayAndCount.fCount); break; case kString: // Sets the string value. fValue.fString = new UnicodeString(*source.fValue.fString); break; case kDouble: // Sets the double value. fValue.fDouble = source.fValue.fDouble; break; case kLong: case kInt64: // Sets the long value. fValue.fInt64 = source.fValue.fInt64; break; case kDate: // Sets the Date value. fValue.fDate = source.fValue.fDate; break; case kObject: fValue.fObject = objectClone(source.fValue.fObject); break; } UErrorCode status = U_ZERO_ERROR; if (source.fDecimalQuantity != NULL) { fDecimalQuantity = new DecimalQuantity(*source.fDecimalQuantity); } if (source.fDecimalStr != NULL) { fDecimalStr = new CharString(*source.fDecimalStr, status); if (U_FAILURE(status)) { delete fDecimalStr; fDecimalStr = NULL; } } } return *this; } // ------------------------------------- UBool Formattable::operator==(const Formattable& that) const { int32_t i; if (this == &that) return TRUE; // Returns FALSE if the data types are different. if (fType != that.fType) return FALSE; // Compares the actual data values. UBool equal = TRUE; switch (fType) { case kDate: equal = (fValue.fDate == that.fValue.fDate); break; case kDouble: equal = (fValue.fDouble == that.fValue.fDouble); break; case kLong: case kInt64: equal = (fValue.fInt64 == that.fValue.fInt64); break; case kString: equal = (*(fValue.fString) == *(that.fValue.fString)); break; case kArray: if (fValue.fArrayAndCount.fCount != that.fValue.fArrayAndCount.fCount) { equal = FALSE; break; } // Checks each element for equality. for (i=0; i<fValue.fArrayAndCount.fCount; ++i) { if (fValue.fArrayAndCount.fArray[i] != that.fValue.fArrayAndCount.fArray[i]) { equal = FALSE; break; } } break; case kObject: if (fValue.fObject == NULL || that.fValue.fObject == NULL) { equal = FALSE; } else { equal = objectEquals(fValue.fObject, that.fValue.fObject); } break; } // TODO: compare digit lists if numeric. return equal; } // ------------------------------------- Formattable::~Formattable() { dispose(); } // ------------------------------------- void Formattable::dispose() { // Deletes the data value if necessary. switch (fType) { case kString: delete fValue.fString; break; case kArray: delete[] fValue.fArrayAndCount.fArray; break; case kObject: delete fValue.fObject; break; default: break; } fType = kLong; fValue.fInt64 = 0; delete fDecimalStr; fDecimalStr = NULL; delete fDecimalQuantity; fDecimalQuantity = NULL; } Formattable * Formattable::clone() const { return new Formattable(*this); } // ------------------------------------- // Gets the data type of this Formattable object. Formattable::Type Formattable::getType() const { return fType; } UBool Formattable::isNumeric() const { switch (fType) { case kDouble: case kLong: case kInt64: return TRUE; default: return FALSE; } } // ------------------------------------- int32_t //Formattable::getLong(UErrorCode* status) const Formattable::getLong(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: return (int32_t)fValue.fInt64; case Formattable::kInt64: if (fValue.fInt64 > INT32_MAX) { status = U_INVALID_FORMAT_ERROR; return INT32_MAX; } else if (fValue.fInt64 < INT32_MIN) { status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { return (int32_t)fValue.fInt64; } case Formattable::kDouble: if (fValue.fDouble > INT32_MAX) { status = U_INVALID_FORMAT_ERROR; return INT32_MAX; } else if (fValue.fDouble < INT32_MIN) { status = U_INVALID_FORMAT_ERROR; return INT32_MIN; } else { return (int32_t)fValue.fDouble; // loses fraction } case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } // TODO Later replace this with instanceof call if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getLong(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } // ------------------------------------- // Maximum int that can be represented exactly in a double. (53 bits) // Larger ints may be rounded to a near-by value as not all are representable. // TODO: move this constant elsewhere, possibly configure it for different // floating point formats, if any non-standard ones are still in use. static const int64_t U_DOUBLE_MAX_EXACT_INT = 9007199254740992LL; int64_t Formattable::getInt64(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: case Formattable::kInt64: return fValue.fInt64; case Formattable::kDouble: if (fValue.fDouble > (double)U_INT64_MAX) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MAX; } else if (fValue.fDouble < (double)U_INT64_MIN) { status = U_INVALID_FORMAT_ERROR; return U_INT64_MIN; } else if (fabs(fValue.fDouble) > U_DOUBLE_MAX_EXACT_INT && fDecimalQuantity != NULL) { if (fDecimalQuantity->fitsInLong(true)) { return fDecimalQuantity->toLong(); } else { // Unexpected status = U_INVALID_FORMAT_ERROR; return fDecimalQuantity->isNegative() ? U_INT64_MIN : U_INT64_MAX; } } else { return (int64_t)fValue.fDouble; } case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getInt64(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } // ------------------------------------- double Formattable::getDouble(UErrorCode& status) const { if (U_FAILURE(status)) { return 0; } switch (fType) { case Formattable::kLong: case Formattable::kInt64: // loses precision return (double)fValue.fInt64; case Formattable::kDouble: return fValue.fDouble; case Formattable::kObject: if (fValue.fObject == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return 0; } // TODO Later replace this with instanceof call if (instanceOfMeasure(fValue.fObject)) { return ((const Measure*) fValue.fObject)-> getNumber().getDouble(status); } U_FALLTHROUGH; default: status = U_INVALID_FORMAT_ERROR; return 0; } } const UObject* Formattable::getObject() const { return (fType == kObject) ? fValue.fObject : NULL; } // ------------------------------------- // Sets the value to a double value d. void Formattable::setDouble(double d) { dispose(); fType = kDouble; fValue.fDouble = d; } // ------------------------------------- // Sets the value to a long value l. void Formattable::setLong(int32_t l) { dispose(); fType = kLong; fValue.fInt64 = l; } // ------------------------------------- // Sets the value to an int64 value ll. void Formattable::setInt64(int64_t ll) { dispose(); fType = kInt64; fValue.fInt64 = ll; } // ------------------------------------- // Sets the value to a Date instance d. void Formattable::setDate(UDate d) { dispose(); fType = kDate; fValue.fDate = d; } // ------------------------------------- // Sets the value to a string value stringToCopy. void Formattable::setString(const UnicodeString& stringToCopy) { dispose(); fType = kString; fValue.fString = new UnicodeString(stringToCopy); } // ------------------------------------- // Sets the value to an array of Formattable objects. void Formattable::setArray(const Formattable* array, int32_t count) { dispose(); fType = kArray; fValue.fArrayAndCount.fArray = createArrayCopy(array, count); fValue.fArrayAndCount.fCount = count; } // ------------------------------------- // Adopts the stringToAdopt value. void Formattable::adoptString(UnicodeString* stringToAdopt) { dispose(); fType = kString; fValue.fString = stringToAdopt; } // ------------------------------------- // Adopts the array value and its count. void Formattable::adoptArray(Formattable* array, int32_t count) { dispose(); fType = kArray; fValue.fArrayAndCount.fArray = array; fValue.fArrayAndCount.fCount = count; } void Formattable::adoptObject(UObject* objectToAdopt) { dispose(); fType = kObject; fValue.fObject = objectToAdopt; } // ------------------------------------- UnicodeString& Formattable::getString(UnicodeString& result, UErrorCode& status) const { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); result.setToBogus(); } else { if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); } else { result = *fValue.fString; } } return result; } // ------------------------------------- const UnicodeString& Formattable::getString(UErrorCode& status) const { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); return *getBogus(); } if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); return *getBogus(); } return *fValue.fString; } // ------------------------------------- UnicodeString& Formattable::getString(UErrorCode& status) { if (fType != kString) { setError(status, U_INVALID_FORMAT_ERROR); return *getBogus(); } if (fValue.fString == NULL) { setError(status, U_MEMORY_ALLOCATION_ERROR); return *getBogus(); } return *fValue.fString; } // ------------------------------------- const Formattable* Formattable::getArray(int32_t& count, UErrorCode& status) const { if (fType != kArray) { setError(status, U_INVALID_FORMAT_ERROR); count = 0; return NULL; } count = fValue.fArrayAndCount.fCount; return fValue.fArrayAndCount.fArray; } // ------------------------------------- // Gets the bogus string, ensures mondo bogosity. UnicodeString* Formattable::getBogus() const { return (UnicodeString*)&fBogus; /* cast away const :-( */ } // -------------------------------------- StringPiece Formattable::getDecimalNumber(UErrorCode &status) { if (U_FAILURE(status)) { return ""; } if (fDecimalStr != NULL) { return fDecimalStr->toStringPiece(); } CharString *decimalStr = internalGetCharString(status); if(decimalStr == NULL) { return ""; // getDecimalNumber returns "" for error cases } else { return decimalStr->toStringPiece(); } } CharString *Formattable::internalGetCharString(UErrorCode &status) { if(fDecimalStr == NULL) { if (fDecimalQuantity == NULL) { // No decimal number for the formattable yet. Which means the value was // set directly by the user as an int, int64 or double. If the value came // from parsing, or from the user setting a decimal number, fDecimalNum // would already be set. // LocalPointer<DecimalQuantity> dq(new DecimalQuantity(), status); if (U_FAILURE(status)) { return nullptr; } populateDecimalQuantity(*dq, status); if (U_FAILURE(status)) { return nullptr; } fDecimalQuantity = dq.orphan(); } fDecimalStr = new CharString(); if (fDecimalStr == NULL) { status = U_MEMORY_ALLOCATION_ERROR; return NULL; } // Older ICUs called uprv_decNumberToString here, which is not exactly the same as // DecimalQuantity::toScientificString(). The biggest difference is that uprv_decNumberToString does // not print scientific notation for magnitudes greater than -5 and smaller than some amount (+5?). if (fDecimalQuantity->isZero()) { fDecimalStr->append("0", -1, status); } else if (std::abs(fDecimalQuantity->getMagnitude()) < 5) { fDecimalStr->appendInvariantChars(fDecimalQuantity->toPlainString(), status); } else { fDecimalStr->appendInvariantChars(fDecimalQuantity->toScientificString(), status); } } return fDecimalStr; } void Formattable::populateDecimalQuantity(number::impl::DecimalQuantity& output, UErrorCode& status) const { if (fDecimalQuantity != nullptr) { output = *fDecimalQuantity; return; } switch (fType) { case kDouble: output.setToDouble(this->getDouble()); output.roundToInfinity(); break; case kLong: output.setToInt(this->getLong()); break; case kInt64: output.setToLong(this->getInt64()); break; default: // The formattable's value is not a numeric type. status = U_INVALID_STATE_ERROR; } } // --------------------------------------- void Formattable::adoptDecimalQuantity(DecimalQuantity *dq) { if (fDecimalQuantity != NULL) { delete fDecimalQuantity; } fDecimalQuantity = dq; if (dq == NULL) { // allow adoptDigitList(NULL) to clear return; } // Set the value into the Union of simple type values. // Cannot use the set() functions because they would delete the fDecimalNum value. if (fDecimalQuantity->fitsInLong()) { fValue.fInt64 = fDecimalQuantity->toLong(); if (fValue.fInt64 <= INT32_MAX && fValue.fInt64 >= INT32_MIN) { fType = kLong; } else { fType = kInt64; } } else { fType = kDouble; fValue.fDouble = fDecimalQuantity->toDouble(); } } // --------------------------------------- void Formattable::setDecimalNumber(StringPiece numberString, UErrorCode &status) { if (U_FAILURE(status)) { return; } dispose(); auto* dq = new DecimalQuantity(); dq->setToDecNumber(numberString, status); adoptDecimalQuantity(dq); // Note that we do not hang on to the caller's input string. // If we are asked for the string, we will regenerate one from fDecimalQuantity. } #if 0 //---------------------------------------------------- // console I/O //---------------------------------------------------- #ifdef _DEBUG #include <iostream> using namespace std; #include "unicode/datefmt.h" #include "unistrm.h" class FormattableStreamer /* not : public UObject because all methods are static */ { public: static void streamOut(ostream& stream, const Formattable& obj); private: FormattableStreamer() {} // private - forbid instantiation }; // This is for debugging purposes only. This will send a displayable // form of the Formattable object to the output stream. void FormattableStreamer::streamOut(ostream& stream, const Formattable& obj) { static DateFormat *defDateFormat = 0; UnicodeString buffer; switch(obj.getType()) { case Formattable::kDate : // Creates a DateFormat instance for formatting the // Date instance. if (defDateFormat == 0) { defDateFormat = DateFormat::createInstance(); } defDateFormat->format(obj.getDate(), buffer); stream << buffer; break; case Formattable::kDouble : // Output the double as is. stream << obj.getDouble() << 'D'; break; case Formattable::kLong : // Output the double as is. stream << obj.getLong() << 'L'; break; case Formattable::kString: // Output the double as is. Please see UnicodeString console // I/O routine for more details. stream << '"' << obj.getString(buffer) << '"'; break; case Formattable::kArray: int32_t i, count; const Formattable* array; array = obj.getArray(count); stream << '['; // Recursively calling the console I/O routine for each element in the array. for (i=0; i<count; ++i) { FormattableStreamer::streamOut(stream, array[i]); stream << ( (i==(count-1)) ? "" : ", " ); } stream << ']'; break; default: // Not a recognizable Formattable object. stream << "INVALID_Formattable"; } stream.flush(); } #endif #endif U_NAMESPACE_END /* ---- UFormattable implementation ---- */ U_NAMESPACE_USE U_DRAFT UFormattable* U_EXPORT2 ufmt_open(UErrorCode *status) { if( U_FAILURE(*status) ) { return NULL; } UFormattable *fmt = (new Formattable())->toUFormattable(); if( fmt == NULL ) { *status = U_MEMORY_ALLOCATION_ERROR; } return fmt; } U_DRAFT void U_EXPORT2 ufmt_close(UFormattable *fmt) { Formattable *obj = Formattable::fromUFormattable(fmt); delete obj; } U_INTERNAL UFormattableType U_EXPORT2 ufmt_getType(const UFormattable *fmt, UErrorCode *status) { if(U_FAILURE(*status)) { return (UFormattableType)UFMT_COUNT; } const Formattable *obj = Formattable::fromUFormattable(fmt); return (UFormattableType)obj->getType(); } U_INTERNAL UBool U_EXPORT2 ufmt_isNumeric(const UFormattable *fmt) { const Formattable *obj = Formattable::fromUFormattable(fmt); return obj->isNumeric(); } U_DRAFT UDate U_EXPORT2 ufmt_getDate(const UFormattable *fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getDate(*status); } U_DRAFT double U_EXPORT2 ufmt_getDouble(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getDouble(*status); } U_DRAFT int32_t U_EXPORT2 ufmt_getLong(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getLong(*status); } U_DRAFT const void *U_EXPORT2 ufmt_getObject(const UFormattable *fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); const void *ret = obj->getObject(); if( ret==NULL && (obj->getType() != Formattable::kObject) && U_SUCCESS( *status )) { *status = U_INVALID_FORMAT_ERROR; } return ret; } U_DRAFT const UChar* U_EXPORT2 ufmt_getUChars(UFormattable *fmt, int32_t *len, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); // avoid bogosity by checking the type first. if( obj->getType() != Formattable::kString ) { if( U_SUCCESS(*status) ){ *status = U_INVALID_FORMAT_ERROR; } return NULL; } // This should return a valid string UnicodeString &str = obj->getString(*status); if( U_SUCCESS(*status) && len != NULL ) { *len = str.length(); } return str.getTerminatedBuffer(); } U_DRAFT int32_t U_EXPORT2 ufmt_getArrayLength(const UFormattable* fmt, UErrorCode *status) { const Formattable *obj = Formattable::fromUFormattable(fmt); int32_t count; (void)obj->getArray(count, *status); return count; } U_DRAFT UFormattable * U_EXPORT2 ufmt_getArrayItemByIndex(UFormattable* fmt, int32_t n, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); int32_t count; (void)obj->getArray(count, *status); if(U_FAILURE(*status)) { return NULL; } else if(n<0 || n>=count) { setError(*status, U_INDEX_OUTOFBOUNDS_ERROR); return NULL; } else { return (*obj)[n].toUFormattable(); // returns non-const Formattable } } U_DRAFT const char * U_EXPORT2 ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status) { if(U_FAILURE(*status)) { return ""; } Formattable *obj = Formattable::fromUFormattable(fmt); CharString *charString = obj->internalGetCharString(*status); if(U_FAILURE(*status)) { return ""; } if(charString == NULL) { *status = U_MEMORY_ALLOCATION_ERROR; return ""; } else { if(len!=NULL) { *len = charString->length(); } return charString->data(); } } U_DRAFT int64_t U_EXPORT2 ufmt_getInt64(UFormattable *fmt, UErrorCode *status) { Formattable *obj = Formattable::fromUFormattable(fmt); return obj->getInt64(*status); } #endif /* #if !UCONFIG_NO_FORMATTING */ //eof
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_434_0
crossvul-cpp_data_good_291_0
/********************************************************************** * Log: * 2006-03-12: Parts originally authored by Doug Madory as wifi_parser.c * 2013-03-15: Substantially modified by Simson Garfinkel for inclusion into tcpflow * 2013-11-18: reworked static calls to be entirely calls to a class. Changed TimeVal pointer to an instance variable that includes the full packet header. **********************************************************************/ //*do 11-18 #include "config.h" // pull in HAVE_ defines #define __STDC_FORMAT_MACROS #include <stdint.h> #include <inttypes.h> #include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <stdarg.h> #include <errno.h> #ifdef HAVE_NET_ETHERNET_H #include <net/ethernet.h> #endif #ifdef HAVE_ARPA_INET_H #include <arpa/inet.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #pragma GCC diagnostic ignored "-Wcast-align" #include "wifipcap.h" #include "cpack.h" #include "extract.h" #include "oui.h" #include "ethertype.h" #include "icmp.h" #include "ipproto.h" /* wifipcap uses a MAC class which is somewhat lame, but works */ MAC MAC::broadcast(0xffffffffffffULL); MAC MAC::null((uint64_t)0); int WifiPacket::debug=0; int MAC::print_fmt(MAC::PRINT_FMT_COLON); std::ostream& operator<<(std::ostream& out, const MAC& mac) { const char *fmt = MAC::print_fmt == MAC::PRINT_FMT_COLON ? "%02x:%02x:%02x:%02x:%02x:%02x" : "%02x%02x%02x%02x%02x%02x"; char buf[24]; sprintf(buf, fmt, (int)((mac.val>>40)&0xff), (int)((mac.val>>32)&0xff), (int)((mac.val>>24)&0xff), (int)((mac.val>>16)&0xff), (int)((mac.val>>8)&0xff), (int)((mac.val)&0xff) ); out << buf; return out; } std::ostream& operator<<(std::ostream& out, const struct in_addr& ip) { out << inet_ntoa(ip); return out; } struct tok { int v; /* value */ const char *s; /* string */ }; #if 0 static const struct tok ethertype_values[] = { { ETHERTYPE_IP, "IPv4" }, { ETHERTYPE_MPLS, "MPLS unicast" }, { ETHERTYPE_MPLS_MULTI, "MPLS multicast" }, { ETHERTYPE_IPV6, "IPv6" }, { ETHERTYPE_8021Q, "802.1Q" }, { ETHERTYPE_VMAN, "VMAN" }, { ETHERTYPE_PUP, "PUP" }, { ETHERTYPE_ARP, "ARP"}, { ETHERTYPE_REVARP, "Reverse ARP"}, { ETHERTYPE_NS, "NS" }, { ETHERTYPE_SPRITE, "Sprite" }, { ETHERTYPE_TRAIL, "Trail" }, { ETHERTYPE_MOPDL, "MOP DL" }, { ETHERTYPE_MOPRC, "MOP RC" }, { ETHERTYPE_DN, "DN" }, { ETHERTYPE_LAT, "LAT" }, { ETHERTYPE_SCA, "SCA" }, { ETHERTYPE_LANBRIDGE, "Lanbridge" }, { ETHERTYPE_DECDNS, "DEC DNS" }, { ETHERTYPE_DECDTS, "DEC DTS" }, { ETHERTYPE_VEXP, "VEXP" }, { ETHERTYPE_VPROD, "VPROD" }, { ETHERTYPE_ATALK, "Appletalk" }, { ETHERTYPE_AARP, "Appletalk ARP" }, { ETHERTYPE_IPX, "IPX" }, { ETHERTYPE_PPP, "PPP" }, { ETHERTYPE_SLOW, "Slow Protocols" }, { ETHERTYPE_PPPOED, "PPPoE D" }, { ETHERTYPE_PPPOES, "PPPoE S" }, { ETHERTYPE_EAPOL, "EAPOL" }, { ETHERTYPE_JUMBO, "Jumbo" }, { ETHERTYPE_LOOPBACK, "Loopback" }, { ETHERTYPE_ISO, "OSI" }, { ETHERTYPE_GRE_ISO, "GRE-OSI" }, { 0, NULL} }; #endif /*max length of an IEEE 802.11 packet*/ #ifndef MAX_LEN_80211 #define MAX_LEN_80211 3000 #endif /* from ethereal packet-prism.c */ #define pletohs(p) ((u_int16_t) \ ((u_int16_t)*((const u_int8_t *)(p)+1)<<8| \ (u_int16_t)*((const u_int8_t *)(p)+0)<<0)) #define pntohl(p) ((u_int32_t)*((const u_int8_t *)(p)+0)<<24| \ (u_int32_t)*((const u_int8_t *)(p)+1)<<16| \ (u_int32_t)*((const u_int8_t *)(p)+2)<<8| \ (u_int32_t)*((const u_int8_t *)(p)+3)<<0) #define COOK_FRAGMENT_NUMBER(x) ((x) & 0x000F) #define COOK_SEQUENCE_NUMBER(x) (((x) & 0xFFF0) >> 4) /* end ethereal code */ /* Sequence number gap */ #define SEQ_GAP(current, last)(0xfff & (current - last)) /* In the following three arrays, even though the QoS subtypes are listed, in the rest of the program * the QoS subtypes are treated as "OTHER_TYPES". The file "ieee802_11.h" currently doesn't account for * the existence of QoS subtypes. The QoS subtypes might need to be accomodated there in the future. */ #if 0 static const char * mgmt_subtype_text[] = { "AssocReq", "AssocResp", "ReAssocReq", "ReAssocResp", "ProbeReq", "ProbeResp", "", "", "Beacon", "ATIM", "Disassoc", "Auth", "DeAuth", "Action", /*QoS mgmt_subtype*/ "", "" }; static const char * ctrl_subtype_text[] = { "", "", "", "", "", "", "", "", "BlockAckReq", /*QoS ctrl_subtype*/ "BlockAck", /*QoS ctrl_subtype*/ "PS-Poll", "RTS", "CTS", "ACK", "CF-End", "CF-End+CF-Ack" }; static const char * data_subtype_text[] = { "Data", "Data+CF-Ack", "Data+CF-Poll", "Data+CF-Ack+CF-Poll", "Null(no_data)", "CF-Ack(no_data)", "CF-Poll(no_data)", "CF-Ack+CF-Poll(no_data)", "QoS_Data", /*QoS data_subtypes from here on*/ "QoS_Data+CF-Ack", "QoS_Data+CF-Poll", "QoS_Data+CF-Ack+CF-Poll", "QoS_Null(no_data)", "", "QoS_CF-Poll(no_data)", "QoS_CF-Ack+CF-Poll(no_data)" }; #endif /////////////////////////////////////////////////////////////////////////////// // crc32 implementation needed for wifi checksum /* crc32.c * CRC-32 routine * * $Id: crc32.cpp,v 1.1 2007/02/14 00:05:50 jpang Exp $ * * Ethereal - Network traffic analyzer * By Gerald Combs <gerald@ethereal.com> * Copyright 1998 Gerald Combs * * Copied from README.developer * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Credits: * * Table from Solomon Peachy * Routine from Chris Waters */ /* * Table for the AUTODIN/HDLC/802.x CRC. * * Polynomial is * * x^32 + x^26 + x^23 + x^22 + x^16 + x^12 + x^11 + x^8 + x^7 + * x^5 + x^4 + x^2 + x + 1 */ static const uint32_t crc32_ccitt_table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; #define CRC32_CCITT_SEED 0xFFFFFFFF static uint32_t crc32_ccitt_seed(const uint8_t *buf, size_t len, uint32_t seed); static uint32_t crc32_ccitt(const uint8_t *buf, size_t len) { return ( crc32_ccitt_seed(buf, len, CRC32_CCITT_SEED) ); } static uint32_t crc32_ccitt_seed(const uint8_t *buf, size_t len, uint32_t seed) { uint32_t crc32 = seed; for (unsigned int i = 0; i < len; i++){ crc32 = crc32_ccitt_table[(crc32 ^ buf[i]) & 0xff] ^ (crc32 >> 8); } return ( ~crc32 ); } /* * IEEE 802.x version (Ethernet and 802.11, at least) - byte-swap * the result of "crc32()". * * XXX - does this mean we should fetch the Ethernet and 802.11 * Frame Checksum (FCS) with "tvb_get_letohl()" rather than "tvb_get_ntohl()", * or is fetching it big-endian and byte-swapping the CRC done * to cope with 802.x sending stuff out in reverse bit order? */ static uint32_t crc32_802(const unsigned char *buf, size_t len) { uint32_t c_crc; c_crc = crc32_ccitt(buf, len); /* Byte reverse. */ c_crc = ((unsigned char)(c_crc>>0)<<24) | ((unsigned char)(c_crc>>8)<<16) | ((unsigned char)(c_crc>>16)<<8) | ((unsigned char)(c_crc>>24)<<0); return ( c_crc ); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /* Translate Ethernet address, as seen in struct ether_header, to type MAC. */ /* Extract header length. */ static size_t extract_header_length(u_int16_t fc) { switch (FC_TYPE(fc)) { case T_MGMT: return MGMT_HDRLEN; case T_CTRL: switch (FC_SUBTYPE(fc)) { case CTRL_PS_POLL: return CTRL_PS_POLL_HDRLEN; case CTRL_RTS: return CTRL_RTS_HDRLEN; case CTRL_CTS: return CTRL_CTS_HDRLEN; case CTRL_ACK: return CTRL_ACK_HDRLEN; case CTRL_CF_END: return CTRL_END_HDRLEN; case CTRL_END_ACK: return CTRL_END_ACK_HDRLEN; default: return 0; } case T_DATA: return (FC_TO_DS(fc) && FC_FROM_DS(fc)) ? 30 : 24; default: return 0; } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// #pragma GCC diagnostic ignored "-Wcast-align" void WifiPacket::handle_llc(const mac_hdr_t &mac,const u_char *ptr, size_t len,u_int16_t fc) { if (len < 7) { // truncated header! cbs->HandleLLC(*this,NULL, ptr, len); return; } // http://www.wildpackets.com/resources/compendium/wireless_lan/wlan_packets llc_hdr_t hdr; hdr.dsap = EXTRACT_LE_8BITS(ptr); // Destination Service Access point hdr.ssap = EXTRACT_LE_8BITS(ptr + 1); // Source Service Access Point hdr.control= EXTRACT_LE_8BITS(ptr + 2); // ignored by most protocols hdr.oui = EXTRACT_24BITS(ptr + 3); hdr.type = EXTRACT_16BITS(ptr + 6); /* "When both the DSAP and SSAP are set to 0xAA, the type is * interpreted as a protocol not defined by IEEE and the LSAP is * referred to as SubNetwork Access Protocol (SNAP). In SNAP, the * 5 bytes that follow the DSAP, SSAP, and control byte are called * the Protocol Discriminator." */ if(hdr.dsap==0xAA && hdr.ssap==0xAA){ cbs->HandleLLC(*this,&hdr,ptr+8,len-8); return; } if (hdr.oui == OUI_ENCAP_ETHER || hdr.oui == OUI_CISCO_90) { cbs->HandleLLC(*this,&hdr, ptr+8, len-8); return; } cbs->HandleLLCUnknown(*this,ptr, len); } void WifiPacket::handle_wep(const u_char *ptr, size_t len) { // Jeff: XXX handle TKIP/CCMP ? how can we demultiplex different // protection protocols? struct wep_hdr_t hdr; u_int32_t iv; if (len < IEEE802_11_IV_LEN + IEEE802_11_KID_LEN) { // truncated! cbs->HandleWEP(*this,NULL, ptr, len); return; } iv = EXTRACT_LE_32BITS(ptr); hdr.iv = IV_IV(iv); hdr.pad = IV_PAD(iv); hdr.keyid = IV_KEYID(iv); cbs->HandleWEP(*this,&hdr, ptr, len); } /////////////////////////////////////////////////////////////////////////////// static const char *auth_alg_text[]={"Open System","Shared Key","EAP"}; #define NUM_AUTH_ALGS (sizeof auth_alg_text / sizeof auth_alg_text[0]) static const char *status_text[] = { "Succesful", /* 0 */ "Unspecified failure", /* 1 */ "Reserved", /* 2 */ "Reserved", /* 3 */ "Reserved", /* 4 */ "Reserved", /* 5 */ "Reserved", /* 6 */ "Reserved", /* 7 */ "Reserved", /* 8 */ "Reserved", /* 9 */ "Cannot Support all requested capabilities in the Capability Information field", /* 10 */ "Reassociation denied due to inability to confirm that association exists", /* 11 */ "Association denied due to reason outside the scope of the standard", /* 12 */ "Responding station does not support the specified authentication algorithm ", /* 13 */ "Received an Authentication frame with authentication transaction " \ "sequence number out of expected sequence", /* 14 */ "Authentication rejected because of challenge failure", /* 15 */ "Authentication rejected due to timeout waiting for next frame in sequence", /* 16 */ "Association denied because AP is unable to handle additional associated stations", /* 17 */ "Association denied due to requesting station not supporting all of the " \ "data rates in BSSBasicRateSet parameter", /* 18 */ }; #define NUM_STATUSES (sizeof status_text / sizeof status_text[0]) static const char *reason_text[] = { "Reserved", /* 0 */ "Unspecified reason", /* 1 */ "Previous authentication no longer valid", /* 2 */ "Deauthenticated because sending station is leaving (or has left) IBSS or ESS", /* 3 */ "Disassociated due to inactivity", /* 4 */ "Disassociated because AP is unable to handle all currently associated stations", /* 5 */ "Class 2 frame received from nonauthenticated station", /* 6 */ "Class 3 frame received from nonassociated station", /* 7 */ "Disassociated because sending station is leaving (or has left) BSS", /* 8 */ "Station requesting (re)association is not authenticated with responding station", /* 9 */ }; #define NUM_REASONS (sizeof reason_text / sizeof reason_text[0]) const char *Wifipcap::WifiUtil::MgmtAuthAlg2Txt(uint v) { return v < NUM_AUTH_ALGS ? auth_alg_text[v] : "Unknown"; } const char *Wifipcap::WifiUtil::MgmtStatusCode2Txt(uint v) { return v < NUM_STATUSES ? status_text[v] : "Reserved"; } const char *Wifipcap::WifiUtil::MgmtReasonCode2Txt(uint v) { return v < NUM_REASONS ? reason_text[v] : "Reserved"; } /////////////////////////////////////////////////////////////////////////////// // Jeff: HACK -- tcpdump uses a global variable to check truncation #define TTEST2(_p, _l) ((const u_char *)&(_p) - p + (_l) <= (ssize_t)len) void WifiPacket::parse_elements(struct mgmt_body_t *pbody, const u_char *p, int offset, size_t len) { /* * We haven't seen any elements yet. */ pbody->challenge_status = NOT_PRESENT; pbody->ssid_status = NOT_PRESENT; pbody->rates_status = NOT_PRESENT; pbody->ds_status = NOT_PRESENT; pbody->cf_status = NOT_PRESENT; pbody->tim_status = NOT_PRESENT; for (;;) { if (!TTEST2(*(p + offset), 1)) return; switch (*(p + offset)) { case E_SSID: /* Present, possibly truncated */ pbody->ssid_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->ssid, p + offset, 2); offset += 2; if (pbody->ssid.length != 0) { if (pbody->ssid.length > sizeof(pbody->ssid.ssid) - 1) return; if (!TTEST2(*(p + offset), pbody->ssid.length)) return; memcpy(&pbody->ssid.ssid, p + offset, pbody->ssid.length); offset += pbody->ssid.length; } pbody->ssid.ssid[pbody->ssid.length] = '\0'; /* Present and not truncated */ pbody->ssid_status = PRESENT; break; case E_CHALLENGE: /* Present, possibly truncated */ pbody->challenge_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->challenge, p + offset, 2); offset += 2; if (pbody->challenge.length != 0) { if (pbody->challenge.length > sizeof(pbody->challenge.text) - 1) return; if (!TTEST2(*(p + offset), pbody->challenge.length)) return; memcpy(&pbody->challenge.text, p + offset, pbody->challenge.length); offset += pbody->challenge.length; } pbody->challenge.text[pbody->challenge.length] = '\0'; /* Present and not truncated */ pbody->challenge_status = PRESENT; break; case E_RATES: /* Present, possibly truncated */ pbody->rates_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&(pbody->rates), p + offset, 2); offset += 2; if (pbody->rates.length != 0) { if (pbody->rates.length > sizeof pbody->rates.rate) return; if (!TTEST2(*(p + offset), pbody->rates.length)) return; memcpy(&pbody->rates.rate, p + offset, pbody->rates.length); offset += pbody->rates.length; } /* Present and not truncated */ pbody->rates_status = PRESENT; break; case E_DS: /* Present, possibly truncated */ pbody->ds_status = TRUNCATED; if (!TTEST2(*(p + offset), 3)) return; memcpy(&pbody->ds, p + offset, 3); offset += 3; /* Present and not truncated */ pbody->ds_status = PRESENT; break; case E_CF: /* Present, possibly truncated */ pbody->cf_status = TRUNCATED; if (!TTEST2(*(p + offset), 8)) return; memcpy(&pbody->cf, p + offset, 8); offset += 8; /* Present and not truncated */ pbody->cf_status = PRESENT; break; case E_TIM: /* Present, possibly truncated */ pbody->tim_status = TRUNCATED; if (!TTEST2(*(p + offset), 2)) return; memcpy(&pbody->tim, p + offset, 2); offset += 2; if (!TTEST2(*(p + offset), 3)) return; memcpy(&pbody->tim.count, p + offset, 3); offset += 3; if (pbody->tim.length <= 3) break; if (pbody->rates.length > sizeof pbody->tim.bitmap) return; if (!TTEST2(*(p + offset), pbody->tim.length - 3)) return; memcpy(pbody->tim.bitmap, p + (pbody->tim.length - 3), (pbody->tim.length - 3)); offset += pbody->tim.length - 3; /* Present and not truncated */ pbody->tim_status = PRESENT; break; default: #ifdef DEBUG_WIFI printf("(1) unhandled element_id (%d) ", *(p + offset) ); #endif if (!TTEST2(*(p + offset), 2)) return; if (!TTEST2(*(p + offset + 2), *(p + offset + 1))) return; offset += *(p + offset + 1) + 2; break; } } } /********************************************************************************* * Print Handle functions for the management frame types *********************************************************************************/ int WifiPacket::handle_beacon( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); printf(" %s", CAPABILITY_ESS(pbody.capability_info) ? "ESS" : "IBSS"); PRINT_DS_CHANNEL(pbody); */ cbs->Handle80211MgmtBeacon(*this, pmh, &pbody); return 1; } int WifiPacket::handle_assoc_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); */ cbs->Handle80211MgmtAssocRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_assoc_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len, bool reassoc) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_STATUS_LEN + IEEE802_11_AID_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.status_code = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_STATUS_LEN; pbody.aid = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_AID_LEN; parse_elements(&pbody, p, offset, len); /* printf(" AID(%x) :%s: %s", ((u_int16_t)(pbody.aid << 2 )) >> 2 , CAPABILITY_PRIVACY(pbody.capability_info) ? " PRIVACY " : "", (pbody.status_code < NUM_STATUSES ? status_text[pbody.status_code] : "n/a")); */ if (!reassoc) cbs->Handle80211MgmtAssocResponse(*this, pmh, &pbody); else cbs->Handle80211MgmtReassocResponse(*this, pmh, &pbody); return 1; } int WifiPacket::handle_reassoc_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_CAPINFO_LEN + IEEE802_11_LISTENINT_LEN + IEEE802_11_AP_LEN)) return 0; pbody.capability_info = EXTRACT_LE_16BITS(p); offset += IEEE802_11_CAPINFO_LEN; pbody.listen_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_LISTENINT_LEN; memcpy(&pbody.ap, p+offset, IEEE802_11_AP_LEN); offset += IEEE802_11_AP_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); printf(" AP : %s", etheraddr_string( pbody.ap )); */ cbs->Handle80211MgmtReassocRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_reassoc_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { /* Same as a Association Reponse */ return handle_assoc_response(pmh, p, len, true); } int WifiPacket::handle_probe_request( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); */ cbs->Handle80211MgmtProbeRequest(*this, pmh, &pbody); return 1; } int WifiPacket::handle_probe_response( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_TSTAMP_LEN + IEEE802_11_BCNINT_LEN + IEEE802_11_CAPINFO_LEN)) return 0; memcpy(&pbody.timestamp, p, IEEE802_11_TSTAMP_LEN); offset += IEEE802_11_TSTAMP_LEN; pbody.beacon_interval = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_BCNINT_LEN; pbody.capability_info = EXTRACT_LE_16BITS(p+offset); offset += IEEE802_11_CAPINFO_LEN; parse_elements(&pbody, p, offset, len); /* PRINT_SSID(pbody); PRINT_RATES(pbody); PRINT_DS_CHANNEL(pbody); */ cbs->Handle80211MgmtProbeResponse(*this, pmh, &pbody); return 1; } int WifiPacket::handle_atim( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { /* the frame body for ATIM is null. */ cbs->Handle80211MgmtATIM(*this, pmh); return 1; } int WifiPacket::handle_disassoc( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); /* printf(": %s", (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved" ); */ cbs->Handle80211MgmtDisassoc(*this, pmh, &pbody); return 1; } int WifiPacket::handle_auth( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, 6)) return 0; pbody.auth_alg = EXTRACT_LE_16BITS(p); offset += 2; pbody.auth_trans_seq_num = EXTRACT_LE_16BITS(p + offset); offset += 2; pbody.status_code = EXTRACT_LE_16BITS(p + offset); offset += 2; parse_elements(&pbody, p, offset, len); /* if ((pbody.auth_alg == 1) && ((pbody.auth_trans_seq_num == 2) || (pbody.auth_trans_seq_num == 3))) { printf(" (%s)-%x [Challenge Text] %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, ((pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : "")); return 1; } printf(" (%s)-%x: %s", (pbody.auth_alg < NUM_AUTH_ALGS) ? auth_alg_text[pbody.auth_alg] : "Reserved", pbody.auth_trans_seq_num, (pbody.auth_trans_seq_num % 2) ? ((pbody.status_code < NUM_STATUSES) ? status_text[pbody.status_code] : "n/a") : ""); */ cbs->Handle80211MgmtAuth(*this, pmh, &pbody); return 1; } int WifiPacket::handle_deauth( const struct mgmt_header_t *pmh, const u_char *p, size_t len) { struct mgmt_body_t pbody; int offset = 0; //const char *reason = NULL; memset(&pbody, 0, sizeof(pbody)); if (!TTEST2(*p, IEEE802_11_REASON_LEN)) return 0; pbody.reason_code = EXTRACT_LE_16BITS(p); offset += IEEE802_11_REASON_LEN; /* reason = (pbody.reason_code < NUM_REASONS) ? reason_text[pbody.reason_code] : "Reserved"; if (eflag) { printf(": %s", reason); } else { printf(" (%s): %s", etheraddr_string(pmh->sa), reason); } */ cbs->Handle80211MgmtDeauth(*this, pmh, &pbody); return 1; } /********************************************************************************* * Print Body funcs *********************************************************************************/ /** Decode a management request. * @return 0 - failure, non-zero success * * NOTE — this function and all that it calls should be handled as methods in WifipcapCallbacks */ int WifiPacket::decode_mgmt_body(u_int16_t fc, struct mgmt_header_t *pmh, const u_char *p, size_t len) { if(debug) std::cerr << "decode_mgmt_body FC_SUBTYPE(fc)="<<(int)FC_SUBTYPE(fc)<<" "; switch (FC_SUBTYPE(fc)) { case ST_ASSOC_REQUEST: return handle_assoc_request(pmh, p, len); case ST_ASSOC_RESPONSE: return handle_assoc_response(pmh, p, len); case ST_REASSOC_REQUEST: return handle_reassoc_request(pmh, p, len); case ST_REASSOC_RESPONSE: return handle_reassoc_response(pmh, p, len); case ST_PROBE_REQUEST: return handle_probe_request(pmh, p, len); case ST_PROBE_RESPONSE: return handle_probe_response(pmh, p, len); case ST_BEACON: return handle_beacon(pmh, p, len); case ST_ATIM: return handle_atim(pmh, p, len); case ST_DISASSOC: return handle_disassoc(pmh, p, len); case ST_AUTH: if (len < 3) { return 0; } if ((p[0] == 0 ) && (p[1] == 0) && (p[2] == 0)) { //printf("Authentication (Shared-Key)-3 "); cbs->Handle80211MgmtAuthSharedKey(*this, pmh, p, len); return 0; } return handle_auth(pmh, p, len); case ST_DEAUTH: return handle_deauth(pmh, p, len); break; default: return 0; } } int WifiPacket::decode_mgmt_frame(const u_char * ptr, size_t len, u_int16_t fc, u_int8_t hdrlen) { mgmt_header_t hdr; u_int16_t seq_ctl; hdr.da = MAC::ether2MAC(ptr + 4); hdr.sa = MAC::ether2MAC(ptr + 10); hdr.bssid = MAC::ether2MAC(ptr + 16); hdr.duration = EXTRACT_LE_16BITS(ptr+2); seq_ctl = pletohs(ptr + 22); hdr.seq = COOK_SEQUENCE_NUMBER(seq_ctl); hdr.frag = COOK_FRAGMENT_NUMBER(seq_ctl); cbs->Handle80211(*this, fc, hdr.sa, hdr.da, MAC::null, MAC::null, ptr, len); int ret = decode_mgmt_body(fc, &hdr, ptr+MGMT_HDRLEN, len-MGMT_HDRLEN); if (ret==0) { cbs->Handle80211Unknown(*this, fc, ptr, len); return 0; } return 0; } int WifiPacket::decode_data_frame(const u_char * ptr, size_t len, u_int16_t fc) { mac_hdr_t hdr; hdr.fc = fc; hdr.duration = EXTRACT_LE_16BITS(ptr+2); hdr.seq_ctl = pletohs(ptr + 22); hdr.seq = COOK_SEQUENCE_NUMBER(hdr.seq_ctl); hdr.frag = COOK_FRAGMENT_NUMBER(hdr.seq_ctl); if(FC_TYPE(fc)==2 && FC_SUBTYPE(fc)==8){ // quality of service? hdr.qos = 1; } size_t hdrlen=0; const MAC address1 = MAC::ether2MAC(ptr+4); const MAC address2 = MAC::ether2MAC(ptr+10); const MAC address3 = MAC::ether2MAC(ptr+16); /* call the 80211 callback data callback */ if (FC_TO_DS(fc)==0 && FC_FROM_DS(fc)==0) { /* ad hoc IBSS */ hdr.da = address1; hdr.sa = address2; hdr.bssid = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataIBSS( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc)==0 && FC_FROM_DS(fc)) { /* from AP to STA */ hdr.da = address1; hdr.bssid = address2; hdr.sa = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataFromAP( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)==0) { /* frame from STA to AP */ hdr.bssid = address1; hdr.sa = address2; hdr.da = address3; hdrlen = DATA_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataToAP( *this, hdr, ptr+hdrlen, len-hdrlen); } else if (FC_TO_DS(fc) && FC_FROM_DS(fc)) { /* WDS */ const MAC address4 = MAC::ether2MAC(ptr+18); hdr.ra = address1; hdr.ta = address2; hdr.da = address3; hdr.sa = address4; hdrlen = DATA_WDS_HDRLEN; if(hdr.qos) hdrlen+=2; cbs->Handle80211( *this, fc, hdr.sa, hdr.da, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211DataWDS( *this, hdr, ptr+hdrlen, len-hdrlen); } /* Handle either the WEP or the link layer. This handles the data itself */ if (FC_WEP(fc)) { handle_wep(ptr+hdrlen, len-hdrlen-4 ); } else { handle_llc(hdr, ptr+hdrlen, len-hdrlen-4, fc); } return 0; } int WifiPacket::decode_ctrl_frame(const u_char * ptr, size_t len, u_int16_t fc) { u_int16_t du = EXTRACT_LE_16BITS(ptr+2); //duration switch (FC_SUBTYPE(fc)) { case CTRL_PS_POLL: { ctrl_ps_poll_t hdr; hdr.fc = fc; hdr.aid = du; hdr.bssid = MAC::ether2MAC(ptr+4); hdr.ta = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, hdr.ta, ptr, len); cbs->Handle80211CtrlPSPoll( *this, &hdr); break; } case CTRL_RTS: { ctrl_rts_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.ta = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, hdr.ta, ptr, len); cbs->Handle80211CtrlRTS( *this, &hdr); break; } case CTRL_CTS: { ctrl_cts_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlCTS( *this, &hdr); break; } case CTRL_ACK: { ctrl_ack_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlAck( *this, &hdr); break; } case CTRL_CF_END: { ctrl_end_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.bssid = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlCFEnd( *this, &hdr); break; } case CTRL_END_ACK: { ctrl_end_ack_t hdr; hdr.fc = fc; hdr.duration = du; hdr.ra = MAC::ether2MAC(ptr+4); hdr.bssid = MAC::ether2MAC(ptr+10); cbs->Handle80211( *this, fc, MAC::null, MAC::null, hdr.ra, MAC::null, ptr, len); cbs->Handle80211CtrlEndAck( *this, &hdr); break; } default: { cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, MAC::null, ptr, len); cbs->Handle80211Unknown( *this, fc, ptr, len); return -1; //add the case statements for QoS control frames once ieee802_11.h is updated } } return 0; } #ifndef roundup2 #define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ #endif void WifiPacket::handle_80211(const u_char * pkt, size_t len /* , int pad */) { if (debug) std::cerr << "handle_80211(len= " << len << " "; if (len < 2) { cbs->Handle80211( *this, 0, MAC::null, MAC::null, MAC::null, MAC::null, pkt, len); cbs->Handle80211Unknown( *this, -1, pkt, len); return; } u_int16_t fc = EXTRACT_LE_16BITS(pkt); //frame control size_t hdrlen = extract_header_length(fc); /* if (pad) { hdrlen = roundup2(hdrlen, 4); } */ if (debug) std::cerr << "FC_TYPE(fc)= " << FC_TYPE(fc) << " "; if (len < IEEE802_11_FC_LEN || len < hdrlen) { cbs->Handle80211Unknown( *this, fc, pkt, len); return; } /* Always calculate the frame checksum, but only process the packets if the FCS or if we are ignoring it */ if (len >= hdrlen + 4) { // assume fcs is last 4 bytes (?) u_int32_t fcs_sent = EXTRACT_32BITS(pkt+len-4); u_int32_t fcs = crc32_802(pkt, len-4); /* if (fcs != fcs_sent) { cerr << "bad fcs: "; fprintf (stderr, "%08x != %08x\n", fcs_sent, fcs); } */ fcs_ok = (fcs == fcs_sent); } if (cbs->Check80211FCS(*this) && fcs_ok==false){ cbs->Handle80211Unknown(*this,fc,pkt,len); return; } // fill in current_frame: type, sn switch (FC_TYPE(fc)) { case T_MGMT: if(decode_mgmt_frame(pkt, len, fc, hdrlen)<0) return; break; case T_DATA: if(decode_data_frame(pkt, len, fc)<0) return; break; case T_CTRL: if(decode_ctrl_frame(pkt, len, fc)<0) return; break; default: cbs->Handle80211( *this, fc, MAC::null, MAC::null, MAC::null, MAC::null, pkt, len); cbs->Handle80211Unknown( *this, fc, pkt, len); return; } } int WifiPacket::print_radiotap_field(struct cpack_state *s, u_int32_t bit, int *pad, radiotap_hdr *hdr) { union { int8_t i8; u_int8_t u8; int16_t i16; u_int16_t u16; u_int32_t u32; u_int64_t u64; } u, u2, u3; int rc; switch (bit) { case IEEE80211_RADIOTAP_FLAGS: rc = cpack_uint8(s, &u.u8); if (u.u8 & IEEE80211_RADIOTAP_F_DATAPAD) *pad = 1; break; case IEEE80211_RADIOTAP_RATE: case IEEE80211_RADIOTAP_DB_ANTSIGNAL: case IEEE80211_RADIOTAP_DB_ANTNOISE: case IEEE80211_RADIOTAP_ANTENNA: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: case IEEE80211_RADIOTAP_DBM_ANTNOISE: rc = cpack_int8(s, &u.i8); break; case IEEE80211_RADIOTAP_CHANNEL: rc = cpack_uint16(s, &u.u16); if (rc != 0) break; rc = cpack_uint16(s, &u2.u16); break; case IEEE80211_RADIOTAP_FHSS: case IEEE80211_RADIOTAP_LOCK_QUALITY: case IEEE80211_RADIOTAP_TX_ATTENUATION: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DBM_TX_POWER: rc = cpack_int8(s, &u.i8); break; case IEEE80211_RADIOTAP_TSFT: rc = cpack_uint64(s, &u.u64); break; case IEEE80211_RADIOTAP_RX_FLAGS: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_TX_FLAGS: rc = cpack_uint16(s, &u.u16); break; case IEEE80211_RADIOTAP_RTS_RETRIES: rc = cpack_uint8(s, &u.u8); break; case IEEE80211_RADIOTAP_DATA_RETRIES: rc = cpack_uint8(s, &u.u8); break; // simson add follows: case IEEE80211_RADIOTAP_XCHANNEL: rc = cpack_uint8(s, &u.u8); // simson guess break; case IEEE80211_RADIOTAP_MCS: rc = cpack_uint8(s, &u.u8) || cpack_uint8(s, &u2.u8) || cpack_uint8(s, &u3.u8); // simson guess break; // simson end default: /* this bit indicates a field whose * size we do not know, so we cannot * proceed. */ //printf("[0x%08x] ", bit); fprintf(stderr, "wifipcap: unknown radiotap bit: %d (%d)\n", bit,IEEE80211_RADIOTAP_XCHANNEL); return -1 ; } if (rc != 0) { //printf("[|802.11]"); fprintf(stderr, "wifipcap: truncated radiotap header for bit: %d\n", bit); return rc ; } switch (bit) { case IEEE80211_RADIOTAP_CHANNEL: //printf("%u MHz ", u.u16); if (u2.u16 != 0) //printf("(0x%04x) ", u2.u16); hdr->has_channel = true; hdr->channel = u2.u16; break; case IEEE80211_RADIOTAP_FHSS: //printf("fhset %d fhpat %d ", u.u16 & 0xff, (u.u16 >> 8) & 0xff); hdr->has_fhss = true; hdr->fhss_fhset = u.u16 & 0xff; hdr->fhss_fhpat = (u.u16 >> 8) & 0xff; break; case IEEE80211_RADIOTAP_RATE: //PRINT_RATE("", u.u8, " Mb/s "); hdr->has_rate = true; hdr->rate = u.u8; break; case IEEE80211_RADIOTAP_DBM_ANTSIGNAL: //printf("%ddB signal ", u.i8); hdr->has_signal_dbm = true; hdr->signal_dbm = u.i8; break; case IEEE80211_RADIOTAP_DBM_ANTNOISE: //printf("%ddB noise ", u.i8); hdr->has_noise_dbm = true; hdr->noise_dbm = u.i8; break; case IEEE80211_RADIOTAP_DB_ANTSIGNAL: //printf("%ddB signal ", u.u8); hdr->has_signal_db = true; hdr->signal_db = u.u8; break; case IEEE80211_RADIOTAP_DB_ANTNOISE: //printf("%ddB noise ", u.u8); hdr->has_noise_db = true; hdr->noise_db = u.u8; break; case IEEE80211_RADIOTAP_LOCK_QUALITY: //printf("%u sq ", u.u16); hdr->has_quality = true; hdr->quality = u.u16; break; case IEEE80211_RADIOTAP_TX_ATTENUATION: //printf("%d tx power ", -(int)u.u16); hdr->has_txattenuation = true; hdr->txattenuation = -(int)u.u16; break; case IEEE80211_RADIOTAP_DB_TX_ATTENUATION: //printf("%ddB tx power ", -(int)u.u8); hdr->has_txattenuation_db = true; hdr->txattenuation_db = -(int)u.u8; break; case IEEE80211_RADIOTAP_DBM_TX_POWER: //printf("%ddBm tx power ", u.i8); hdr->has_txpower_dbm = true; hdr->txpower_dbm = u.i8; break; case IEEE80211_RADIOTAP_FLAGS: hdr->has_flags = true; if (u.u8 & IEEE80211_RADIOTAP_F_CFP) //printf("cfp "); hdr->flags_cfp = true; if (u.u8 & IEEE80211_RADIOTAP_F_SHORTPRE) //printf("short preamble "); hdr->flags_short_preamble = true; if (u.u8 & IEEE80211_RADIOTAP_F_WEP) //printf("wep "); hdr->flags_wep = true; if (u.u8 & IEEE80211_RADIOTAP_F_FRAG) //printf("fragmented "); hdr->flags_fragmented = true; if (u.u8 & IEEE80211_RADIOTAP_F_BADFCS) //printf("bad-fcs "); hdr->flags_badfcs = true; break; case IEEE80211_RADIOTAP_ANTENNA: //printf("antenna %d ", u.u8); hdr->has_antenna = true; hdr->antenna = u.u8; break; case IEEE80211_RADIOTAP_TSFT: //printf("%" PRIu64 "us tsft ", u.u64); hdr->has_tsft = true; hdr->tsft = u.u64; break; case IEEE80211_RADIOTAP_RX_FLAGS: hdr->has_rxflags = true; hdr->rxflags = u.u16; break; case IEEE80211_RADIOTAP_TX_FLAGS: hdr->has_txflags = true; hdr->txflags = u.u16; break; case IEEE80211_RADIOTAP_RTS_RETRIES: hdr->has_rts_retries = true; hdr->rts_retries = u.u8; break; case IEEE80211_RADIOTAP_DATA_RETRIES: hdr->has_data_retries = true; hdr->data_retries = u.u8; break; } return 0 ; } void WifiPacket::handle_radiotap(const u_char *p,size_t caplen) { #define BITNO_32(x) (((x) >> 16) ? 16 + BITNO_16((x) >> 16) : BITNO_16((x))) #define BITNO_16(x) (((x) >> 8) ? 8 + BITNO_8((x) >> 8) : BITNO_8((x))) #define BITNO_8(x) (((x) >> 4) ? 4 + BITNO_4((x) >> 4) : BITNO_4((x))) #define BITNO_4(x) (((x) >> 2) ? 2 + BITNO_2((x) >> 2) : BITNO_2((x))) #define BITNO_2(x) (((x) & 2) ? 1 : 0) #define BIT(n) (1 << n) #define IS_EXTENDED(__p) (EXTRACT_LE_32BITS(__p) & BIT(IEEE80211_RADIOTAP_EXT)) != 0 // If caplen is too small, just give it a try and carry on. if (caplen < sizeof(struct ieee80211_radiotap_header)) { cbs->HandleRadiotap( *this, NULL, p, caplen); return; } struct ieee80211_radiotap_header *hdr = (struct ieee80211_radiotap_header *)p; size_t len = EXTRACT_LE_16BITS(&hdr->it_len); // length of radiotap header if (caplen < len) { //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } uint32_t *last_presentp=0; for (last_presentp = &hdr->it_present; IS_EXTENDED(last_presentp) && (u_char*)(last_presentp + 1) <= p + len; last_presentp++){ } /* are there more bitmap extensions than bytes in header? */ if (IS_EXTENDED(last_presentp)) { //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } const u_char *iter = (u_char*)(last_presentp + 1); struct cpack_state cpacker; if (cpack_init(&cpacker, (u_int8_t*)iter, len - (iter - p)) != 0) { /* XXX */ //printf("[|802.11]"); cbs->HandleRadiotap( *this, NULL, p, caplen); return;// caplen; } radiotap_hdr ohdr; memset(&ohdr, 0, sizeof(ohdr)); /* Assume no Atheros padding between 802.11 header and body */ int pad = 0; uint32_t *presentp; int bit0=0; for (bit0 = 0, presentp = &hdr->it_present; presentp <= last_presentp; presentp++, bit0 += 32) { u_int32_t present, next_present; for (present = EXTRACT_LE_32BITS(presentp); present; present = next_present) { /* clear the least significant bit that is set */ next_present = present & (present - 1); /* extract the least significant bit that is set */ enum ieee80211_radiotap_type bit = (enum ieee80211_radiotap_type) (bit0 + BITNO_32(present ^ next_present)); /* print the next radiotap field */ int r = print_radiotap_field(&cpacker, bit, &pad, &ohdr); /* If we got an error, break both loops */ if(r!=0) goto done; } } done:; cbs->HandleRadiotap( *this, &ohdr, p, caplen); //return len + ieee802_11_print(p + len, length - len, caplen - len, pad); #undef BITNO_32 #undef BITNO_16 #undef BITNO_8 #undef BITNO_4 #undef BITNO_2 #undef BIT handle_80211(p+len, caplen-len); } void WifiPacket::handle_prism(const u_char *pc, size_t len) { prism2_pkthdr hdr; /* get the fields */ if (len>=144){ hdr.host_time = EXTRACT_LE_32BITS(pc+32); hdr.mac_time = EXTRACT_LE_32BITS(pc+44); hdr.channel = EXTRACT_LE_32BITS(pc+56); hdr.rssi = EXTRACT_LE_32BITS(pc+68); hdr.sq = EXTRACT_LE_32BITS(pc+80); hdr.signal = EXTRACT_LE_32BITS(pc+92); hdr.noise = EXTRACT_LE_32BITS(pc+104); hdr.rate = EXTRACT_LE_32BITS(pc+116)/2; hdr.istx = EXTRACT_LE_32BITS(pc+128); cbs->HandlePrism( *this, &hdr, pc + 144, len - 144); handle_80211(pc+144,len-144); } } /////////////////////////////////////////////////////////////////////////////// /// /// handle_*: /// handle each of the packet types /// /// 2018-08-02: slg - I'm not sure why this is commented out. void WifiPacket::handle_ether(const u_char *ptr, size_t len) { #if 0 ether_hdr_t hdr; hdr.da = MAC::ether2MAC(ptr); hdr.sa = MAC::ether2MAC(ptr+6); hdr.type = EXTRACT_16BITS(ptr + 12); ptr += 14; len -= 14; cbs->HandleEthernet(*this, &hdr, ptr, len); switch (hdr.type) { case ETHERTYPE_IP: handle_ip(ptr, len); return; case ETHERTYPE_IPV6: handle_ip6(ptr, len); return; case ETHERTYPE_ARP: handle_arp( ptr, len); return; default: cbs->HandleL2Unknown(*this, hdr.type, ptr, len); return; } #endif } /////////////////////////////////////////////////////////////////////////////// /* These are all static functions */ #if 0 void Wifipcap::dl_prism(const PcapUserData &data, const struct pcap_pkthdr *header, const u_char * packet) { WifipcapCallbacks *cbs = data.cbs; if(header->caplen < 144) return; // prism header cbs->PacketBegin( packet, header->caplen, header->len); handle_prism(cbs,packet+144,header->caplen-144); cbs->PacketEnd(); } void Wifipcap::dl_prism(u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { PcapUserData *data = reinterpret_cast<PcapUserData *>(user); Wifipcap::dl_prism(*data,header,packet); } #endif #if 0 void Wifipcap::dl_ieee802_11_radio(const PcapUserData &data, const struct pcap_pkthdr *header, const u_char * packet) { data.cbs->PacketBegin( packet, header->caplen, header->len); handle_radiotap(packet, header->caplen); data.cbs->PacketEnd(); } #endif void Wifipcap::dl_ieee802_11_radio(const u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { const PcapUserData *data = reinterpret_cast<const PcapUserData *>(user); WifiPacket pkt(data->cbs,data->header_type,header,packet); data->cbs->PacketBegin(pkt,packet,header->caplen,header->len); pkt.handle_radiotap(packet,header->caplen); data->cbs->PacketEnd(pkt); //Wifipcap::dl_ieee802_11_radio(*data,header,packet); } /////////////////////////////////////////////////////////////////////////////// /* None of these are used in tcpflow */ bool Wifipcap::InitNext() { if (morefiles.size() < 1){ return false; } if (descr) { pcap_close(descr); } Init(morefiles.front(), false); morefiles.pop_front(); return true; } void Wifipcap::Init(const char *name, bool live) { if (verbose){ std::cerr << "wifipcap: initializing '" << name << "'" << std::endl; } if (!live) { #ifdef _WIN32 std::cerr << "Trace replay is unsupported in windows." << std::endl; exit(1); #else // mini hack: handle gziped files since all our traces are in // this format int slen = strlen(name); bool gzip = !strcmp(name+slen-3, ".gz"); bool bzip = !strcmp(name+slen-4, ".bz2"); char cmd[256]; char errbuf[256]; if (gzip) sprintf(cmd, "zcat %s", name); else if (bzip) sprintf(cmd, "bzcat %s", name); else // using cat here instead of pcap_open or fopen is intentional // neither of these may be able to handle large files (>2GB files) // but cat uses the linux routines to allow it to sprintf(cmd, "cat %s", name); FILE *pipe = popen(cmd, "r"); if (pipe == NULL) { printf("popen(): %s\n", strerror(errno)); exit(1); } descr = pcap_fopen_offline(pipe, errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n", errbuf); exit(1); } #endif } else { char errbuf[256]; descr = pcap_open_live(name,BUFSIZ,1,-1,errbuf); if(descr == NULL) { printf("pcap_open_live(): %s\n", errbuf); exit(1); } } datalink = pcap_datalink(descr); if (datalink != DLT_PRISM_HEADER && datalink != DLT_IEEE802_11_RADIO && datalink != DLT_IEEE802_11) { if (datalink == DLT_EN10MB) { printf("warning: ethernet datalink type: %s\n", pcap_datalink_val_to_name(datalink)); } else { printf("warning: unrecognized datalink type: %s\n", pcap_datalink_val_to_name(datalink)); } } } /* object-oriented version of pcap callback. Called with the callbacks object, * the DLT type, the header and the packet. * This is the main packet processor. * It records some stats and then dispatches to the appropriate callback. */ void Wifipcap::handle_packet(WifipcapCallbacks *cbs,int header_type, const struct pcap_pkthdr *header, const u_char * packet) { /* Record start time if we don't have it */ if (startTime == TIME_NONE) { startTime = header->ts; lastPrintTime = header->ts; } /* Print stats if necessary */ if (header->ts.tv_sec > lastPrintTime.tv_sec + Wifipcap::PRINT_TIME_INTERVAL) { if (verbose) { int hours = (header->ts.tv_sec - startTime.tv_sec)/3600; int days = hours/24; int left = hours%24; fprintf(stderr, "wifipcap: %2d days %2d hours, %10" PRId64 " pkts\n", days, left, packetsProcessed); } lastPrintTime = header->ts; } packetsProcessed++; /* Create the packet object and call the appropriate callbacks */ WifiPacket pkt(cbs,header_type,header,packet); /* Notify callback */ cbs->PacketBegin(pkt, packet, header->caplen, header->len); //int frameLen = header->caplen; switch(header_type) { case DLT_PRISM_HEADER: pkt.handle_prism(packet,header->caplen); break; case DLT_IEEE802_11_RADIO: pkt.handle_radiotap(packet,header->caplen); break; case DLT_IEEE802_11: pkt.handle_80211(packet,header->caplen); break; case DLT_EN10MB: pkt.handle_ether(packet,header->caplen); break; default: #if 0 /// 2018-08-02: slg - I'm also not sure why this is commented out. // try handling it as default IP assuming framing is ethernet // (this is for testing) pkt.handle_ip(packet,header->caplen); #endif break; } cbs->PacketEnd(pkt); } /* The raw callback from pcap; jump back into the object-oriented domain */ /* note: u_char *user may not be const according to spec */ void Wifipcap::handle_packet_callback(u_char *user, const struct pcap_pkthdr *header, const u_char * packet) { Wifipcap::PcapUserData *data = reinterpret_cast<Wifipcap::PcapUserData *>(user); data->wcap->handle_packet(data->cbs,data->header_type,header,packet); } const char *Wifipcap::SetFilter(const char *filter) { struct bpf_program fp; #ifdef PCAP_NETMASK_UNKNOWN bpf_u_int32 netp=PCAP_NETMASK_UNKNOWN; #else bpf_u_int32 netp=0; #endif if(pcap_compile(descr,&fp,(char *)filter,0,netp) == -1) { return "Error calling pcap_compile"; } if(pcap_setfilter(descr,&fp) == -1) { return "Error setting filter"; } return NULL; } void Wifipcap::Run(WifipcapCallbacks *cbs, int maxpkts) { /* NOTE: This needs to be fixed so that the correct handle_packet is called */ packetsProcessed = 0; do { PcapUserData data(this,cbs,DLT_IEEE802_11_RADIO); pcap_loop(descr, maxpkts > 0 ? maxpkts - packetsProcessed : 0, Wifipcap::handle_packet_callback, reinterpret_cast<u_char *>(&data)); } while ( InitNext() ); } ///////////////////////////////////////////////////////////////////////////////
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_291_0
crossvul-cpp_data_bad_583_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, unsigned count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD else if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF; for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if(width>768 || raw_width>768 || height > 512 || raw_height>512 ) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; if(col>=0) FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* extra room for data stored w/o predictor */ int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float libraw_powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * libraw_powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; #ifdef LIBRAW_LIBRARY_BUILD if(offset>ifp->size()-8) // At least 8 bytes for tag/len offset = ifp->size()-8; #endif while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); if(len < 0) return; // just ignore wrong len?? or raise bad file exception? switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64(2.0f, -int_to_float((get4(),get4()))); aperture = libraw_powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = libraw_powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 { ushort q = get2(); cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024; } if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; if ((int)size < 0) return; // 2+GB is too much if (save + size < save) return; // 32bit overflow fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // data length should be in range w*h..w*h*2 if(width*height < (LIBRAW_MAX_ALLOC_MB*1024*512L) && width*height>1 && i >= width * height && i <= width*height*2) { #endif switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD } else is_raw = 0; #endif } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ( (int)width + (int)left_margin > 65535) || ( (int)height + (int)top_margin > 65535) ) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_583_1
crossvul-cpp_data_good_434_1
// © 2017 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include <cstdlib> #include <cmath> #include <limits> #include <stdlib.h> #include "unicode/plurrule.h" #include "cmemory.h" #include "number_decnum.h" #include "putilimp.h" #include "number_decimalquantity.h" #include "number_roundingutils.h" #include "double-conversion.h" #include "charstr.h" #include "number_utils.h" #include "uassert.h" using namespace icu; using namespace icu::number; using namespace icu::number::impl; using icu::double_conversion::DoubleToStringConverter; using icu::double_conversion::StringToDoubleConverter; namespace { int8_t NEGATIVE_FLAG = 1; int8_t INFINITY_FLAG = 2; int8_t NAN_FLAG = 4; /** Helper function for safe subtraction (no overflow). */ inline int32_t safeSubtract(int32_t a, int32_t b) { // Note: In C++, signed integer subtraction is undefined behavior. int32_t diff = static_cast<int32_t>(static_cast<uint32_t>(a) - static_cast<uint32_t>(b)); if (b < 0 && diff < a) { return INT32_MAX; } if (b > 0 && diff > a) { return INT32_MIN; } return diff; } static double DOUBLE_MULTIPLIERS[] = { 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20, 1e21}; } // namespace icu::IFixedDecimal::~IFixedDecimal() = default; DecimalQuantity::DecimalQuantity() { setBcdToZero(); flags = 0; } DecimalQuantity::~DecimalQuantity() { if (usingBytes) { uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; usingBytes = false; } } DecimalQuantity::DecimalQuantity(const DecimalQuantity &other) { *this = other; } DecimalQuantity::DecimalQuantity(DecimalQuantity&& src) U_NOEXCEPT { *this = std::move(src); } DecimalQuantity &DecimalQuantity::operator=(const DecimalQuantity &other) { if (this == &other) { return *this; } copyBcdFrom(other); copyFieldsFrom(other); return *this; } DecimalQuantity& DecimalQuantity::operator=(DecimalQuantity&& src) U_NOEXCEPT { if (this == &src) { return *this; } moveBcdFrom(src); copyFieldsFrom(src); return *this; } void DecimalQuantity::copyFieldsFrom(const DecimalQuantity& other) { bogus = other.bogus; lOptPos = other.lOptPos; lReqPos = other.lReqPos; rReqPos = other.rReqPos; rOptPos = other.rOptPos; scale = other.scale; precision = other.precision; flags = other.flags; origDouble = other.origDouble; origDelta = other.origDelta; isApproximate = other.isApproximate; } void DecimalQuantity::clear() { lOptPos = INT32_MAX; lReqPos = 0; rReqPos = 0; rOptPos = INT32_MIN; flags = 0; setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data } void DecimalQuantity::setIntegerLength(int32_t minInt, int32_t maxInt) { // Validation should happen outside of DecimalQuantity, e.g., in the Precision class. U_ASSERT(minInt >= 0); U_ASSERT(maxInt >= minInt); // Special behavior: do not set minInt to be less than what is already set. // This is so significant digits rounding can set the integer length. if (minInt < lReqPos) { minInt = lReqPos; } // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE lOptPos = maxInt; lReqPos = minInt; } void DecimalQuantity::setFractionLength(int32_t minFrac, int32_t maxFrac) { // Validation should happen outside of DecimalQuantity, e.g., in the Precision class. U_ASSERT(minFrac >= 0); U_ASSERT(maxFrac >= minFrac); // Save values into internal state // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE rReqPos = -minFrac; rOptPos = -maxFrac; } uint64_t DecimalQuantity::getPositionFingerprint() const { uint64_t fingerprint = 0; fingerprint ^= lOptPos; fingerprint ^= (lReqPos << 16); fingerprint ^= (static_cast<uint64_t>(rReqPos) << 32); fingerprint ^= (static_cast<uint64_t>(rOptPos) << 48); return fingerprint; } void DecimalQuantity::roundToIncrement(double roundingIncrement, RoundingMode roundingMode, int32_t maxFrac, UErrorCode& status) { // TODO(13701): Move the nickel check into a higher-level API. if (roundingIncrement == 0.05) { roundToMagnitude(-2, roundingMode, true, status); roundToMagnitude(-maxFrac, roundingMode, false, status); return; } else if (roundingIncrement == 0.5) { roundToMagnitude(-1, roundingMode, true, status); roundToMagnitude(-maxFrac, roundingMode, false, status); return; } // TODO(13701): This is innefficient. Improve? // TODO(13701): Should we convert to decNumber instead? roundToInfinity(); double temp = toDouble(); temp /= roundingIncrement; // Use another DecimalQuantity to perform the actual rounding... DecimalQuantity dq; dq.setToDouble(temp); dq.roundToMagnitude(0, roundingMode, status); temp = dq.toDouble(); temp *= roundingIncrement; setToDouble(temp); // Since we reset the value to a double, we need to specify the rounding boundary // in order to get the DecimalQuantity out of approximation mode. // NOTE: In Java, we have minMaxFrac, but in C++, the two are differentiated. roundToMagnitude(-maxFrac, roundingMode, status); } void DecimalQuantity::multiplyBy(const DecNum& multiplicand, UErrorCode& status) { if (isInfinite() || isZero() || isNaN()) { return; } // Convert to DecNum, multiply, and convert back. DecNum decnum; toDecNum(decnum, status); if (U_FAILURE(status)) { return; } decnum.multiplyBy(multiplicand, status); if (U_FAILURE(status)) { return; } setToDecNum(decnum, status); } void DecimalQuantity::divideBy(const DecNum& divisor, UErrorCode& status) { if (isInfinite() || isZero() || isNaN()) { return; } // Convert to DecNum, multiply, and convert back. DecNum decnum; toDecNum(decnum, status); if (U_FAILURE(status)) { return; } decnum.divideBy(divisor, status); if (U_FAILURE(status)) { return; } setToDecNum(decnum, status); } void DecimalQuantity::negate() { flags ^= NEGATIVE_FLAG; } int32_t DecimalQuantity::getMagnitude() const { U_ASSERT(precision != 0); return scale + precision - 1; } bool DecimalQuantity::adjustMagnitude(int32_t delta) { if (precision != 0) { // i.e., scale += delta; origDelta += delta bool overflow = uprv_add32_overflow(scale, delta, &scale); overflow = uprv_add32_overflow(origDelta, delta, &origDelta) || overflow; // Make sure that precision + scale won't overflow, either int32_t dummy; overflow = overflow || uprv_add32_overflow(scale, precision, &dummy); return overflow; } return false; } double DecimalQuantity::getPluralOperand(PluralOperand operand) const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. U_ASSERT(!isApproximate); switch (operand) { case PLURAL_OPERAND_I: // Invert the negative sign if necessary return static_cast<double>(isNegative() ? -toLong(true) : toLong(true)); case PLURAL_OPERAND_F: return static_cast<double>(toFractionLong(true)); case PLURAL_OPERAND_T: return static_cast<double>(toFractionLong(false)); case PLURAL_OPERAND_V: return fractionCount(); case PLURAL_OPERAND_W: return fractionCountWithoutTrailingZeros(); default: return std::abs(toDouble()); } } bool DecimalQuantity::hasIntegerValue() const { return scale >= 0; } int32_t DecimalQuantity::getUpperDisplayMagnitude() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); int32_t magnitude = scale + precision; int32_t result = (lReqPos > magnitude) ? lReqPos : (lOptPos < magnitude) ? lOptPos : magnitude; return result - 1; } int32_t DecimalQuantity::getLowerDisplayMagnitude() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); int32_t magnitude = scale; int32_t result = (rReqPos < magnitude) ? rReqPos : (rOptPos > magnitude) ? rOptPos : magnitude; return result; } int8_t DecimalQuantity::getDigit(int32_t magnitude) const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment at the top of this file explaining the "isApproximate" field. U_ASSERT(!isApproximate); return getDigitPos(magnitude - scale); } int32_t DecimalQuantity::fractionCount() const { return -getLowerDisplayMagnitude(); } int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const { return -scale > 0 ? -scale : 0; // max(-scale, 0) } bool DecimalQuantity::isNegative() const { return (flags & NEGATIVE_FLAG) != 0; } int8_t DecimalQuantity::signum() const { return isNegative() ? -1 : isZero() ? 0 : 1; } bool DecimalQuantity::isInfinite() const { return (flags & INFINITY_FLAG) != 0; } bool DecimalQuantity::isNaN() const { return (flags & NAN_FLAG) != 0; } bool DecimalQuantity::isZero() const { return precision == 0; } DecimalQuantity &DecimalQuantity::setToInt(int32_t n) { setBcdToZero(); flags = 0; if (n == INT32_MIN) { flags |= NEGATIVE_FLAG; // leave as INT32_MIN; handled below in _setToInt() } else if (n < 0) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToInt(n); compact(); } return *this; } void DecimalQuantity::_setToInt(int32_t n) { if (n == INT32_MIN) { readLongToBcd(-static_cast<int64_t>(n)); } else { readIntToBcd(n); } } DecimalQuantity &DecimalQuantity::setToLong(int64_t n) { setBcdToZero(); flags = 0; if (n < 0 && n > INT64_MIN) { flags |= NEGATIVE_FLAG; n = -n; } if (n != 0) { _setToLong(n); compact(); } return *this; } void DecimalQuantity::_setToLong(int64_t n) { if (n == INT64_MIN) { DecNum decnum; UErrorCode localStatus = U_ZERO_ERROR; decnum.setTo("9.223372036854775808E+18", localStatus); if (U_FAILURE(localStatus)) { return; } // unexpected flags |= NEGATIVE_FLAG; readDecNumberToBcd(decnum); } else if (n <= INT32_MAX) { readIntToBcd(static_cast<int32_t>(n)); } else { readLongToBcd(n); } } DecimalQuantity &DecimalQuantity::setToDouble(double n) { setBcdToZero(); flags = 0; // signbit() from <math.h> handles +0.0 vs -0.0 if (std::signbit(n)) { flags |= NEGATIVE_FLAG; n = -n; } if (std::isnan(n) != 0) { flags |= NAN_FLAG; } else if (std::isfinite(n) == 0) { flags |= INFINITY_FLAG; } else if (n != 0) { _setToDoubleFast(n); compact(); } return *this; } void DecimalQuantity::_setToDoubleFast(double n) { isApproximate = true; origDouble = n; origDelta = 0; // Make sure the double is an IEEE 754 double. If not, fall back to the slow path right now. // TODO: Make a fast path for other types of doubles. if (!std::numeric_limits<double>::is_iec559) { convertToAccurateDouble(); // Turn off the approximate double flag, since the value is now exact. isApproximate = false; origDouble = 0.0; return; } // To get the bits from the double, use memcpy, which takes care of endianness. uint64_t ieeeBits; uprv_memcpy(&ieeeBits, &n, sizeof(n)); int32_t exponent = static_cast<int32_t>((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff; // Not all integers can be represented exactly for exponent > 52 if (exponent <= 52 && static_cast<int64_t>(n) == n) { _setToLong(static_cast<int64_t>(n)); return; } // 3.3219... is log2(10) auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809489); if (fracLength >= 0) { int32_t i = fracLength; // 1e22 is the largest exact double. for (; i >= 22; i -= 22) n *= 1e22; n *= DOUBLE_MULTIPLIERS[i]; } else { int32_t i = fracLength; // 1e22 is the largest exact double. for (; i <= -22; i += 22) n /= 1e22; n /= DOUBLE_MULTIPLIERS[-i]; } auto result = static_cast<int64_t>(std::round(n)); if (result != 0) { _setToLong(result); scale -= fracLength; } } void DecimalQuantity::convertToAccurateDouble() { U_ASSERT(origDouble != 0); int32_t delta = origDelta; // Call the slow oracle function (Double.toString in Java, DoubleToAscii in C++). char buffer[DoubleToStringConverter::kBase10MaximalLength + 1]; bool sign; // unused; always positive int32_t length; int32_t point; DoubleToStringConverter::DoubleToAscii( origDouble, DoubleToStringConverter::DtoaMode::SHORTEST, 0, buffer, sizeof(buffer), &sign, &length, &point ); setBcdToZero(); readDoubleConversionToBcd(buffer, length, point); scale += delta; explicitExactDouble = true; } DecimalQuantity &DecimalQuantity::setToDecNumber(StringPiece n, UErrorCode& status) { setBcdToZero(); flags = 0; // Compute the decNumber representation DecNum decnum; decnum.setTo(n, status); _setToDecNum(decnum, status); return *this; } DecimalQuantity& DecimalQuantity::setToDecNum(const DecNum& decnum, UErrorCode& status) { setBcdToZero(); flags = 0; _setToDecNum(decnum, status); return *this; } void DecimalQuantity::_setToDecNum(const DecNum& decnum, UErrorCode& status) { if (U_FAILURE(status)) { return; } if (decnum.isNegative()) { flags |= NEGATIVE_FLAG; } if (!decnum.isZero()) { readDecNumberToBcd(decnum); compact(); } } int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const { // NOTE: Call sites should be guarded by fitsInLong(), like this: // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ } // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits. uint64_t result = 0L; int32_t upperMagnitude = std::min(scale + precision, lOptPos) - 1; if (truncateIfOverflow) { upperMagnitude = std::min(upperMagnitude, 17); } for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } if (isNegative()) { return static_cast<int64_t>(0LL - result); // i.e., -result } return static_cast<int64_t>(result); } uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const { uint64_t result = 0L; int32_t magnitude = -1; int32_t lowerMagnitude = std::max(scale, rOptPos); if (includeTrailingZeros) { lowerMagnitude = std::min(lowerMagnitude, rReqPos); } for (; magnitude >= lowerMagnitude && result <= 1e18L; magnitude--) { result = result * 10 + getDigitPos(magnitude - scale); } // Remove trailing zeros; this can happen during integer overflow cases. if (!includeTrailingZeros) { while (result > 0 && (result % 10) == 0) { result /= 10; } } return result; } bool DecimalQuantity::fitsInLong(bool ignoreFraction) const { if (isZero()) { return true; } if (scale < 0 && !ignoreFraction) { return false; } int magnitude = getMagnitude(); if (magnitude < 18) { return true; } if (magnitude > 18) { return false; } // Hard case: the magnitude is 10^18. // The largest int64 is: 9,223,372,036,854,775,807 for (int p = 0; p < precision; p++) { int8_t digit = getDigit(18 - p); static int8_t INT64_BCD[] = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 }; if (digit < INT64_BCD[p]) { return true; } else if (digit > INT64_BCD[p]) { return false; } } // Exactly equal to max long plus one. return isNegative(); } double DecimalQuantity::toDouble() const { // If this assertion fails, you need to call roundToInfinity() or some other rounding method. // See the comment in the header file explaining the "isApproximate" field. U_ASSERT(!isApproximate); if (isNaN()) { return NAN; } else if (isInfinite()) { return isNegative() ? -INFINITY : INFINITY; } // We are processing well-formed input, so we don't need any special options to StringToDoubleConverter. StringToDoubleConverter converter(0, 0, 0, "", ""); UnicodeString numberString = this->toScientificString(); int32_t count; return converter.StringToDouble( reinterpret_cast<const uint16_t*>(numberString.getBuffer()), numberString.length(), &count); } void DecimalQuantity::toDecNum(DecNum& output, UErrorCode& status) const { // Special handling for zero if (precision == 0) { output.setTo("0", status); } // Use the BCD constructor. We need to do a little bit of work to convert, though. // The decNumber constructor expects most-significant first, but we store least-significant first. MaybeStackArray<uint8_t, 20> ubcd(precision); for (int32_t m = 0; m < precision; m++) { ubcd[precision - m - 1] = static_cast<uint8_t>(getDigitPos(m)); } output.setTo(ubcd.getAlias(), precision, scale, isNegative(), status); } void DecimalQuantity::truncate() { if (scale < 0) { shiftRight(-scale); scale = 0; compact(); } } void DecimalQuantity::roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) { roundToMagnitude(magnitude, roundingMode, true, status); } void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) { roundToMagnitude(magnitude, roundingMode, false, status); } void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status) { // The position in the BCD at which rounding will be performed; digits to the right of position // will be rounded away. int position = safeSubtract(magnitude, scale); // "trailing" = least significant digit to the left of rounding int8_t trailingDigit = getDigitPos(position); if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. } else if (precision == 0) { // No rounding for zero. } else { // Perform rounding logic. // "leading" = most significant digit to the right of rounding int8_t leadingDigit = getDigitPos(safeSubtract(position, 1)); // Compute which section of the number we are in. // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles) // LOWER means we are between the bottom edge and the midpoint, like 1.391 // MIDPOINT means we are exactly in the middle, like 1.500 // UPPER means we are between the midpoint and the top edge, like 1.916 roundingutils::Section section; if (!isApproximate) { if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = roundingutils::SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = roundingutils::SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = roundingutils::SECTION_LOWER; } else { // .08, .09 => up to .10 section = roundingutils::SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = roundingutils::SECTION_LOWER; } else if (leadingDigit > 5) { // Includes nickel rounding .026-.029 and .076-.079 section = roundingutils::SECTION_UPPER; } else { // Includes nickel rounding .025 and .075 section = roundingutils::SECTION_MIDPOINT; for (int p = safeSubtract(position, 2); p >= 0; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_UPPER; break; } } } } else { int32_t p = safeSubtract(position, 2); int32_t minP = uprv_max(0, precision - 14); if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { section = roundingutils::SECTION_LOWER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_LOWER; break; } } } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = roundingutils::SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = roundingutils::SECTION_LOWER; break; } } } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) { section = roundingutils::SECTION_MIDPOINT; for (; p >= minP; p--) { if (getDigitPos(p) != 0) { section = roundingutils::SECTION_UPPER; break; } } } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) { section = roundingutils::SECTION_UPPER_EDGE; for (; p >= minP; p--) { if (getDigitPos(p) != 9) { section = roundingutils::SECTION_UPPER; break; } } } else if (nickel && trailingDigit != 2 && trailingDigit != 7) { // Nickel rounding, and not at .02x or .07x if (trailingDigit < 2) { // .00, .01 => down to .00 section = roundingutils::SECTION_LOWER; } else if (trailingDigit < 5) { // .03, .04 => up to .05 section = roundingutils::SECTION_UPPER; } else if (trailingDigit < 7) { // .05, .06 => down to .05 section = roundingutils::SECTION_LOWER; } else { // .08, .09 => up to .10 section = roundingutils::SECTION_UPPER; } } else if (leadingDigit < 5) { // Includes nickel rounding .020-.024 and .070-.074 section = roundingutils::SECTION_LOWER; } else { // Includes nickel rounding .026-.029 and .076-.079 section = roundingutils::SECTION_UPPER; } bool roundsAtMidpoint = roundingutils::roundsAtMidpoint(roundingMode); if (safeSubtract(position, 1) < precision - 14 || (roundsAtMidpoint && section == roundingutils::SECTION_MIDPOINT) || (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) { // Oops! This means that we have to get the exact representation of the double, // because the zone of uncertainty is along the rounding boundary. convertToAccurateDouble(); roundToMagnitude(magnitude, roundingMode, nickel, status); // start over return; } // Turn off the approximate double flag, since the value is now confirmed to be exact. isApproximate = false; origDouble = 0.0; origDelta = 0; if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) { // All digits are to the left of the rounding magnitude. return; } // Good to continue rounding. if (section == -1) { section = roundingutils::SECTION_LOWER; } if (section == -2) { section = roundingutils::SECTION_UPPER; } } // Nickel rounding "half even" goes to the nearest whole (away from the 5). bool isEven = nickel ? (trailingDigit < 2 || trailingDigit > 7 || (trailingDigit == 2 && section != roundingutils::SECTION_UPPER) || (trailingDigit == 7 && section == roundingutils::SECTION_UPPER)) : (trailingDigit % 2) == 0; bool roundDown = roundingutils::getRoundingDirection(isEven, isNegative(), section, roundingMode, status); if (U_FAILURE(status)) { return; } // Perform truncation if (position >= precision) { setBcdToZero(); scale = magnitude; } else { shiftRight(position); } if (nickel) { if (trailingDigit < 5 && roundDown) { setDigitPos(0, 0); compact(); return; } else if (trailingDigit >= 5 && !roundDown) { setDigitPos(0, 9); trailingDigit = 9; // do not return: use the bubbling logic below } else { setDigitPos(0, 5); // compact not necessary: digit at position 0 is nonzero return; } } // Bubble the result to the higher digits if (!roundDown) { if (trailingDigit == 9) { int bubblePos = 0; // Note: in the long implementation, the most digits BCD can have at this point is // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe. for (; getDigitPos(bubblePos) == 9; bubblePos++) {} shiftRight(bubblePos); // shift off the trailing 9s } int8_t digit0 = getDigitPos(0); U_ASSERT(digit0 != 9); setDigitPos(0, static_cast<int8_t>(digit0 + 1)); precision += 1; // in case an extra digit got added } compact(); } } void DecimalQuantity::roundToInfinity() { if (isApproximate) { convertToAccurateDouble(); } } void DecimalQuantity::appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger) { U_ASSERT(leadingZeros >= 0); // Zero requires special handling to maintain the invariant that the least-significant digit // in the BCD is nonzero. if (value == 0) { if (appendAsInteger && precision != 0) { scale += leadingZeros + 1; } return; } // Deal with trailing zeros if (scale > 0) { leadingZeros += scale; if (appendAsInteger) { scale = 0; } } // Append digit shiftLeft(leadingZeros + 1); setDigitPos(0, value); // Fix scale if in integer mode if (appendAsInteger) { scale += leadingZeros + 1; } } UnicodeString DecimalQuantity::toPlainString() const { U_ASSERT(!isApproximate); UnicodeString sb; if (isNegative()) { sb.append(u'-'); } if (precision == 0 || getMagnitude() < 0) { sb.append(u'0'); } for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (m == -1) { sb.append(u'.'); } sb.append(getDigit(m) + u'0'); } return sb; } UnicodeString DecimalQuantity::toScientificString() const { U_ASSERT(!isApproximate); UnicodeString result; if (isNegative()) { result.append(u'-'); } if (precision == 0) { result.append(u"0E+0", -1); return result; } // NOTE: It is not safe to add to lOptPos (aka maxInt) or subtract from // rOptPos (aka -maxFrac) due to overflow. int32_t upperPos = std::min(precision + scale, lOptPos) - scale - 1; int32_t lowerPos = std::max(scale, rOptPos) - scale; int32_t p = upperPos; result.append(u'0' + getDigitPos(p)); if ((--p) >= lowerPos) { result.append(u'.'); for (; p >= lowerPos; p--) { result.append(u'0' + getDigitPos(p)); } } result.append(u'E'); int32_t _scale = upperPos + scale; if (_scale == INT32_MIN) { result.append({u"-2147483648", -1}); return result; } else if (_scale < 0) { _scale *= -1; result.append(u'-'); } else { result.append(u'+'); } if (_scale == 0) { result.append(u'0'); } int32_t insertIndex = result.length(); while (_scale > 0) { std::div_t res = std::div(_scale, 10); result.insert(insertIndex, u'0' + res.rem); _scale = res.quot; } return result; } //////////////////////////////////////////////////// /// End of DecimalQuantity_AbstractBCD.java /// /// Start of DecimalQuantity_DualStorageBCD.java /// //////////////////////////////////////////////////// int8_t DecimalQuantity::getDigitPos(int32_t position) const { if (usingBytes) { if (position < 0 || position >= precision) { return 0; } return fBCD.bcdBytes.ptr[position]; } else { if (position < 0 || position >= 16) { return 0; } return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf); } } void DecimalQuantity::setDigitPos(int32_t position, int8_t value) { U_ASSERT(position >= 0); if (usingBytes) { ensureCapacity(position + 1); fBCD.bcdBytes.ptr[position] = value; } else if (position >= 16) { switchStorage(); ensureCapacity(position + 1); fBCD.bcdBytes.ptr[position] = value; } else { int shift = position * 4; fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift); } } void DecimalQuantity::shiftLeft(int32_t numDigits) { if (!usingBytes && precision + numDigits > 16) { switchStorage(); } if (usingBytes) { ensureCapacity(precision + numDigits); int i = precision + numDigits - 1; for (; i >= numDigits; i--) { fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i - numDigits]; } for (; i >= 0; i--) { fBCD.bcdBytes.ptr[i] = 0; } } else { fBCD.bcdLong <<= (numDigits * 4); } scale -= numDigits; precision += numDigits; } void DecimalQuantity::shiftRight(int32_t numDigits) { if (usingBytes) { int i = 0; for (; i < precision - numDigits; i++) { fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i + numDigits]; } for (; i < precision; i++) { fBCD.bcdBytes.ptr[i] = 0; } } else { fBCD.bcdLong >>= (numDigits * 4); } scale += numDigits; precision -= numDigits; } void DecimalQuantity::setBcdToZero() { if (usingBytes) { uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; usingBytes = false; } fBCD.bcdLong = 0L; scale = 0; precision = 0; isApproximate = false; origDouble = 0; origDelta = 0; } void DecimalQuantity::readIntToBcd(int32_t n) { U_ASSERT(n != 0); // ints always fit inside the long implementation. uint64_t result = 0L; int i = 16; for (; n != 0; n /= 10, i--) { result = (result >> 4) + ((static_cast<uint64_t>(n) % 10) << 60); } U_ASSERT(!usingBytes); fBCD.bcdLong = result >> (i * 4); scale = 0; precision = 16 - i; } void DecimalQuantity::readLongToBcd(int64_t n) { U_ASSERT(n != 0); if (n >= 10000000000000000L) { ensureCapacity(); int i = 0; for (; n != 0L; n /= 10L, i++) { fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(n % 10); } U_ASSERT(usingBytes); scale = 0; precision = i; } else { uint64_t result = 0L; int i = 16; for (; n != 0L; n /= 10L, i--) { result = (result >> 4) + ((n % 10) << 60); } U_ASSERT(i >= 0); U_ASSERT(!usingBytes); fBCD.bcdLong = result >> (i * 4); scale = 0; precision = 16 - i; } } void DecimalQuantity::readDecNumberToBcd(const DecNum& decnum) { const decNumber* dn = decnum.getRawDecNumber(); if (dn->digits > 16) { ensureCapacity(dn->digits); for (int32_t i = 0; i < dn->digits; i++) { fBCD.bcdBytes.ptr[i] = dn->lsu[i]; } } else { uint64_t result = 0L; for (int32_t i = 0; i < dn->digits; i++) { result |= static_cast<uint64_t>(dn->lsu[i]) << (4 * i); } fBCD.bcdLong = result; } scale = dn->exponent; precision = dn->digits; } void DecimalQuantity::readDoubleConversionToBcd( const char* buffer, int32_t length, int32_t point) { // NOTE: Despite the fact that double-conversion's API is called // "DoubleToAscii", they actually use '0' (as opposed to u8'0'). if (length > 16) { ensureCapacity(length); for (int32_t i = 0; i < length; i++) { fBCD.bcdBytes.ptr[i] = buffer[length-i-1] - '0'; } } else { uint64_t result = 0L; for (int32_t i = 0; i < length; i++) { result |= static_cast<uint64_t>(buffer[length-i-1] - '0') << (4 * i); } fBCD.bcdLong = result; } scale = point - length; precision = length; } void DecimalQuantity::compact() { if (usingBytes) { int32_t delta = 0; for (; delta < precision && fBCD.bcdBytes.ptr[delta] == 0; delta++); if (delta == precision) { // Number is zero setBcdToZero(); return; } else { // Remove trailing zeros shiftRight(delta); } // Compute precision int32_t leading = precision - 1; for (; leading >= 0 && fBCD.bcdBytes.ptr[leading] == 0; leading--); precision = leading + 1; // Switch storage mechanism if possible if (precision <= 16) { switchStorage(); } } else { if (fBCD.bcdLong == 0L) { // Number is zero setBcdToZero(); return; } // Compact the number (remove trailing zeros) // TODO: Use a more efficient algorithm here and below. There is a logarithmic one. int32_t delta = 0; for (; delta < precision && getDigitPos(delta) == 0; delta++); fBCD.bcdLong >>= delta * 4; scale += delta; // Compute precision int32_t leading = precision - 1; for (; leading >= 0 && getDigitPos(leading) == 0; leading--); precision = leading + 1; } } void DecimalQuantity::ensureCapacity() { ensureCapacity(40); } void DecimalQuantity::ensureCapacity(int32_t capacity) { if (capacity == 0) { return; } int32_t oldCapacity = usingBytes ? fBCD.bcdBytes.len : 0; if (!usingBytes) { // TODO: There is nothing being done to check for memory allocation failures. // TODO: Consider indexing by nybbles instead of bytes in C++, so that we can // make these arrays half the size. fBCD.bcdBytes.ptr = static_cast<int8_t*>(uprv_malloc(capacity * sizeof(int8_t))); fBCD.bcdBytes.len = capacity; // Initialize the byte array to zeros (this is done automatically in Java) uprv_memset(fBCD.bcdBytes.ptr, 0, capacity * sizeof(int8_t)); } else if (oldCapacity < capacity) { auto bcd1 = static_cast<int8_t*>(uprv_malloc(capacity * 2 * sizeof(int8_t))); uprv_memcpy(bcd1, fBCD.bcdBytes.ptr, oldCapacity * sizeof(int8_t)); // Initialize the rest of the byte array to zeros (this is done automatically in Java) uprv_memset(bcd1 + oldCapacity, 0, (capacity - oldCapacity) * sizeof(int8_t)); uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = bcd1; fBCD.bcdBytes.len = capacity * 2; } usingBytes = true; } void DecimalQuantity::switchStorage() { if (usingBytes) { // Change from bytes to long uint64_t bcdLong = 0L; for (int i = precision - 1; i >= 0; i--) { bcdLong <<= 4; bcdLong |= fBCD.bcdBytes.ptr[i]; } uprv_free(fBCD.bcdBytes.ptr); fBCD.bcdBytes.ptr = nullptr; fBCD.bcdLong = bcdLong; usingBytes = false; } else { // Change from long to bytes // Copy the long into a local variable since it will get munged when we allocate the bytes uint64_t bcdLong = fBCD.bcdLong; ensureCapacity(); for (int i = 0; i < precision; i++) { fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(bcdLong & 0xf); bcdLong >>= 4; } U_ASSERT(usingBytes); } } void DecimalQuantity::copyBcdFrom(const DecimalQuantity &other) { setBcdToZero(); if (other.usingBytes) { ensureCapacity(other.precision); uprv_memcpy(fBCD.bcdBytes.ptr, other.fBCD.bcdBytes.ptr, other.precision * sizeof(int8_t)); } else { fBCD.bcdLong = other.fBCD.bcdLong; } } void DecimalQuantity::moveBcdFrom(DecimalQuantity &other) { setBcdToZero(); if (other.usingBytes) { usingBytes = true; fBCD.bcdBytes.ptr = other.fBCD.bcdBytes.ptr; fBCD.bcdBytes.len = other.fBCD.bcdBytes.len; // Take ownership away from the old instance: other.fBCD.bcdBytes.ptr = nullptr; other.usingBytes = false; } else { fBCD.bcdLong = other.fBCD.bcdLong; } } const char16_t* DecimalQuantity::checkHealth() const { if (usingBytes) { if (precision == 0) { return u"Zero precision but we are in byte mode"; } int32_t capacity = fBCD.bcdBytes.len; if (precision > capacity) { return u"Precision exceeds length of byte array"; } if (getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in byte mode"; } if (getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; } for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in byte array"; } if (getDigitPos(i) < 0) { return u"Digit below 0 in byte array"; } } for (int i = precision; i < capacity; i++) { if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in byte array"; } } } else { if (precision == 0 && fBCD.bcdLong != 0) { return u"Value in bcdLong even though precision is zero"; } if (precision > 16) { return u"Precision exceeds length of long"; } if (precision != 0 && getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in long mode"; } if (precision != 0 && getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; } for (int i = 0; i < precision; i++) { if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in long"; } if (getDigitPos(i) < 0) { return u"Digit below 0 in long (?!)"; } } for (int i = precision; i < 16; i++) { if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in long"; } } } // No error return nullptr; } bool DecimalQuantity::operator==(const DecimalQuantity& other) const { bool basicEquals = scale == other.scale && precision == other.precision && flags == other.flags && lOptPos == other.lOptPos && lReqPos == other.lReqPos && rReqPos == other.rReqPos && rOptPos == other.rOptPos && isApproximate == other.isApproximate; if (!basicEquals) { return false; } if (precision == 0) { return true; } else if (isApproximate) { return origDouble == other.origDouble && origDelta == other.origDelta; } else { for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) { if (getDigit(m) != other.getDigit(m)) { return false; } } return true; } } UnicodeString DecimalQuantity::toString() const { MaybeStackArray<char, 30> digits(precision + 1); for (int32_t i = 0; i < precision; i++) { digits[i] = getDigitPos(precision - i - 1) + '0'; } digits[precision] = 0; // terminate buffer char buffer8[100]; snprintf( buffer8, sizeof(buffer8), "<DecimalQuantity %d:%d:%d:%d %s %s%s%s%d>", (lOptPos > 999 ? 999 : lOptPos), lReqPos, rReqPos, (rOptPos < -999 ? -999 : rOptPos), (usingBytes ? "bytes" : "long"), (isNegative() ? "-" : ""), (precision == 0 ? "0" : digits.getAlias()), "E", scale); return UnicodeString(buffer8, -1, US_INV); } #endif /* #if !UCONFIG_NO_FORMATTING */
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_434_1
crossvul-cpp_data_good_5388_1
/* * BER Decoder * (C) 1999-2008,2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/ber_dec.h> #include <botan/bigint.h> #include <botan/loadstor.h> #include <botan/internal/safeint.h> namespace Botan { namespace { /* * BER decode an ASN.1 type tag */ size_t decode_tag(DataSource* ber, ASN1_Tag& type_tag, ASN1_Tag& class_tag) { byte b; if(!ber->read_byte(b)) { class_tag = type_tag = NO_OBJECT; return 0; } if((b & 0x1F) != 0x1F) { type_tag = ASN1_Tag(b & 0x1F); class_tag = ASN1_Tag(b & 0xE0); return 1; } size_t tag_bytes = 1; class_tag = ASN1_Tag(b & 0xE0); size_t tag_buf = 0; while(true) { if(!ber->read_byte(b)) throw BER_Decoding_Error("Long-form tag truncated"); if(tag_buf & 0xFF000000) throw BER_Decoding_Error("Long-form tag overflowed 32 bits"); ++tag_bytes; tag_buf = (tag_buf << 7) | (b & 0x7F); if((b & 0x80) == 0) break; } type_tag = ASN1_Tag(tag_buf); return tag_bytes; } /* * Find the EOC marker */ size_t find_eoc(DataSource*); /* * BER decode an ASN.1 length field */ size_t decode_length(DataSource* ber, size_t& field_size) { byte b; if(!ber->read_byte(b)) throw BER_Decoding_Error("Length field not found"); field_size = 1; if((b & 0x80) == 0) return b; field_size += (b & 0x7F); if(field_size == 1) return find_eoc(ber); if(field_size > 5) throw BER_Decoding_Error("Length field is too large"); size_t length = 0; for(size_t i = 0; i != field_size - 1; ++i) { if(get_byte(0, length) != 0) throw BER_Decoding_Error("Field length overflow"); if(!ber->read_byte(b)) throw BER_Decoding_Error("Corrupted length field"); length = (length << 8) | b; } return length; } /* * BER decode an ASN.1 length field */ size_t decode_length(DataSource* ber) { size_t dummy; return decode_length(ber, dummy); } /* * Find the EOC marker */ size_t find_eoc(DataSource* ber) { secure_vector<byte> buffer(DEFAULT_BUFFERSIZE), data; while(true) { const size_t got = ber->peek(buffer.data(), buffer.size(), data.size()); if(got == 0) break; data += std::make_pair(buffer.data(), got); } DataSource_Memory source(data); data.clear(); size_t length = 0; while(true) { ASN1_Tag type_tag, class_tag; size_t tag_size = decode_tag(&source, type_tag, class_tag); if(type_tag == NO_OBJECT) break; size_t length_size = 0; size_t item_size = decode_length(&source, length_size); source.discard_next(item_size); length = BOTAN_CHECKED_ADD(length, item_size); length = BOTAN_CHECKED_ADD(length, tag_size); length = BOTAN_CHECKED_ADD(length, length_size); if(type_tag == EOC && class_tag == UNIVERSAL) break; } return length; } } /* * Check a type invariant on BER data */ void BER_Object::assert_is_a(ASN1_Tag type_tag_, ASN1_Tag class_tag_) { if(type_tag != type_tag_ || class_tag != class_tag_) throw BER_Decoding_Error("Tag mismatch when decoding got " + std::to_string(type_tag) + "/" + std::to_string(class_tag) + " expected " + std::to_string(type_tag_) + "/" + std::to_string(class_tag_)); } /* * Check if more objects are there */ bool BER_Decoder::more_items() const { if(m_source->end_of_data() && (m_pushed.type_tag == NO_OBJECT)) return false; return true; } /* * Verify that no bytes remain in the source */ BER_Decoder& BER_Decoder::verify_end() { if(!m_source->end_of_data() || (m_pushed.type_tag != NO_OBJECT)) throw Invalid_State("BER_Decoder::verify_end called, but data remains"); return (*this); } /* * Save all the bytes remaining in the source */ BER_Decoder& BER_Decoder::raw_bytes(secure_vector<byte>& out) { out.clear(); byte buf; while(m_source->read_byte(buf)) out.push_back(buf); return (*this); } BER_Decoder& BER_Decoder::raw_bytes(std::vector<byte>& out) { out.clear(); byte buf; while(m_source->read_byte(buf)) out.push_back(buf); return (*this); } /* * Discard all the bytes remaining in the source */ BER_Decoder& BER_Decoder::discard_remaining() { byte buf; while(m_source->read_byte(buf)) ; return (*this); } /* * Return the BER encoding of the next object */ BER_Object BER_Decoder::get_next_object() { BER_Object next; if(m_pushed.type_tag != NO_OBJECT) { next = m_pushed; m_pushed.class_tag = m_pushed.type_tag = NO_OBJECT; return next; } decode_tag(m_source, next.type_tag, next.class_tag); if(next.type_tag == NO_OBJECT) return next; const size_t length = decode_length(m_source); if(!m_source->check_available(length)) throw BER_Decoding_Error("Value truncated"); next.value.resize(length); if(m_source->read(next.value.data(), length) != length) throw BER_Decoding_Error("Value truncated"); if(next.type_tag == EOC && next.class_tag == UNIVERSAL) return get_next_object(); return next; } BER_Decoder& BER_Decoder::get_next(BER_Object& ber) { ber = get_next_object(); return (*this); } /* * Push a object back into the stream */ void BER_Decoder::push_back(const BER_Object& obj) { if(m_pushed.type_tag != NO_OBJECT) throw Invalid_State("BER_Decoder: Only one push back is allowed"); m_pushed = obj; } /* * Begin decoding a CONSTRUCTED type */ BER_Decoder BER_Decoder::start_cons(ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, ASN1_Tag(class_tag | CONSTRUCTED)); BER_Decoder result(obj.value.data(), obj.value.size()); result.m_parent = this; return result; } /* * Finish decoding a CONSTRUCTED type */ BER_Decoder& BER_Decoder::end_cons() { if(!m_parent) throw Invalid_State("BER_Decoder::end_cons called with NULL parent"); if(!m_source->end_of_data()) throw Decoding_Error("BER_Decoder::end_cons called with data left"); return (*m_parent); } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(DataSource& src) { m_source = &src; m_owns = false; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const byte data[], size_t length) { m_source = new DataSource_Memory(data, length); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const secure_vector<byte>& data) { m_source = new DataSource_Memory(data); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const std::vector<byte>& data) { m_source = new DataSource_Memory(data.data(), data.size()); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Copy Constructor */ BER_Decoder::BER_Decoder(const BER_Decoder& other) { m_source = other.m_source; m_owns = false; if(other.m_owns) { other.m_owns = false; m_owns = true; } m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = other.m_parent; } /* * BER_Decoder Destructor */ BER_Decoder::~BER_Decoder() { if(m_owns) delete m_source; m_source = nullptr; } /* * Request for an object to decode itself */ BER_Decoder& BER_Decoder::decode(ASN1_Object& obj, ASN1_Tag, ASN1_Tag) { obj.decode_from(*this); return (*this); } /* * Decode a BER encoded NULL */ BER_Decoder& BER_Decoder::decode_null() { BER_Object obj = get_next_object(); obj.assert_is_a(NULL_TAG, UNIVERSAL); if(obj.value.size()) throw BER_Decoding_Error("NULL object had nonzero size"); return (*this); } /* * Decode a BER encoded BOOLEAN */ BER_Decoder& BER_Decoder::decode(bool& out) { return decode(out, BOOLEAN, UNIVERSAL); } /* * Decode a small BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(size_t& out) { return decode(out, INTEGER, UNIVERSAL); } /* * Decode a BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(BigInt& out) { return decode(out, INTEGER, UNIVERSAL); } BER_Decoder& BER_Decoder::decode_octet_string_bigint(BigInt& out) { secure_vector<byte> out_vec; decode(out_vec, OCTET_STRING); out = BigInt::decode(out_vec.data(), out_vec.size()); return (*this); } std::vector<byte> BER_Decoder::get_next_octet_string() { std::vector<byte> out_vec; decode(out_vec, OCTET_STRING); return out_vec; } /* * Decode a BER encoded BOOLEAN */ BER_Decoder& BER_Decoder::decode(bool& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(obj.value.size() != 1) throw BER_Decoding_Error("BER boolean value had invalid size"); out = (obj.value[0]) ? true : false; return (*this); } /* * Decode a small BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(size_t& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BigInt integer; decode(integer, type_tag, class_tag); if(integer.bits() > 32) throw BER_Decoding_Error("Decoded integer value larger than expected"); out = 0; for(size_t i = 0; i != 4; ++i) out = (out << 8) | integer.byte_at(3-i); return (*this); } /* * Decode a small BER encoded INTEGER */ u64bit BER_Decoder::decode_constrained_integer(ASN1_Tag type_tag, ASN1_Tag class_tag, size_t T_bytes) { if(T_bytes > 8) throw BER_Decoding_Error("Can't decode small integer over 8 bytes"); BigInt integer; decode(integer, type_tag, class_tag); if(integer.bits() > 8*T_bytes) throw BER_Decoding_Error("Decoded integer value larger than expected"); u64bit out = 0; for(size_t i = 0; i != 8; ++i) out = (out << 8) | integer.byte_at(7-i); return out; } /* * Decode a BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(BigInt& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(obj.value.empty()) out = 0; else { const bool negative = (obj.value[0] & 0x80) ? true : false; if(negative) { for(size_t i = obj.value.size(); i > 0; --i) if(obj.value[i-1]--) break; for(size_t i = 0; i != obj.value.size(); ++i) obj.value[i] = ~obj.value[i]; } out = BigInt(&obj.value[0], obj.value.size()); if(negative) out.flip_sign(); } return (*this); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(secure_vector<byte>& out, ASN1_Tag real_type) { return decode(out, real_type, real_type, UNIVERSAL); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(std::vector<byte>& out, ASN1_Tag real_type) { return decode(out, real_type, real_type, UNIVERSAL); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(secure_vector<byte>& buffer, ASN1_Tag real_type, ASN1_Tag type_tag, ASN1_Tag class_tag) { if(real_type != OCTET_STRING && real_type != BIT_STRING) throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", real_type); BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(real_type == OCTET_STRING) buffer = obj.value; else { if(obj.value.empty()) throw BER_Decoding_Error("Invalid BIT STRING"); if(obj.value[0] >= 8) throw BER_Decoding_Error("Bad number of unused bits in BIT STRING"); buffer.resize(obj.value.size() - 1); copy_mem(buffer.data(), &obj.value[1], obj.value.size() - 1); } return (*this); } BER_Decoder& BER_Decoder::decode(std::vector<byte>& buffer, ASN1_Tag real_type, ASN1_Tag type_tag, ASN1_Tag class_tag) { if(real_type != OCTET_STRING && real_type != BIT_STRING) throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", real_type); BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(real_type == OCTET_STRING) buffer = unlock(obj.value); else { if(obj.value.empty()) throw BER_Decoding_Error("Invalid BIT STRING"); if(obj.value[0] >= 8) throw BER_Decoding_Error("Bad number of unused bits in BIT STRING"); buffer.resize(obj.value.size() - 1); copy_mem(buffer.data(), &obj.value[1], obj.value.size() - 1); } return (*this); } }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_5388_1
crossvul-cpp_data_good_3222_1
/* Audio File Library Copyright (C) 2010-2013, Michael Pruett <michael@68k.org> Copyright (C) 2001, Silicon Graphics, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* This module implements Microsoft ADPCM compression. */ #include "config.h" #include "MSADPCM.h" #include <assert.h> #include <cstdlib> #include <limits> #include <string.h> #include "BlockCodec.h" #include "Compiler.h" #include "File.h" #include "Track.h" #include "afinternal.h" #include "audiofile.h" #include "byteorder.h" #include "util.h" #include "../pcm.h" struct ms_adpcm_state { uint8_t predictorIndex; int delta; int16_t sample1, sample2; ms_adpcm_state() { predictorIndex = 0; delta = 16; sample1 = 0; sample2 = 0; } }; class MSADPCM : public BlockCodec { public: static MSADPCM *createDecompress(Track *, File *, bool canSeek, bool headerless, AFframecount *chunkFrames); static MSADPCM *createCompress(Track *, File *, bool canSeek, bool headerless, AFframecount *chunkFrames); virtual ~MSADPCM(); bool initializeCoefficients(); virtual const char *name() const OVERRIDE { return mode() == Compress ? "ms_adpcm_compress" : "ms_adpcm_decompress"; } virtual void describe() OVERRIDE; private: // m_coefficients is an array of m_numCoefficients ADPCM coefficient pairs. int m_numCoefficients; int16_t m_coefficients[256][2]; ms_adpcm_state *m_state; MSADPCM(Mode mode, Track *track, File *fh, bool canSeek); int decodeBlock(const uint8_t *encoded, int16_t *decoded) OVERRIDE; int encodeBlock(const int16_t *decoded, uint8_t *encoded) OVERRIDE; void choosePredictorForBlock(const int16_t *decoded); }; static inline int clamp(int x, int low, int high) { if (x < low) return low; if (x > high) return high; return x; } static const int16_t adaptationTable[] = { 230, 230, 230, 230, 307, 409, 512, 614, 768, 614, 512, 409, 307, 230, 230, 230 }; int firstBitSet(int x) { int position=0; while (x!=0) { x>>=1; ++position; } return position; } #ifndef __has_builtin #define __has_builtin(x) 0 #endif int multiplyCheckOverflow(int a, int b, int *result) { #if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow)) return __builtin_mul_overflow(a, b, result); #else if (firstBitSet(a)+firstBitSet(b)>31) // int is signed, so we can't use 32 bits return true; *result = a * b; return false; #endif } // Compute a linear PCM value from the given differential coded value. static int16_t decodeSample(ms_adpcm_state &state, uint8_t code, const int16_t *coefficient, bool *ok=NULL) { int linearSample = (state.sample1 * coefficient[0] + state.sample2 * coefficient[1]) >> 8; int delta; linearSample += ((code & 0x08) ? (code - 0x10) : code) * state.delta; linearSample = clamp(linearSample, MIN_INT16, MAX_INT16); if (multiplyCheckOverflow(state.delta, adaptationTable[code], &delta)) { if (ok) *ok=false; _af_error(AF_BAD_COMPRESSION, "Error decoding sample"); return 0; } delta >>= 8; if (delta < 16) delta = 16; state.delta = delta; state.sample2 = state.sample1; state.sample1 = linearSample; if (ok) *ok=true; return static_cast<int16_t>(linearSample); } // Compute a differential coded value from the given linear PCM sample. static uint8_t encodeSample(ms_adpcm_state &state, int16_t sample, const int16_t *coefficient) { int predictor = (state.sample1 * coefficient[0] + state.sample2 * coefficient[1]) >> 8; int code = sample - predictor; int bias = state.delta / 2; if (code < 0) bias = -bias; code = (code + bias) / state.delta; code = clamp(code, -8, 7) & 0xf; predictor += ((code & 0x8) ? (code - 0x10) : code) * state.delta; state.sample2 = state.sample1; state.sample1 = clamp(predictor, MIN_INT16, MAX_INT16); state.delta = (adaptationTable[code] * state.delta) >> 8; if (state.delta < 16) state.delta = 16; return code; } // Decode one block of MS ADPCM data. int MSADPCM::decodeBlock(const uint8_t *encoded, int16_t *decoded) { ms_adpcm_state decoderState[2]; ms_adpcm_state *state[2]; int channelCount = m_track->f.channelCount; // Calculate the number of bytes needed for decoded data. int outputLength = m_framesPerPacket * sizeof (int16_t) * channelCount; state[0] = &decoderState[0]; if (channelCount == 2) state[1] = &decoderState[1]; else state[1] = &decoderState[0]; // Initialize block predictor. for (int i=0; i<channelCount; i++) { state[i]->predictorIndex = *encoded++; assert(state[i]->predictorIndex < m_numCoefficients); } // Initialize delta. for (int i=0; i<channelCount; i++) { state[i]->delta = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } // Initialize first two samples. for (int i=0; i<channelCount; i++) { state[i]->sample1 = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } for (int i=0; i<channelCount; i++) { state[i]->sample2 = (encoded[1]<<8) | encoded[0]; encoded += sizeof (uint16_t); } const int16_t *coefficient[2] = { m_coefficients[state[0]->predictorIndex], m_coefficients[state[1]->predictorIndex] }; for (int i=0; i<channelCount; i++) *decoded++ = state[i]->sample2; for (int i=0; i<channelCount; i++) *decoded++ = state[i]->sample1; /* The first two samples have already been 'decoded' in the block header. */ int samplesRemaining = (m_framesPerPacket - 2) * m_track->f.channelCount; while (samplesRemaining > 0) { uint8_t code; int16_t newSample; bool ok; code = *encoded >> 4; newSample = decodeSample(*state[0], code, coefficient[0], &ok); if (!ok) return 0; *decoded++ = newSample; code = *encoded & 0x0f; newSample = decodeSample(*state[1], code, coefficient[1], &ok); if (!ok) return 0; *decoded++ = newSample; encoded++; samplesRemaining -= 2; } return outputLength; } int MSADPCM::encodeBlock(const int16_t *decoded, uint8_t *encoded) { choosePredictorForBlock(decoded); int channelCount = m_track->f.channelCount; // Encode predictor. for (int c=0; c<channelCount; c++) *encoded++ = m_state[c].predictorIndex; // Encode delta. for (int c=0; c<channelCount; c++) { *encoded++ = m_state[c].delta & 0xff; *encoded++ = m_state[c].delta >> 8; } // Enccode first two samples. for (int c=0; c<channelCount; c++) m_state[c].sample2 = *decoded++; for (int c=0; c<channelCount; c++) m_state[c].sample1 = *decoded++; for (int c=0; c<channelCount; c++) { *encoded++ = m_state[c].sample1 & 0xff; *encoded++ = m_state[c].sample1 >> 8; } for (int c=0; c<channelCount; c++) { *encoded++ = m_state[c].sample2 & 0xff; *encoded++ = m_state[c].sample2 >> 8; } ms_adpcm_state *state[2] = { &m_state[0], &m_state[channelCount - 1] }; const int16_t *coefficient[2] = { m_coefficients[state[0]->predictorIndex], m_coefficients[state[1]->predictorIndex] }; int samplesRemaining = (m_framesPerPacket - 2) * m_track->f.channelCount; while (samplesRemaining > 0) { uint8_t code1 = encodeSample(*state[0], *decoded++, coefficient[0]); uint8_t code2 = encodeSample(*state[1], *decoded++, coefficient[1]); *encoded++ = (code1 << 4) | code2; samplesRemaining -= 2; } return m_bytesPerPacket; } void MSADPCM::choosePredictorForBlock(const int16_t *decoded) { const int kPredictorSampleLength = 3; int channelCount = m_track->f.channelCount; for (int c=0; c<channelCount; c++) { int bestPredictorIndex = 0; int bestPredictorError = std::numeric_limits<int>::max(); for (int k=0; k<m_numCoefficients; k++) { int a0 = m_coefficients[k][0]; int a1 = m_coefficients[k][1]; int currentPredictorError = 0; for (int i=2; i<2+kPredictorSampleLength; i++) { int error = std::abs(decoded[i*channelCount + c] - ((a0 * decoded[(i-1)*channelCount + c] + a1 * decoded[(i-2)*channelCount + c]) >> 8)); currentPredictorError += error; } currentPredictorError /= 4 * kPredictorSampleLength; if (currentPredictorError < bestPredictorError) { bestPredictorError = currentPredictorError; bestPredictorIndex = k; } if (!currentPredictorError) break; } if (bestPredictorError < 16) bestPredictorError = 16; m_state[c].predictorIndex = bestPredictorIndex; m_state[c].delta = bestPredictorError; } } void MSADPCM::describe() { m_outChunk->f.byteOrder = _AF_BYTEORDER_NATIVE; m_outChunk->f.compressionType = AF_COMPRESSION_NONE; m_outChunk->f.compressionParams = AU_NULL_PVLIST; } MSADPCM::MSADPCM(Mode mode, Track *track, File *fh, bool canSeek) : BlockCodec(mode, track, fh, canSeek), m_numCoefficients(0), m_state(NULL) { m_state = new ms_adpcm_state[m_track->f.channelCount]; } MSADPCM::~MSADPCM() { delete [] m_state; } bool MSADPCM::initializeCoefficients() { AUpvlist pv = m_track->f.compressionParams; long l; if (_af_pv_getlong(pv, _AF_MS_ADPCM_NUM_COEFFICIENTS, &l)) { m_numCoefficients = l; } else { _af_error(AF_BAD_CODEC_CONFIG, "number of coefficients not set"); return false; } void *v; if (_af_pv_getptr(pv, _AF_MS_ADPCM_COEFFICIENTS, &v)) { memcpy(m_coefficients, v, m_numCoefficients * 2 * sizeof (int16_t)); } else { _af_error(AF_BAD_CODEC_CONFIG, "coefficient array not set"); return false; } return true; } MSADPCM *MSADPCM::createDecompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { assert(fh->tell() == track->fpos_first_frame); MSADPCM *msadpcm = new MSADPCM(Decompress, track, fh, canSeek); if (!msadpcm->initializeCoefficients()) { delete msadpcm; return NULL; } *chunkFrames = msadpcm->m_framesPerPacket; return msadpcm; } MSADPCM *MSADPCM::createCompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { assert(fh->tell() == track->fpos_first_frame); MSADPCM *msadpcm = new MSADPCM(Compress, track, fh, canSeek); if (!msadpcm->initializeCoefficients()) { delete msadpcm; return NULL; } *chunkFrames = msadpcm->m_framesPerPacket; return msadpcm; } bool _af_ms_adpcm_format_ok (AudioFormat *f) { if (f->channelCount != 1 && f->channelCount != 2) { _af_error(AF_BAD_COMPRESSION, "MS ADPCM compression requires 1 or 2 channels"); return false; } if (f->sampleFormat != AF_SAMPFMT_TWOSCOMP || f->sampleWidth != 16) { _af_error(AF_BAD_COMPRESSION, "MS ADPCM compression requires 16-bit signed integer format"); return false; } if (f->byteOrder != _AF_BYTEORDER_NATIVE) { _af_error(AF_BAD_COMPRESSION, "MS ADPCM compression requires native byte order"); return false; } return true; } FileModule *_af_ms_adpcm_init_decompress (Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { return MSADPCM::createDecompress(track, fh, canSeek, headerless, chunkFrames); } FileModule *_af_ms_adpcm_init_compress (Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { return MSADPCM::createCompress(track, fh, canSeek, headerless, chunkFrames); }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_3222_1
crossvul-cpp_data_bad_582_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, unsigned count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD else if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } if(feof(ifp)) throw LIBRAW_EXCEPTION_IO_EOF; for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if(width>768 || raw_width>768 || height > 512 || raw_height>512 ) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; if(col>=0) FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* extra room for data stored w/o predictor */ int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float libraw_powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * libraw_powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * libraw_powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = libraw_powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = libraw_powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = libraw_powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = libraw_powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; #ifdef LIBRAW_LIBRARY_BUILD if(offset>ifp->size()-8) // At least 8 bytes for tag/len offset = ifp->size()-8; #endif while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); if(len < 0) return; // just ignore wrong len?? or raise bad file exception? switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64(2.0f, -int_to_float((get4(),get4()))); aperture = libraw_powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = libraw_powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 { ushort q = get2(); cam_mul[c ^ (c >> 1)] = q? 1024.0 / get2() : 1024; } if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // data length should be in range w*h..w*h*2 if(width*height < (LIBRAW_MAX_ALLOC_MB*1024*512L) && width*height>1 && i >= width * height && i <= width*height*2) { #endif switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD } else is_raw = 0; #endif } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ( (int)width + (int)left_margin > 65535) || ( (int)height + (int)top_margin > 65535) ) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_582_1
crossvul-cpp_data_bad_3222_1
404: Not Found
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_3222_1
crossvul-cpp_data_good_3222_0
/* Audio File Library Copyright (C) 2013 Michael Pruett <michael@68k.org> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "BlockCodec.h" #include "Track.h" #include <assert.h> BlockCodec::BlockCodec(Mode mode, Track *track, File *fh, bool canSeek) : FileModule(mode, track, fh, canSeek), m_bytesPerPacket(-1), m_framesPerPacket(-1), m_framesToIgnore(-1), m_savedPositionNextFrame(-1), m_savedNextFrame(-1) { m_framesPerPacket = track->f.framesPerPacket; m_bytesPerPacket = track->f.bytesPerPacket; } void BlockCodec::runPull() { AFframecount framesToRead = m_outChunk->frameCount; AFframecount framesRead = 0; assert(framesToRead % m_framesPerPacket == 0); int blockCount = framesToRead / m_framesPerPacket; // Read the compressed data. ssize_t bytesRead = read(m_inChunk->buffer, m_bytesPerPacket * blockCount); int blocksRead = bytesRead >= 0 ? bytesRead / m_bytesPerPacket : 0; // Decompress into m_outChunk. for (int i=0; i<blocksRead; i++) { if (decodeBlock(static_cast<const uint8_t *>(m_inChunk->buffer) + i * m_bytesPerPacket, static_cast<int16_t *>(m_outChunk->buffer) + i * m_framesPerPacket * m_track->f.channelCount)==0) break; framesRead += m_framesPerPacket; } m_track->nextfframe += framesRead; assert(tell() == m_track->fpos_next_frame); if (framesRead < framesToRead) reportReadError(framesRead, framesToRead); m_outChunk->frameCount = framesRead; } void BlockCodec::reset1() { AFframecount nextTrackFrame = m_track->nextfframe; m_track->nextfframe = (nextTrackFrame / m_framesPerPacket) * m_framesPerPacket; m_framesToIgnore = nextTrackFrame - m_track->nextfframe; } void BlockCodec::reset2() { m_track->fpos_next_frame = m_track->fpos_first_frame + m_bytesPerPacket * (m_track->nextfframe / m_framesPerPacket); m_track->frames2ignore += m_framesToIgnore; assert(m_track->nextfframe % m_framesPerPacket == 0); } void BlockCodec::runPush() { AFframecount framesToWrite = m_inChunk->frameCount; int channelCount = m_inChunk->f.channelCount; int blockCount = (framesToWrite + m_framesPerPacket - 1) / m_framesPerPacket; for (int i=0; i<blockCount; i++) { encodeBlock(static_cast<const int16_t *>(m_inChunk->buffer) + i * m_framesPerPacket * channelCount, static_cast<uint8_t *>(m_outChunk->buffer) + i * m_bytesPerPacket); } ssize_t bytesWritten = write(m_outChunk->buffer, m_bytesPerPacket * blockCount); ssize_t blocksWritten = bytesWritten >= 0 ? bytesWritten / m_bytesPerPacket : 0; AFframecount framesWritten = std::min((AFframecount) blocksWritten * m_framesPerPacket, framesToWrite); m_track->nextfframe += framesWritten; m_track->totalfframes = m_track->nextfframe; assert(tell() == m_track->fpos_next_frame); if (framesWritten < framesToWrite) reportWriteError(framesWritten, framesToWrite); } void BlockCodec::sync1() { m_savedPositionNextFrame = m_track->fpos_next_frame; m_savedNextFrame = m_track->nextfframe; } void BlockCodec::sync2() { assert(tell() == m_track->fpos_next_frame); m_track->fpos_after_data = tell(); m_track->fpos_next_frame = m_savedPositionNextFrame; m_track->nextfframe = m_savedNextFrame; }
./CrossVul/dataset_final_sorted/CWE-190/cpp/good_3222_0
crossvul-cpp_data_bad_5388_1
/* * BER Decoder * (C) 1999-2008,2015 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/ber_dec.h> #include <botan/bigint.h> #include <botan/loadstor.h> namespace Botan { namespace { /* * BER decode an ASN.1 type tag */ size_t decode_tag(DataSource* ber, ASN1_Tag& type_tag, ASN1_Tag& class_tag) { byte b; if(!ber->read_byte(b)) { class_tag = type_tag = NO_OBJECT; return 0; } if((b & 0x1F) != 0x1F) { type_tag = ASN1_Tag(b & 0x1F); class_tag = ASN1_Tag(b & 0xE0); return 1; } size_t tag_bytes = 1; class_tag = ASN1_Tag(b & 0xE0); size_t tag_buf = 0; while(true) { if(!ber->read_byte(b)) throw BER_Decoding_Error("Long-form tag truncated"); if(tag_buf & 0xFF000000) throw BER_Decoding_Error("Long-form tag overflowed 32 bits"); ++tag_bytes; tag_buf = (tag_buf << 7) | (b & 0x7F); if((b & 0x80) == 0) break; } type_tag = ASN1_Tag(tag_buf); return tag_bytes; } /* * Find the EOC marker */ size_t find_eoc(DataSource*); /* * BER decode an ASN.1 length field */ size_t decode_length(DataSource* ber, size_t& field_size) { byte b; if(!ber->read_byte(b)) throw BER_Decoding_Error("Length field not found"); field_size = 1; if((b & 0x80) == 0) return b; field_size += (b & 0x7F); if(field_size == 1) return find_eoc(ber); if(field_size > 5) throw BER_Decoding_Error("Length field is too large"); size_t length = 0; for(size_t i = 0; i != field_size - 1; ++i) { if(get_byte(0, length) != 0) throw BER_Decoding_Error("Field length overflow"); if(!ber->read_byte(b)) throw BER_Decoding_Error("Corrupted length field"); length = (length << 8) | b; } return length; } /* * BER decode an ASN.1 length field */ size_t decode_length(DataSource* ber) { size_t dummy; return decode_length(ber, dummy); } /* * Find the EOC marker */ size_t find_eoc(DataSource* ber) { secure_vector<byte> buffer(DEFAULT_BUFFERSIZE), data; while(true) { const size_t got = ber->peek(buffer.data(), buffer.size(), data.size()); if(got == 0) break; data += std::make_pair(buffer.data(), got); } DataSource_Memory source(data); data.clear(); size_t length = 0; while(true) { ASN1_Tag type_tag, class_tag; size_t tag_size = decode_tag(&source, type_tag, class_tag); if(type_tag == NO_OBJECT) break; size_t length_size = 0; size_t item_size = decode_length(&source, length_size); source.discard_next(item_size); length += item_size + length_size + tag_size; if(type_tag == EOC && class_tag == UNIVERSAL) break; } return length; } } /* * Check a type invariant on BER data */ void BER_Object::assert_is_a(ASN1_Tag type_tag_, ASN1_Tag class_tag_) { if(type_tag != type_tag_ || class_tag != class_tag_) throw BER_Decoding_Error("Tag mismatch when decoding got " + std::to_string(type_tag) + "/" + std::to_string(class_tag) + " expected " + std::to_string(type_tag_) + "/" + std::to_string(class_tag_)); } /* * Check if more objects are there */ bool BER_Decoder::more_items() const { if(m_source->end_of_data() && (m_pushed.type_tag == NO_OBJECT)) return false; return true; } /* * Verify that no bytes remain in the source */ BER_Decoder& BER_Decoder::verify_end() { if(!m_source->end_of_data() || (m_pushed.type_tag != NO_OBJECT)) throw Invalid_State("BER_Decoder::verify_end called, but data remains"); return (*this); } /* * Save all the bytes remaining in the source */ BER_Decoder& BER_Decoder::raw_bytes(secure_vector<byte>& out) { out.clear(); byte buf; while(m_source->read_byte(buf)) out.push_back(buf); return (*this); } BER_Decoder& BER_Decoder::raw_bytes(std::vector<byte>& out) { out.clear(); byte buf; while(m_source->read_byte(buf)) out.push_back(buf); return (*this); } /* * Discard all the bytes remaining in the source */ BER_Decoder& BER_Decoder::discard_remaining() { byte buf; while(m_source->read_byte(buf)) ; return (*this); } /* * Return the BER encoding of the next object */ BER_Object BER_Decoder::get_next_object() { BER_Object next; if(m_pushed.type_tag != NO_OBJECT) { next = m_pushed; m_pushed.class_tag = m_pushed.type_tag = NO_OBJECT; return next; } decode_tag(m_source, next.type_tag, next.class_tag); if(next.type_tag == NO_OBJECT) return next; const size_t length = decode_length(m_source); if(!m_source->check_available(length)) throw BER_Decoding_Error("Value truncated"); next.value.resize(length); if(m_source->read(next.value.data(), length) != length) throw BER_Decoding_Error("Value truncated"); if(next.type_tag == EOC && next.class_tag == UNIVERSAL) return get_next_object(); return next; } BER_Decoder& BER_Decoder::get_next(BER_Object& ber) { ber = get_next_object(); return (*this); } /* * Push a object back into the stream */ void BER_Decoder::push_back(const BER_Object& obj) { if(m_pushed.type_tag != NO_OBJECT) throw Invalid_State("BER_Decoder: Only one push back is allowed"); m_pushed = obj; } /* * Begin decoding a CONSTRUCTED type */ BER_Decoder BER_Decoder::start_cons(ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, ASN1_Tag(class_tag | CONSTRUCTED)); BER_Decoder result(obj.value.data(), obj.value.size()); result.m_parent = this; return result; } /* * Finish decoding a CONSTRUCTED type */ BER_Decoder& BER_Decoder::end_cons() { if(!m_parent) throw Invalid_State("BER_Decoder::end_cons called with NULL parent"); if(!m_source->end_of_data()) throw Decoding_Error("BER_Decoder::end_cons called with data left"); return (*m_parent); } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(DataSource& src) { m_source = &src; m_owns = false; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const byte data[], size_t length) { m_source = new DataSource_Memory(data, length); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const secure_vector<byte>& data) { m_source = new DataSource_Memory(data); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Constructor */ BER_Decoder::BER_Decoder(const std::vector<byte>& data) { m_source = new DataSource_Memory(data.data(), data.size()); m_owns = true; m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = nullptr; } /* * BER_Decoder Copy Constructor */ BER_Decoder::BER_Decoder(const BER_Decoder& other) { m_source = other.m_source; m_owns = false; if(other.m_owns) { other.m_owns = false; m_owns = true; } m_pushed.type_tag = m_pushed.class_tag = NO_OBJECT; m_parent = other.m_parent; } /* * BER_Decoder Destructor */ BER_Decoder::~BER_Decoder() { if(m_owns) delete m_source; m_source = nullptr; } /* * Request for an object to decode itself */ BER_Decoder& BER_Decoder::decode(ASN1_Object& obj, ASN1_Tag, ASN1_Tag) { obj.decode_from(*this); return (*this); } /* * Decode a BER encoded NULL */ BER_Decoder& BER_Decoder::decode_null() { BER_Object obj = get_next_object(); obj.assert_is_a(NULL_TAG, UNIVERSAL); if(obj.value.size()) throw BER_Decoding_Error("NULL object had nonzero size"); return (*this); } /* * Decode a BER encoded BOOLEAN */ BER_Decoder& BER_Decoder::decode(bool& out) { return decode(out, BOOLEAN, UNIVERSAL); } /* * Decode a small BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(size_t& out) { return decode(out, INTEGER, UNIVERSAL); } /* * Decode a BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(BigInt& out) { return decode(out, INTEGER, UNIVERSAL); } BER_Decoder& BER_Decoder::decode_octet_string_bigint(BigInt& out) { secure_vector<byte> out_vec; decode(out_vec, OCTET_STRING); out = BigInt::decode(out_vec.data(), out_vec.size()); return (*this); } std::vector<byte> BER_Decoder::get_next_octet_string() { std::vector<byte> out_vec; decode(out_vec, OCTET_STRING); return out_vec; } /* * Decode a BER encoded BOOLEAN */ BER_Decoder& BER_Decoder::decode(bool& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(obj.value.size() != 1) throw BER_Decoding_Error("BER boolean value had invalid size"); out = (obj.value[0]) ? true : false; return (*this); } /* * Decode a small BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(size_t& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BigInt integer; decode(integer, type_tag, class_tag); if(integer.bits() > 32) throw BER_Decoding_Error("Decoded integer value larger than expected"); out = 0; for(size_t i = 0; i != 4; ++i) out = (out << 8) | integer.byte_at(3-i); return (*this); } /* * Decode a small BER encoded INTEGER */ u64bit BER_Decoder::decode_constrained_integer(ASN1_Tag type_tag, ASN1_Tag class_tag, size_t T_bytes) { if(T_bytes > 8) throw BER_Decoding_Error("Can't decode small integer over 8 bytes"); BigInt integer; decode(integer, type_tag, class_tag); if(integer.bits() > 8*T_bytes) throw BER_Decoding_Error("Decoded integer value larger than expected"); u64bit out = 0; for(size_t i = 0; i != 8; ++i) out = (out << 8) | integer.byte_at(7-i); return out; } /* * Decode a BER encoded INTEGER */ BER_Decoder& BER_Decoder::decode(BigInt& out, ASN1_Tag type_tag, ASN1_Tag class_tag) { BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(obj.value.empty()) out = 0; else { const bool negative = (obj.value[0] & 0x80) ? true : false; if(negative) { for(size_t i = obj.value.size(); i > 0; --i) if(obj.value[i-1]--) break; for(size_t i = 0; i != obj.value.size(); ++i) obj.value[i] = ~obj.value[i]; } out = BigInt(&obj.value[0], obj.value.size()); if(negative) out.flip_sign(); } return (*this); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(secure_vector<byte>& out, ASN1_Tag real_type) { return decode(out, real_type, real_type, UNIVERSAL); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(std::vector<byte>& out, ASN1_Tag real_type) { return decode(out, real_type, real_type, UNIVERSAL); } /* * BER decode a BIT STRING or OCTET STRING */ BER_Decoder& BER_Decoder::decode(secure_vector<byte>& buffer, ASN1_Tag real_type, ASN1_Tag type_tag, ASN1_Tag class_tag) { if(real_type != OCTET_STRING && real_type != BIT_STRING) throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", real_type); BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(real_type == OCTET_STRING) buffer = obj.value; else { if(obj.value.empty()) throw BER_Decoding_Error("Invalid BIT STRING"); if(obj.value[0] >= 8) throw BER_Decoding_Error("Bad number of unused bits in BIT STRING"); buffer.resize(obj.value.size() - 1); copy_mem(buffer.data(), &obj.value[1], obj.value.size() - 1); } return (*this); } BER_Decoder& BER_Decoder::decode(std::vector<byte>& buffer, ASN1_Tag real_type, ASN1_Tag type_tag, ASN1_Tag class_tag) { if(real_type != OCTET_STRING && real_type != BIT_STRING) throw BER_Bad_Tag("Bad tag for {BIT,OCTET} STRING", real_type); BER_Object obj = get_next_object(); obj.assert_is_a(type_tag, class_tag); if(real_type == OCTET_STRING) buffer = unlock(obj.value); else { if(obj.value.empty()) throw BER_Decoding_Error("Invalid BIT STRING"); if(obj.value[0] >= 8) throw BER_Decoding_Error("Bad number of unused bits in BIT STRING"); buffer.resize(obj.value.size() - 1); copy_mem(buffer.data(), &obj.value[1], obj.value.size() - 1); } return (*this); } }
./CrossVul/dataset_final_sorted/CWE-190/cpp/bad_5388_1
crossvul-cpp_data_bad_540_0
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 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. */ #include "opj_includes.h" /** @defgroup PI PI - Implementation of a packet iterator */ /*@{*/ /** @name Local static functions */ /*@{*/ /** Get next packet in layer-resolution-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-layer-component-precinct order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi); /** Get next packet in resolution-precinct-component-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi); /** Get next packet in precinct-component-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi); /** Get next packet in component-precinct-resolution-layer order. @param pi packet iterator to modify @return returns false if pi pointed to the last packet or else returns true */ static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi); /** * Updates the coding parameters if the encoding is used with Progression order changes and final (or cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used). * * @param p_cp the coding parameters to modify * @param p_num_comps the number of components * @param p_tileno the tile index being concerned. * @param p_tx0 X0 parameter for the tile * @param p_tx1 X1 parameter for the tile * @param p_ty0 Y0 parameter for the tile * @param p_ty1 Y1 parameter for the tile * @param p_max_prec the maximum precision for all the bands of the tile * @param p_max_res the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min the minimum dy of all the components of all the resolutions for the tile. */ static void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the the minimum dy of all the components of all the resolutions for the tile. */ static void opj_get_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ); /** * Gets the encoding parameters needed to update the coding parameters and all the pocs. * The precinct widths, heights, dx and dy for each component at each resolution will be stored as well. * the last parameter of the function should be an array of pointers of size nb components, each pointer leading * to an area of size 4 * max_res. The data is stored inside this area with the following pattern : * dx_compi_res0 , dy_compi_res0 , w_compi_res0, h_compi_res0 , dx_compi_res1 , dy_compi_res1 , w_compi_res1, h_compi_res1 , ... * * @param p_image the image being encoded. * @param p_cp the coding parameters. * @param tileno the tile index of the tile being encoded. * @param p_tx0 pointer that will hold the X0 parameter for the tile * @param p_tx1 pointer that will hold the X1 parameter for the tile * @param p_ty0 pointer that will hold the Y0 parameter for the tile * @param p_ty1 pointer that will hold the Y1 parameter for the tile * @param p_max_prec pointer that will hold the the maximum precision for all the bands of the tile * @param p_max_res pointer that will hold the the maximum number of resolutions for all the poc inside the tile. * @param p_dx_min pointer that will hold the the minimum dx of all the components of all the resolutions for the tile. * @param p_dy_min pointer that will hold the the minimum dy of all the components of all the resolutions for the tile. * @param p_resolutions pointer to an area corresponding to the one described above. */ static void opj_get_all_encoding_parameters(const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ); /** * Allocates memory for a packet iterator. Data and data sizes are set by this operation. * No other data is set. The include section of the packet iterator is not allocated. * * @param p_image the image used to initialize the packet iterator (in fact only the number of components is relevant. * @param p_cp the coding parameters. * @param tileno the index of the tile from which creating the packet iterator. */ static opj_pi_iterator_t * opj_pi_create( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno ); /** * FIXME DOC */ static void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ static void opj_pi_update_decode_poc ( opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res); /** * FIXME DOC */ OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog); /*@}*/ /*@}*/ /* ========================================================== local functions ========================================================== */ OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if (!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; res = &comp->resolutions[pi->resno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; if(!pi->tp_on){ pi->poc.precno1 = res->pw * res->ph; } for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } return OPJ_FALSE; } OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) { for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; comp = &pi->comps[pi->compno]; if (pi->resno >= comp->numresolutions) { continue; } res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { OPJ_UINT32 compno, resno; pi->first = 0; pi->dx = 0; pi->dy = 0; for (compno = 0; compno < pi->numcomps; compno++) { comp = &pi->comps[compno]; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } } } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { comp = &pi->comps[pi->compno]; for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi) { opj_pi_comp_t *comp = NULL; opj_pi_resolution_t *res = NULL; OPJ_UINT32 index = 0; if (!pi->first) { comp = &pi->comps[pi->compno]; goto LABEL_SKIP; } else { pi->first = 0; } for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) { OPJ_UINT32 resno; comp = &pi->comps[pi->compno]; pi->dx = 0; pi->dy = 0; for (resno = 0; resno < comp->numresolutions; resno++) { OPJ_UINT32 dx, dy; res = &comp->resolutions[resno]; dx = comp->dx * (1u << (res->pdx + comp->numresolutions - 1 - resno)); dy = comp->dy * (1u << (res->pdy + comp->numresolutions - 1 - resno)); pi->dx = !pi->dx ? dx : opj_uint_min(pi->dx, dx); pi->dy = !pi->dy ? dy : opj_uint_min(pi->dy, dy); } if (!pi->tp_on){ pi->poc.ty0 = pi->ty0; pi->poc.tx0 = pi->tx0; pi->poc.ty1 = pi->ty1; pi->poc.tx1 = pi->tx1; } for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1; pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) { for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1; pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) { for (pi->resno = pi->poc.resno0; pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) { OPJ_UINT32 levelno; OPJ_INT32 trx0, try0; OPJ_INT32 trx1, try1; OPJ_UINT32 rpx, rpy; OPJ_INT32 prci, prcj; res = &comp->resolutions[pi->resno]; levelno = comp->numresolutions - 1 - pi->resno; trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno)); try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno)); trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno)); try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno)); rpx = res->pdx + levelno; rpy = res->pdy + levelno; if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) && ((try0 << levelno) % (1 << rpy))))){ continue; } if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) && ((trx0 << levelno) % (1 << rpx))))){ continue; } if ((res->pw==0)||(res->ph==0)) continue; if ((trx0==trx1)||(try0==try1)) continue; prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x, (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx) - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx); prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y, (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy) - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy); pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw); for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) { index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno * pi->step_c + pi->precno * pi->step_p; if (!pi->include[index]) { pi->include[index] = 1; return OPJ_TRUE; } LABEL_SKIP:; } } } } } return OPJ_FALSE; } void opj_get_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res ) { /* loop */ OPJ_UINT32 compno, resno; /* pointers */ const opj_tcp_t *l_tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* position in x and y of tile */ OPJ_UINT32 p, q; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps [p_tileno]; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */ p = p_tileno % p_cp->tw; q = p_tileno / p_cp->tw; /* find extent of tile */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision is 0 (can only grow) */ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min */ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* arithmetic variables to calculate */ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_pw, l_ph; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts */ for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; l_dx = l_img_comp->dx * (1u << (l_pdx + l_tccp->numresolutions - 1 - resno)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_tccp->numresolutions - 1 - resno)); /* take the minimum size for dx for each comp and resolution */ *p_dx_min = opj_uint_min(*p_dx_min, l_dx); *p_dy_min = opj_uint_min(*p_dy_min, l_dy); /* various calculations of extents */ l_level_no = l_tccp->numresolutions - 1 - resno; l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); l_product = l_pw * l_ph; /* update precision */ if (l_product > *p_max_prec) { *p_max_prec = l_product; } } ++l_img_comp; ++l_tccp; } } void opj_get_all_encoding_parameters( const opj_image_t *p_image, const opj_cp_t *p_cp, OPJ_UINT32 tileno, OPJ_INT32 * p_tx0, OPJ_INT32 * p_tx1, OPJ_INT32 * p_ty0, OPJ_INT32 * p_ty1, OPJ_UINT32 * p_dx_min, OPJ_UINT32 * p_dy_min, OPJ_UINT32 * p_max_prec, OPJ_UINT32 * p_max_res, OPJ_UINT32 ** p_resolutions ) { /* loop*/ OPJ_UINT32 compno, resno; /* pointers*/ const opj_tcp_t *tcp = 00; const opj_tccp_t * l_tccp = 00; const opj_image_comp_t * l_img_comp = 00; /* to store l_dx, l_dy, w and h for each resolution and component.*/ OPJ_UINT32 * lResolutionPtr; /* position in x and y of tile*/ OPJ_UINT32 p, q; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(tileno < p_cp->tw * p_cp->th); /* initializations*/ tcp = &p_cp->tcps [tileno]; l_tccp = tcp->tccps; l_img_comp = p_image->comps; /* position in x and y of tile*/ p = tileno % p_cp->tw; q = tileno / p_cp->tw; /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */ *p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0); *p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1); *p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0); *p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1); /* max precision and resolution is 0 (can only grow)*/ *p_max_prec = 0; *p_max_res = 0; /* take the largest value for dx_min and dy_min*/ *p_dx_min = 0x7fffffff; *p_dy_min = 0x7fffffff; for (compno = 0; compno < p_image->numcomps; ++compno) { /* aritmetic variables to calculate*/ OPJ_UINT32 l_level_no; OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1; OPJ_INT32 l_px0, l_py0, l_px1, py1; OPJ_UINT32 l_product; OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1; OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph; lResolutionPtr = p_resolutions[compno]; l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx); l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy); l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx); l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy); if (l_tccp->numresolutions > *p_max_res) { *p_max_res = l_tccp->numresolutions; } /* use custom size for precincts*/ l_level_no = l_tccp->numresolutions - 1; for (resno = 0; resno < l_tccp->numresolutions; ++resno) { OPJ_UINT32 l_dx, l_dy; /* precinct width and height*/ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; *lResolutionPtr++ = l_pdx; *lResolutionPtr++ = l_pdy; l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no)); l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no)); /* take the minimum size for l_dx for each comp and resolution*/ *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx); *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy); /* various calculations of extents*/ l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no); l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no); l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no); l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no); l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx; l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy; l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx; py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy; l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx); l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy); *lResolutionPtr++ = l_pw; *lResolutionPtr++ = l_ph; l_product = l_pw * l_ph; /* update precision*/ if (l_product > *p_max_prec) { *p_max_prec = l_product; } --l_level_no; } ++l_tccp; ++l_img_comp; } } opj_pi_iterator_t * opj_pi_create( const opj_image_t *image, const opj_cp_t *cp, OPJ_UINT32 tileno ) { /* loop*/ OPJ_UINT32 pino, compno; /* number of poc in the p_pi*/ OPJ_UINT32 l_poc_bound; /* pointers to tile coding parameters and components.*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *tcp = 00; const opj_tccp_t *tccp = 00; /* current packet iterator being allocated*/ opj_pi_iterator_t *l_current_pi = 00; /* preconditions in debug*/ assert(cp != 00); assert(image != 00); assert(tileno < cp->tw * cp->th); /* initializations*/ tcp = &cp->tcps[tileno]; l_poc_bound = tcp->numpocs+1; /* memory allocations*/ l_pi = (opj_pi_iterator_t*) opj_calloc((l_poc_bound), sizeof(opj_pi_iterator_t)); if (!l_pi) { return NULL; } l_current_pi = l_pi; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps, sizeof(opj_pi_comp_t)); if (! l_current_pi->comps) { opj_pi_destroy(l_pi, l_poc_bound); return NULL; } l_current_pi->numcomps = image->numcomps; for (compno = 0; compno < image->numcomps; ++compno) { opj_pi_comp_t *comp = &l_current_pi->comps[compno]; tccp = &tcp->tccps[compno]; comp->resolutions = (opj_pi_resolution_t*) opj_calloc(tccp->numresolutions, sizeof(opj_pi_resolution_t)); if (!comp->resolutions) { opj_pi_destroy(l_pi, l_poc_bound); return 00; } comp->numresolutions = tccp->numresolutions; } ++l_current_pi; } return l_pi; } void opj_pi_update_encode_poc_and_final ( opj_cp_t *p_cp, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE = l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; /* special treatment for the first element*/ l_current_poc->layS = 0; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; for (pino = 1;pino < l_poc_bound ; ++pino) { l_current_poc->compS = l_current_poc->compno0; l_current_poc->compE= l_current_poc->compno1; l_current_poc->resS = l_current_poc->resno0; l_current_poc->resE = l_current_poc->resno1; l_current_poc->layE = l_current_poc->layno1; l_current_poc->prg = l_current_poc->prg1; l_current_poc->prcS = 0; /* special treatment here different from the first element*/ l_current_poc->layS = (l_current_poc->layE > (l_current_poc-1)->layE) ? l_current_poc->layE : 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } void opj_pi_update_encode_not_poc ( opj_cp_t *p_cp, OPJ_UINT32 p_num_comps, OPJ_UINT32 p_tileno, OPJ_INT32 p_tx0, OPJ_INT32 p_tx1, OPJ_INT32 p_ty0, OPJ_INT32 p_ty1, OPJ_UINT32 p_max_prec, OPJ_UINT32 p_max_res, OPJ_UINT32 p_dx_min, OPJ_UINT32 p_dy_min) { /* loop*/ OPJ_UINT32 pino; /* tile coding parameter*/ opj_tcp_t *l_tcp = 00; /* current poc being updated*/ opj_poc_t * l_current_poc = 00; /* number of pocs*/ OPJ_UINT32 l_poc_bound; /* preconditions in debug*/ assert(p_cp != 00); assert(p_tileno < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps [p_tileno]; /* number of iterations in the loop */ l_poc_bound = l_tcp->numpocs+1; /* start at first element, and to make sure the compiler will not make a calculation each time in the loop store a pointer to the current element to modify rather than l_tcp->pocs[i]*/ l_current_poc = l_tcp->pocs; for (pino = 0; pino < l_poc_bound ; ++pino) { l_current_poc->compS = 0; l_current_poc->compE = p_num_comps;/*p_image->numcomps;*/ l_current_poc->resS = 0; l_current_poc->resE = p_max_res; l_current_poc->layS = 0; l_current_poc->layE = l_tcp->numlayers; l_current_poc->prg = l_tcp->prg; l_current_poc->prcS = 0; l_current_poc->prcE = p_max_prec; l_current_poc->txS = (OPJ_UINT32)p_tx0; l_current_poc->txE = (OPJ_UINT32)p_tx1; l_current_poc->tyS = (OPJ_UINT32)p_ty0; l_current_poc->tyE = (OPJ_UINT32)p_ty1; l_current_poc->dx = p_dx_min; l_current_poc->dy = p_dy_min; ++ l_current_poc; } } void opj_pi_update_decode_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; opj_poc_t* l_current_poc = 0; OPJ_ARG_NOT_USED(p_max_res); /* preconditions in debug*/ assert(p_pi != 00); assert(p_tcp != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; l_current_poc = p_tcp->pocs; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = l_current_poc->prg; /* Progression Order #0 */ l_current_pi->first = 1; l_current_pi->poc.resno0 = l_current_poc->resno0; /* Resolution Level Index #0 (Start) */ l_current_pi->poc.compno0 = l_current_poc->compno0; /* Component Index #0 (Start) */ l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = l_current_poc->resno1; /* Resolution Level Index #0 (End) */ l_current_pi->poc.compno1 = l_current_poc->compno1; /* Component Index #0 (End) */ l_current_pi->poc.layno1 = l_current_poc->layno1; /* Layer Index #0 (End) */ l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; ++l_current_poc; } } void opj_pi_update_decode_not_poc (opj_pi_iterator_t * p_pi, opj_tcp_t * p_tcp, OPJ_UINT32 p_max_precision, OPJ_UINT32 p_max_res) { /* loop*/ OPJ_UINT32 pino; /* encoding prameters to set*/ OPJ_UINT32 l_bound; opj_pi_iterator_t * l_current_pi = 00; /* preconditions in debug*/ assert(p_tcp != 00); assert(p_pi != 00); /* initializations*/ l_bound = p_tcp->numpocs+1; l_current_pi = p_pi; for (pino = 0;pino<l_bound;++pino) { l_current_pi->poc.prg = p_tcp->prg; l_current_pi->first = 1; l_current_pi->poc.resno0 = 0; l_current_pi->poc.compno0 = 0; l_current_pi->poc.layno0 = 0; l_current_pi->poc.precno0 = 0; l_current_pi->poc.resno1 = p_max_res; l_current_pi->poc.compno1 = l_current_pi->numcomps; l_current_pi->poc.layno1 = p_tcp->numlayers; l_current_pi->poc.precno1 = p_max_precision; ++l_current_pi; } } OPJ_BOOL opj_pi_check_next_level( OPJ_INT32 pos, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, const OPJ_CHAR *prog) { OPJ_INT32 i; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp = &tcps->pocs[pino]; if(pos>=0){ for(i=pos;pos>=0;i--){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'C': if(tcp->comp_t==tcp->compE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'L': if(tcp->lay_t==tcp->layE){ if(opj_pi_check_next_level(pos-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: /* fall through */ case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; } break; default: if(tcp->tx0_t == tcp->txE){ /*TY*/ if(tcp->ty0_t == tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ return OPJ_TRUE; }else{ return OPJ_FALSE; } }else{ return OPJ_TRUE; }/*TY*/ }else{ return OPJ_TRUE; } break; }/*end case P*/ }/*end switch*/ }/*end for*/ }/*end if*/ return OPJ_FALSE; } /* ========================================================== Packet iterator interface ========================================================== */ opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no) { /* loop */ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions */ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers */ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations */ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi */ l_pi = opj_pi_create(p_image, p_cp, p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array */ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters */ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations */ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator */ l_current_pi = l_pi; /* memory allocation for include */ l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator */ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_img_comp->dx;*/ /*l_current_pi->dy = l_img_comp->dy;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; /*l_current_pi->dx = l_dx_min;*/ /*l_current_pi->dy = l_dy_min;*/ l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC) { opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res); } else { opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res); } return l_pi; } opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no, J2K_T2_MODE p_t2_mode ) { /* loop*/ OPJ_UINT32 pino; OPJ_UINT32 compno, resno; /* to store w, h, dx and dy fro all components and resolutions*/ OPJ_UINT32 * l_tmp_data; OPJ_UINT32 ** l_tmp_ptr; /* encoding prameters to set*/ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; OPJ_UINT32 l_bound; OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ; OPJ_UINT32 l_data_stride; /* pointers*/ opj_pi_iterator_t *l_pi = 00; opj_tcp_t *l_tcp = 00; const opj_tccp_t *l_tccp = 00; opj_pi_comp_t *l_current_comp = 00; opj_image_comp_t * l_img_comp = 00; opj_pi_iterator_t * l_current_pi = 00; OPJ_UINT32 * l_encoding_value_ptr = 00; /* preconditions in debug*/ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); /* initializations*/ l_tcp = &p_cp->tcps[p_tile_no]; l_bound = l_tcp->numpocs+1; l_data_stride = 4 * OPJ_J2K_MAXRLVLS; l_tmp_data = (OPJ_UINT32*)opj_malloc( l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32)); if (! l_tmp_data) { return 00; } l_tmp_ptr = (OPJ_UINT32**)opj_malloc( p_image->numcomps * sizeof(OPJ_UINT32 *)); if (! l_tmp_ptr) { opj_free(l_tmp_data); return 00; } /* memory allocation for pi*/ l_pi = opj_pi_create(p_image,p_cp,p_tile_no); if (!l_pi) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); return 00; } l_encoding_value_ptr = l_tmp_data; /* update pointer array*/ for (compno = 0; compno < p_image->numcomps; ++compno) { l_tmp_ptr[compno] = l_encoding_value_ptr; l_encoding_value_ptr += l_data_stride; } /* get encoding parameters*/ opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr); /* step calculations*/ l_step_p = 1; l_step_c = l_max_prec * l_step_p; l_step_r = p_image->numcomps * l_step_c; l_step_l = l_max_res * l_step_r; /* set values for first packet iterator*/ l_pi->tp_on = p_cp->m_specific_param.m_enc.m_tp_on; l_current_pi = l_pi; /* memory allocation for include*/ l_current_pi->include = (OPJ_INT16*) opj_calloc(l_tcp->numlayers * l_step_l, sizeof(OPJ_INT16)); if (!l_current_pi->include) { opj_free(l_tmp_data); opj_free(l_tmp_ptr); opj_pi_destroy(l_pi, l_bound); return 00; } /* special treatment for the first packet iterator*/ l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } ++l_current_pi; for (pino = 1 ; pino<l_bound ; ++pino ) { l_current_comp = l_current_pi->comps; l_img_comp = p_image->comps; l_tccp = l_tcp->tccps; l_current_pi->tx0 = l_tx0; l_current_pi->ty0 = l_ty0; l_current_pi->tx1 = l_tx1; l_current_pi->ty1 = l_ty1; l_current_pi->dx = l_dx_min; l_current_pi->dy = l_dy_min; l_current_pi->step_p = l_step_p; l_current_pi->step_c = l_step_c; l_current_pi->step_r = l_step_r; l_current_pi->step_l = l_step_l; /* allocation for components and number of components has already been calculated by opj_pi_create */ for (compno = 0; compno < l_current_pi->numcomps; ++compno) { opj_pi_resolution_t *l_res = l_current_comp->resolutions; l_encoding_value_ptr = l_tmp_ptr[compno]; l_current_comp->dx = l_img_comp->dx; l_current_comp->dy = l_img_comp->dy; /* resolutions have already been initialized */ for (resno = 0; resno < l_current_comp->numresolutions; resno++) { l_res->pdx = *(l_encoding_value_ptr++); l_res->pdy = *(l_encoding_value_ptr++); l_res->pw = *(l_encoding_value_ptr++); l_res->ph = *(l_encoding_value_ptr++); ++l_res; } ++l_current_comp; ++l_img_comp; ++l_tccp; } /* special treatment*/ l_current_pi->include = (l_current_pi-1)->include; ++l_current_pi; } opj_free(l_tmp_data); l_tmp_data = 00; opj_free(l_tmp_ptr); l_tmp_ptr = 00; if (l_tcp->POC && (OPJ_IS_CINEMA(p_cp->rsiz) || p_t2_mode == FINAL_PASS)) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } return l_pi; } void opj_pi_create_encode( opj_pi_iterator_t *pi, opj_cp_t *cp, OPJ_UINT32 tileno, OPJ_UINT32 pino, OPJ_UINT32 tpnum, OPJ_INT32 tppos, J2K_T2_MODE t2_mode) { const OPJ_CHAR *prog; OPJ_INT32 i; OPJ_UINT32 incr_top=1,resetX=0; opj_tcp_t *tcps =&cp->tcps[tileno]; opj_poc_t *tcp= &tcps->pocs[pino]; prog = opj_j2k_convert_progression_order(tcp->prg); pi[pino].first = 1; pi[pino].poc.prg = tcp->prg; if(!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) && (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))){ pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; }else { for(i=tppos+1;i<4;i++){ switch(prog[i]){ case 'R': pi[pino].poc.resno0 = tcp->resS; pi[pino].poc.resno1 = tcp->resE; break; case 'C': pi[pino].poc.compno0 = tcp->compS; pi[pino].poc.compno1 = tcp->compE; break; case 'L': pi[pino].poc.layno0 = tcp->layS; pi[pino].poc.layno1 = tcp->layE; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prcS; pi[pino].poc.precno1 = tcp->prcE; break; default: pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS; pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE; pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE; break; } break; } } if(tpnum==0){ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; break; case 'R': tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; break; case 'L': tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; break; default: tcp->tx0_t = tcp->txS; tcp->ty0_t = tcp->tyS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; break; } break; } } incr_top=1; }else{ for(i=tppos;i>=0;i--){ switch(prog[i]){ case 'C': pi[pino].poc.compno0 = tcp->comp_t-1; pi[pino].poc.compno1 = tcp->comp_t; break; case 'R': pi[pino].poc.resno0 = tcp->res_t-1; pi[pino].poc.resno1 = tcp->res_t; break; case 'L': pi[pino].poc.layno0 = tcp->lay_t-1; pi[pino].poc.layno1 = tcp->lay_t; break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: pi[pino].poc.precno0 = tcp->prc_t-1; pi[pino].poc.precno1 = tcp->prc_t; break; default: pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx)); pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ; pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy)); pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ; break; } break; } if(incr_top==1){ switch(prog[i]){ case 'R': if(tcp->res_t==tcp->resE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->res_t = tcp->resS; pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.resno0 = tcp->res_t; pi[pino].poc.resno1 = tcp->res_t+1; tcp->res_t+=1; incr_top=0; } break; case 'C': if(tcp->comp_t ==tcp->compE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->comp_t = tcp->compS; pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.compno0 = tcp->comp_t; pi[pino].poc.compno1 = tcp->comp_t+1; tcp->comp_t+=1; incr_top=0; } break; case 'L': if(tcp->lay_t == tcp->layE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->lay_t = tcp->layS; pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.layno0 = tcp->lay_t; pi[pino].poc.layno1 = tcp->lay_t+1; tcp->lay_t+=1; incr_top=0; } break; case 'P': switch(tcp->prg){ case OPJ_LRCP: case OPJ_RLCP: if(tcp->prc_t == tcp->prcE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->prc_t = tcp->prcS; pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=1; }else{ incr_top=0; } }else{ pi[pino].poc.precno0 = tcp->prc_t; pi[pino].poc.precno1 = tcp->prc_t+1; tcp->prc_t+=1; incr_top=0; } break; default: if(tcp->tx0_t >= tcp->txE){ if(tcp->ty0_t >= tcp->tyE){ if(opj_pi_check_next_level(i-1,cp,tileno,pino,prog)){ tcp->ty0_t = tcp->tyS; pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=1;resetX=1; }else{ incr_top=0;resetX=0; } }else{ pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t; pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy)); tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1; incr_top=0;resetX=1; } if(resetX==1){ tcp->tx0_t = tcp->txS; pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; } }else{ pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t; pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx- (tcp->tx0_t % tcp->dx)); tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1; incr_top=0; } break; } break; } } } } } } void opj_pi_destroy(opj_pi_iterator_t *p_pi, OPJ_UINT32 p_nb_elements) { OPJ_UINT32 compno, pino; opj_pi_iterator_t *l_current_pi = p_pi; if (p_pi) { if (p_pi->include) { opj_free(p_pi->include); p_pi->include = 00; } for (pino = 0; pino < p_nb_elements; ++pino){ if(l_current_pi->comps) { opj_pi_comp_t *l_current_component = l_current_pi->comps; for (compno = 0; compno < l_current_pi->numcomps; compno++){ if(l_current_component->resolutions) { opj_free(l_current_component->resolutions); l_current_component->resolutions = 00; } ++l_current_component; } opj_free(l_current_pi->comps); l_current_pi->comps = 0; } ++l_current_pi; } opj_free(p_pi); } } void opj_pi_update_encoding_parameters( const opj_image_t *p_image, opj_cp_t *p_cp, OPJ_UINT32 p_tile_no ) { /* encoding parameters to set */ OPJ_UINT32 l_max_res; OPJ_UINT32 l_max_prec; OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1; OPJ_UINT32 l_dx_min,l_dy_min; /* pointers */ opj_tcp_t *l_tcp = 00; /* preconditions */ assert(p_cp != 00); assert(p_image != 00); assert(p_tile_no < p_cp->tw * p_cp->th); l_tcp = &(p_cp->tcps[p_tile_no]); /* get encoding parameters */ opj_get_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res); if (l_tcp->POC) { opj_pi_update_encode_poc_and_final(p_cp,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } else { opj_pi_update_encode_not_poc(p_cp,p_image->numcomps,p_tile_no,l_tx0,l_tx1,l_ty0,l_ty1,l_max_prec,l_max_res,l_dx_min,l_dy_min); } } OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi) { switch (pi->poc.prg) { case OPJ_LRCP: return opj_pi_next_lrcp(pi); case OPJ_RLCP: return opj_pi_next_rlcp(pi); case OPJ_RPCL: return opj_pi_next_rpcl(pi); case OPJ_PCRL: return opj_pi_next_pcrl(pi); case OPJ_CPRL: return opj_pi_next_cprl(pi); case OPJ_PROG_UNKNOWN: return OPJ_FALSE; } return OPJ_FALSE; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_540_0
crossvul-cpp_data_good_4799_1
/* $Id$ */ /* * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Revised: 2/18/01 BAR -- added syntax for extracting single images from * multi-image TIFF files. * * New syntax is: sourceFileName,image# * * image# ranges from 0..<n-1> where n is the # of images in the file. * There may be no white space between the comma and the filename or * image number. * * Example: tiffcp source.tif,1 destination.tif * * Copies the 2nd image in source.tif to the destination. * ***** * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ #include "tif_config.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #include "tiffio.h" #ifndef HAVE_GETOPT extern int getopt(int, char**, char*); #endif #if defined(VMS) # define unlink delete #endif #define streq(a,b) (strcmp(a,b) == 0) #define strneq(a,b,n) (strncmp(a,b,n) == 0) #define TRUE 1 #define FALSE 0 static int outtiled = -1; static uint32 tilewidth; static uint32 tilelength; static uint16 config; static uint16 compression; static uint16 predictor; static int preset; static uint16 fillorder; static uint16 orientation; static uint32 rowsperstrip; static uint32 g3opts; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 75; /* JPEG quality */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int defpreset = -1; static int tiffcp(TIFF*, TIFF*); static int processCompressOptions(char*); static void usage(void); static char comma = ','; /* (default) comma separator character */ static TIFF* bias = NULL; static int pageNum = 0; static int pageInSeq = 0; static int nextSrcImage (TIFF *tif, char **imageSpec) /* seek to the next image specified in *imageSpec returns 1 if success, 0 if no more images to process *imageSpec=NULL if subsequent images should be processed in sequence */ { if (**imageSpec == comma) { /* if not @comma, we've done all images */ char *start = *imageSpec + 1; tdir_t nextImage = (tdir_t)strtol(start, imageSpec, 0); if (start == *imageSpec) nextImage = TIFFCurrentDirectory (tif); if (**imageSpec) { if (**imageSpec == comma) { /* a trailing comma denotes remaining images in sequence */ if ((*imageSpec)[1] == '\0') *imageSpec = NULL; }else{ fprintf (stderr, "Expected a %c separated image # list after %s\n", comma, TIFFFileName (tif)); exit (-4); /* syntax error */ } } if (TIFFSetDirectory (tif, nextImage)) return 1; fprintf (stderr, "%s%c%d not found!\n", TIFFFileName(tif), comma, (int) nextImage); } return 0; } static TIFF* openSrcImage (char **imageSpec) /* imageSpec points to a pointer to a filename followed by optional ,image#'s Open the TIFF file and assign *imageSpec to either NULL if there are no images specified, or a pointer to the next image number text */ { TIFF *tif; char *fn = *imageSpec; *imageSpec = strchr (fn, comma); if (*imageSpec) { /* there is at least one image number specifier */ **imageSpec = '\0'; tif = TIFFOpen (fn, "r"); /* but, ignore any single trailing comma */ if (!(*imageSpec)[1]) {*imageSpec = NULL; return tif;} if (tif) { **imageSpec = comma; /* replace the comma */ if (!nextSrcImage(tif, imageSpec)) { TIFFClose (tif); tif = NULL; } } }else tif = TIFFOpen (fn, "r"); return tif; } int main(int argc, char* argv[]) { uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) -1; uint32 deftilelength = (uint32) -1; uint32 defrowsperstrip = (uint32) 0; uint64 diroff = 0; TIFF* in; TIFF* out; char mode[10]; char* mp = mode; int c; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, ",:b:c:f:l:o:p:r:w:aistBLMC8x")) != -1) switch (c) { case ',': if (optarg[0] != '=') usage(); comma = optarg[1]; break; case 'b': /* this file is bias image subtracted from others */ if (bias) { fputs ("Only 1 bias image may be specified\n", stderr); exit (-2); } { uint16 samples = (uint16) -1; char **biasFn = &optarg; bias = openSrcImage (biasFn); if (!bias) exit (-5); if (TIFFIsTiled (bias)) { fputs ("Bias image must be organized in strips\n", stderr); exit (-7); } TIFFGetField(bias, TIFFTAG_SAMPLESPERPIXEL, &samples); if (samples != 1) { fputs ("Bias image must be monochrome\n", stderr); exit (-7); } } break; case 'a': /* append to output */ mode[0] = 'a'; break; case 'c': /* compression scheme */ if (!processCompressOptions(optarg)) usage(); break; case 'f': /* fill order */ if (streq(optarg, "lsb2msb")) deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) deffillorder = FILLORDER_MSB2LSB; else usage(); break; case 'i': /* ignore errors */ ignore = TRUE; break; case 'l': /* tile length */ outtiled = TRUE; deftilelength = atoi(optarg); break; case 'o': /* initial directory offset */ diroff = strtoul(optarg, NULL, 0); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) defconfig = PLANARCONFIG_CONTIG; else usage(); break; case 'r': /* rows/strip */ defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'w': /* tile width */ outtiled = TRUE; deftilewidth = atoi(optarg); break; case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; case '8': *mp++ = '8'; *mp = '\0'; break; case 'x': pageInSeq = 1; break; case '?': usage(); /*NOTREACHED*/ } if (argc - optind < 2) usage(); out = TIFFOpen(argv[argc-1], mode); if (out == NULL) return (-2); if ((argc - optind) == 2) pageNum = -1; for (; optind < argc-1 ; optind++) { char *imageCursor = argv[optind]; in = openSrcImage (&imageCursor); if (in == NULL) { (void) TIFFClose(out); return (-3); } if (diroff != 0 && !TIFFSetSubDirectory(in, diroff)) { TIFFError(TIFFFileName(in), "Error, setting subdirectory at " TIFF_UINT64_FORMAT, diroff); (void) TIFFClose(in); (void) TIFFClose(out); return (1); } for (;;) { config = defconfig; compression = defcompression; predictor = defpredictor; preset = defpreset; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (!tiffcp(in, out) || !TIFFWriteDirectory(out)) { (void) TIFFClose(in); (void) TIFFClose(out); return (1); } if (imageCursor) { /* seek next image directory */ if (!nextSrcImage(in, &imageCursor)) break; }else if (!TIFFReadDirectory(in)) break; } (void) TIFFClose(in); } (void) TIFFClose(out); return (0); } static void processZIPOptions(char* cp) { if ( (cp = strchr(cp, ':')) ) { do { cp++; if (isdigit((int)*cp)) defpredictor = atoi(cp); else if (*cp == 'p') defpreset = atoi(++cp); else usage(); } while( (cp = strchr(cp, ':')) ); } } static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { if (streq(opt, "none")) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { char* cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while( cp ) { if (isdigit((int)cp[1])) quality = atoi(cp+1); else if (cp[1] == 'r' ) jpegcolormode = JPEGCOLORMODE_RAW; else usage(); cp = strchr(cp+1,':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { char* cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { processZIPOptions(opt); defcompression = COMPRESSION_ADOBE_DEFLATE; } else if (strneq(opt, "lzma", 4)) { processZIPOptions(opt); defcompression = COMPRESSION_LZMA; } else if (strneq(opt, "jbig", 4)) { defcompression = COMPRESSION_JBIG; } else if (strneq(opt, "sgilog", 6)) { defcompression = COMPRESSION_SGILOG; } else return (0); return (1); } char* stuff[] = { "usage: tiffcp [options] input... output", "where options are:", " -a append to output instead of overwriting", " -o offset set initial directory offset", " -p contig pack samples contiguously (e.g. RGBRGB...)", " -p separate store samples separately (e.g. RRR...GGG...BBB...)", " -s write output in strips", " -t write output in tiles", " -x force the merged tiff pages in sequence", " -8 write BigTIFF instead of default ClassicTIFF", " -B write big-endian instead of native byte order", " -L write little-endian instead of native byte order", " -M disable use of memory-mapped files", " -C disable strip chopping", " -i ignore read errors", " -b file[,#] bias (dark) monochrome image to be subtracted from all others", " -,=% use % rather than , to separate image #'s (per Note below)", "", " -r # make each strip have no more than # rows", " -w # set output tile width (pixels)", " -l # set output tile length (pixels)", "", " -f lsb2msb force lsb-to-msb FillOrder for output", " -f msb2lsb force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] compress output with deflate encoding", " -c lzma[:opts] compress output with LZMA2 encoding", " -c jpeg[:opts] compress output with JPEG encoding", " -c jbig compress output with ISO JBIG encoding", " -c packbits compress output with packbits encoding", " -c g3[:opts] compress output with CCITT Group 3 encoding", " -c g4 compress output with CCITT Group 4 encoding", " -c sgilog compress output with SGILOG encoding", " -c none use no compression algorithm on output", "", "Group 3 options:", " 1d use default CCITT Group 3 1D-encoding", " 2d use optional CCITT Group 3 2D-encoding", " fill byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", "", "JPEG options:", " # set compression quality level (0-100, default 75)", " r output color image as RGB rather than YCbCr", "For example, -c jpeg:r:50 to get JPEG-encoded RGB data with 50% comp. quality", "", "LZW, Deflate (ZIP) and LZMA2 options:", " # set predictor value", " p# set compression level (preset)", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing,", "-c zip:3:p9 for Deflate encoding with maximum compression level and floating", "point predictor.", "", "Note that input filenames may be of the form filename,x,y,z", "where x, y, and z specify image numbers in the filename to copy.", "example: tiffcp -c none -b esp.tif,1 esp.tif,0 test.tif", " subtract 2nd image in esp.tif from 1st yielding uncompressed result test.tif", NULL }; static void usage(void) { char buf[BUFSIZ]; int i; setbuf(stderr, buf); fprintf(stderr, "%s\n\n", TIFFGetVersion()); for (i = 0; stuff[i] != NULL; i++) fprintf(stderr, "%s\n", stuff[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped.", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) typedef int (*copyFunc) (TIFF* in, TIFF* out, uint32 l, uint32 w, uint16 samplesperpixel); static copyFunc pickCopyFunc(TIFF*, TIFF*, uint16, uint16); /* PODD */ static int tiffcp(TIFF* in, TIFF* out) { uint16 bitspersample, samplesperpixel = 1; uint16 input_compression, input_photometric = PHOTOMETRIC_MINISBLACK; copyFunc cf; uint32 width, length; struct cpTag* p; CopyField(TIFFTAG_IMAGEWIDTH, width); CopyField(TIFFTAG_IMAGELENGTH, length); CopyField(TIFFTAG_BITSPERSAMPLE, bitspersample); CopyField(TIFFTAG_SAMPLESPERPIXEL, samplesperpixel); if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else CopyField(TIFFTAG_COMPRESSION, compression); TIFFGetFieldDefaulted(in, TIFFTAG_COMPRESSION, &input_compression); TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric); if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else if (input_photometric == PHOTOMETRIC_YCBCR) { /* Otherwise, can't handle subsampled input */ uint16 subsamplinghor,subsamplingver; TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if (subsamplinghor!=1 || subsamplingver!=1) { fprintf(stderr, "tiffcp: %s: Can't copy/convert subsampled image.\n", TIFFFileName(in)); return FALSE; } } if (compression == COMPRESSION_JPEG) { if (input_photometric == PHOTOMETRIC_RGB && jpegcolormode == JPEGCOLORMODE_RGB) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, samplesperpixel == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else if (input_compression == COMPRESSION_JPEG && samplesperpixel == 3 ) { /* RGB conversion was forced above hence the output will be of the same type */ TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB); } else CopyTag(TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT); if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* * Will copy `Orientation' tag from input image */ TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); switch (orientation) { case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: /* XXX */ TIFFWarning(TIFFFileName(in), "using bottom-left orientation"); orientation = ORIENTATION_BOTLEFT; /* fall thru... */ case ORIENTATION_LEFTBOT: /* XXX */ case ORIENTATION_BOTLEFT: break; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: /* XXX */ default: TIFFWarning(TIFFFileName(in), "using top-left orientation"); orientation = ORIENTATION_TOPLEFT; /* fall thru... */ case ORIENTATION_LEFTTOP: /* XXX */ case ORIENTATION_TOPLEFT: break; } TIFFSetField(out, TIFFTAG_ORIENTATION, orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) -1) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) -1) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) { rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); } if (rowsperstrip > length && rowsperstrip != (uint32)-1) rowsperstrip = length; } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (samplesperpixel <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); break; case COMPRESSION_JBIG: CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); CopyTag(TIFFTAG_FAXDCS, 1, TIFF_ASCII); break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: case COMPRESSION_LZMA: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); if (preset != -1) { if (compression == COMPRESSION_ADOBE_DEFLATE || compression == COMPRESSION_DEFLATE) TIFFSetField(out, TIFFTAG_ZIPQUALITY, preset); else if (compression == COMPRESSION_LZMA) TIFFSetField(out, TIFFTAG_LZMAPRESET, preset); } break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); cp++; inknameslen += (strlen(cp) + 1); ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (pageInSeq == 1) { if (pageNum < 0) /* only one input file */ { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); } else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } else { if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); cf = pickCopyFunc(in, out, bitspersample, samplesperpixel); return (cf ? (*cf)(in, out, length, width, samplesperpixel) : FALSE); } /* * Copy Functions. */ #define DECLAREcpFunc(x) \ static int x(TIFF* in, TIFF* out, \ uint32 imagelength, uint32 imagewidth, tsample_t spp) #define DECLAREreadFunc(x) \ static int x(TIFF* in, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*readFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); #define DECLAREwriteFunc(x) \ static int x(TIFF* out, \ uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp) typedef int (*writeFunc)(TIFF*, uint8*, uint32, uint32, tsample_t); /* * Contig -> contig by scanline for rows/strip change. */ DECLAREcpFunc(cpContig2ContigByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } typedef void biasFn (void *image, void *bias, uint32 pixels); #define subtract(bits) \ static void subtract##bits (void *i, void *b, uint32 pixels)\ {\ uint##bits *image = i;\ uint##bits *bias = b;\ while (pixels--) {\ *image = *image > *bias ? *image-*bias : 0;\ image++, bias++; \ } \ } subtract(8) subtract(16) subtract(32) static biasFn *lineSubtractFn (unsigned bits) { switch (bits) { case 8: return subtract8; case 16: return subtract16; case 32: return subtract32; } return NULL; } /* * Contig -> contig by scanline while subtracting a bias image. */ DECLAREcpFunc(cpBiasedContig2Contig) { if (spp == 1) { tsize_t biasSize = TIFFScanlineSize(bias); tsize_t bufSize = TIFFScanlineSize(in); tdata_t buf, biasBuf; uint32 biasWidth = 0, biasLength = 0; TIFFGetField(bias, TIFFTAG_IMAGEWIDTH, &biasWidth); TIFFGetField(bias, TIFFTAG_IMAGELENGTH, &biasLength); if (biasSize == bufSize && imagelength == biasLength && imagewidth == biasWidth) { uint16 sampleBits = 0; biasFn *subtractLine; TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &sampleBits); subtractLine = lineSubtractFn (sampleBits); if (subtractLine) { uint32 row; buf = _TIFFmalloc(bufSize); biasBuf = _TIFFmalloc(bufSize); for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFReadScanline(bias, biasBuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read biased scanline %lu", (unsigned long) row); goto bad; } subtractLine (buf, biasBuf, imagewidth); if (TIFFWriteScanline(out, buf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } _TIFFfree(buf); _TIFFfree(biasBuf); TIFFSetDirectory(bias, TIFFCurrentDirectory(bias)); /* rewind */ return 1; bad: _TIFFfree(buf); _TIFFfree(biasBuf); return 0; } else { TIFFError(TIFFFileName(in), "No support for biasing %d bit pixels\n", sampleBits); return 0; } } TIFFError(TIFFFileName(in), "Bias image %s,%d\nis not the same size as %s,%d\n", TIFFFileName(bias), TIFFCurrentDirectory(bias), TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } else { TIFFError(TIFFFileName(in), "Can't bias %s,%d as it has >1 Sample/Pixel\n", TIFFFileName(in), TIFFCurrentDirectory(in)); return 0; } } /* * Strip -> strip for change in encoding. */ DECLAREcpFunc(cpDecodedStrips) { tsize_t stripsize = TIFFStripSize(in); tdata_t buf = _TIFFmalloc(stripsize); (void) imagewidth; (void) spp; if (buf) { tstrip_t s, ns = TIFFNumberOfStrips(in); uint32 row = 0; _TIFFmemset(buf, 0, stripsize); for (s = 0; s < ns && row < imagelength; s++) { tsize_t cc = (row + rowsperstrip > imagelength) ? TIFFVStripSize(in, imagelength - row) : stripsize; if (TIFFReadEncodedStrip(in, s, buf, cc) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu", (unsigned long) s); goto bad; } if (TIFFWriteEncodedStrip(out, s, buf, cc) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %lu", (unsigned long) s); goto bad; } row += rowsperstrip; } _TIFFfree(buf); return 1; } else { TIFFError(TIFFFileName(in), "Error, can't allocate memory buffer of size %lu " "to read strips", (unsigned long) stripsize); return 0; } bad: _TIFFfree(buf); return 0; } /* * Separate -> separate by row for rows/strip change. */ DECLAREcpFunc(cpSeparate2SeparateByRow) { tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t buf; uint32 row; tsample_t s; (void) imagewidth; buf = _TIFFmalloc(scanlinesize); if (!buf) return 0; _TIFFmemset(buf, 0, scanlinesize); for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, buf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } if (TIFFWriteScanline(out, buf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } _TIFFfree(buf); return 1; bad: _TIFFfree(buf); return 0; } /* * Contig -> separate by row. */ DECLAREcpFunc(cpContig2SeparateByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); /* unpack channels */ for (s = 0; s < spp; s++) { for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, inbuf, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = ((uint8*)inbuf) + s; outp = (uint8*)outbuf; for (n = imagewidth; n-- > 0;) { *outp++ = *inp; inp += spp; } if (TIFFWriteScanline(out, outbuf, row, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } /* * Separate -> contig by row. */ DECLAREcpFunc(cpSeparate2ContigByRow) { tsize_t scanlinesizein = TIFFScanlineSize(in); tsize_t scanlinesizeout = TIFFScanlineSize(out); tdata_t inbuf; tdata_t outbuf; register uint8 *inp, *outp; register uint32 n; uint32 row; tsample_t s; inbuf = _TIFFmalloc(scanlinesizein); outbuf = _TIFFmalloc(scanlinesizeout); if (!inbuf || !outbuf) goto bad; _TIFFmemset(inbuf, 0, scanlinesizein); _TIFFmemset(outbuf, 0, scanlinesizeout); for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { if (TIFFReadScanline(in, inbuf, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); goto bad; } inp = (uint8*)inbuf; outp = ((uint8*)outbuf) + s; for (n = imagewidth; n-- > 0;) { *outp = *inp++; outp += spp; } } if (TIFFWriteScanline(out, outbuf, row, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write scanline %lu", (unsigned long) row); goto bad; } } if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 1; bad: if (inbuf) _TIFFfree(inbuf); if (outbuf) _TIFFfree(outbuf); return 0; } static void cpStripToTile(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int64 inskew) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) *out++ = *in++; out += outskew; in += inskew; } } static void cpContigBufToSeparateBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample ) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } in += (spp-1) * bytes_per_sample; } out += outskew; in += inskew; } } static void cpSeparateBufToContigBuf(uint8* out, uint8* in, uint32 rows, uint32 cols, int outskew, int inskew, tsample_t spp, int bytes_per_sample) { while (rows-- > 0) { uint32 j = cols; while (j-- > 0) { int n = bytes_per_sample; while( n-- ) { *out++ = *in++; } out += (spp-1)*bytes_per_sample; } out += outskew; in += inskew; } } static int cpImage(TIFF* in, TIFF* out, readFunc fin, writeFunc fout, uint32 imagelength, uint32 imagewidth, tsample_t spp) { int status = 0; tdata_t buf = NULL; tsize_t scanlinesize = TIFFRasterScanlineSize(in); tsize_t bytes = scanlinesize * (tsize_t)imagelength; /* * XXX: Check for integer overflow. */ if (scanlinesize && imagelength && bytes / (tsize_t)imagelength == scanlinesize) { buf = _TIFFmalloc(bytes); if (buf) { if ((*fin)(in, (uint8*)buf, imagelength, imagewidth, spp)) { status = (*fout)(out, (uint8*)buf, imagelength, imagewidth, spp); } _TIFFfree(buf); } else { TIFFError(TIFFFileName(in), "Error, can't allocate space for image buffer"); } } else { TIFFError(TIFFFileName(in), "Error, no space for image buffer"); } return status; } DECLAREreadFunc(readContigStripsIntoBuffer) { tsize_t scanlinesize = TIFFScanlineSize(in); uint8* bufp = buf; uint32 row; (void) imagewidth; (void) spp; for (row = 0; row < imagelength; row++) { if (TIFFReadScanline(in, (tdata_t) bufp, row, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); return 0; } bufp += scanlinesize; } return 1; } DECLAREreadFunc(readSeparateStripsIntoBuffer) { int status = 1; tsize_t scanlinesize = TIFFScanlineSize(in); tdata_t scanline; if (!scanlinesize) return 0; scanline = _TIFFmalloc(scanlinesize); if (!scanline) return 0; _TIFFmemset(scanline, 0, scanlinesize); (void) imagewidth; if (scanline) { uint8* bufp = (uint8*) buf; uint32 row; tsample_t s; for (row = 0; row < imagelength; row++) { /* merge channels */ for (s = 0; s < spp; s++) { uint8* bp = bufp + s; tsize_t n = scanlinesize; uint8* sbuf = scanline; if (TIFFReadScanline(in, scanline, row, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read scanline %lu", (unsigned long) row); status = 0; goto done; } while (n-- > 0) *bp = *sbuf++, bp += spp; } bufp += scanlinesize * spp; } } done: _TIFFfree(scanline); return status; } DECLAREreadFunc(readContigTilesIntoBuffer) { int status = 1; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint32 imagew = TIFFScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int64 iskew = (int64)imagew - (int64)tilew; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; (void) spp; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { if (TIFFReadTile(in, tilebuf, col, row, 0, 0) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu", (unsigned long) col, (unsigned long) row); status = 0; goto done; } if (colb > iskew) { uint32 width = imagew - colb; uint32 oskew = tilew - width; cpStripToTile(bufp + colb, tilebuf, nrow, width, oskew + iskew, oskew ); } else cpStripToTile(bufp + colb, tilebuf, nrow, tilew, iskew, 0); colb += tilew; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREreadFunc(readSeparateTilesIntoBuffer) { int status = 1; uint32 imagew = TIFFRasterScanlineSize(in); uint32 tilew = TIFFTileRowSize(in); int iskew = imagew - tilew*spp; tsize_t tilesize = TIFFTileSize(in); tdata_t tilebuf; uint8* bufp = (uint8*) buf; uint32 tw, tl; uint32 row; uint16 bps = 0, bytes_per_sample; tilebuf = _TIFFmalloc(tilesize); if (tilebuf == 0) return 0; _TIFFmemset(tilebuf, 0, tilesize); (void) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); if( bps == 0 ) { TIFFError(TIFFFileName(in), "Error, cannot read BitsPerSample"); status = 0; goto done; } assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { if (TIFFReadTile(in, tilebuf, col, row, 0, s) < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at %lu %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; goto done; } /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew*spp > imagew) { uint32 width = imagew - colb; int oskew = tilew*spp - width; cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, width/(spp*bytes_per_sample), oskew + iskew, oskew/spp, spp, bytes_per_sample); } else cpSeparateBufToContigBuf( bufp+colb+s*bytes_per_sample, tilebuf, nrow, tw, iskew, 0, spp, bytes_per_sample); } colb += tilew*spp; } bufp += imagew * nrow; } done: _TIFFfree(tilebuf); return status; } DECLAREwriteFunc(writeBufferToContigStrips) { uint32 row, rowsperstrip; tstrip_t strip = 0; (void) imagewidth; (void) spp; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 0; } buf += stripsize; } return 1; } DECLAREwriteFunc(writeBufferToSeparateStrips) { uint32 rowsize = imagewidth * spp; uint32 rowsperstrip; tsize_t stripsize = TIFFStripSize(out); tdata_t obuf; tstrip_t strip = 0; tsample_t s; obuf = _TIFFmalloc(stripsize); if (obuf == NULL) return (0); _TIFFmemset(obuf, 0, stripsize); (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (s = 0; s < spp; s++) { uint32 row; for (row = 0; row < imagelength; row += rowsperstrip) { uint32 nrows = (row+rowsperstrip > imagelength) ? imagelength-row : rowsperstrip; tsize_t stripsize = TIFFVStripSize(out, nrows); cpContigBufToSeparateBuf( obuf, (uint8*) buf + row*rowsize + s, nrows, imagewidth, 0, 0, spp, 1); if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 0; } } } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToContigTiles) { uint32 imagew = TIFFScanlineSize(out); uint32 tilew = TIFFTileRowSize(out); int iskew = imagew - tilew; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; (void) spp; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); for (row = 0; row < imagelength; row += tilelength) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth && colb < imagew; col += tw) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = imagew - colb; int oskew = tilew - width; cpStripToTile(obuf, bufp + colb, nrow, width, oskew, oskew + iskew); } else cpStripToTile(obuf, bufp + colb, nrow, tilew, 0, iskew); if (TIFFWriteTile(out, obuf, col, row, 0, 0) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(obuf); return 0; } colb += tilew; } bufp += nrow * imagew; } _TIFFfree(obuf); return 1; } DECLAREwriteFunc(writeBufferToSeparateTiles) { uint32 imagew = TIFFScanlineSize(out); tsize_t tilew = TIFFTileRowSize(out); uint32 iimagew = TIFFRasterScanlineSize(out); int iskew = iimagew - tilew*spp; tsize_t tilesize = TIFFTileSize(out); tdata_t obuf; uint8* bufp = (uint8*) buf; uint32 tl, tw; uint32 row; uint16 bps = 0, bytes_per_sample; obuf = _TIFFmalloc(TIFFTileSize(out)); if (obuf == NULL) return 0; _TIFFmemset(obuf, 0, tilesize); (void) TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); (void) TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); if( bps == 0 ) { TIFFError(TIFFFileName(out), "Error, cannot read BitsPerSample"); _TIFFfree(obuf); return 0; } assert( bps % 8 == 0 ); bytes_per_sample = bps/8; for (row = 0; row < imagelength; row += tl) { uint32 nrow = (row+tl > imagelength) ? imagelength-row : tl; uint32 colb = 0; uint32 col; for (col = 0; col < imagewidth; col += tw) { tsample_t s; for (s = 0; s < spp; s++) { /* * Tile is clipped horizontally. Calculate * visible portion and skewing factors. */ if (colb + tilew > imagew) { uint32 width = (imagew - colb); int oskew = tilew - width; cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, width/bytes_per_sample, oskew, (oskew*spp)+iskew, spp, bytes_per_sample); } else cpContigBufToSeparateBuf(obuf, bufp + (colb*spp) + s, nrow, tilewidth, 0, iskew, spp, bytes_per_sample); if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError(TIFFFileName(out), "Error, can't write tile at %lu %lu " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 0; } } colb += tilew; } bufp += nrow * iimagew; } _TIFFfree(obuf); return 1; } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigStrips2ContigTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig strips -> separate tiles. */ DECLAREcpFunc(cpContigStrips2SeparateTiles) { return cpImage(in, out, readContigStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate strips -> contig tiles. */ DECLAREcpFunc(cpSeparateStrips2ContigTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate strips -> separate tiles. */ DECLAREcpFunc(cpSeparateStrips2SeparateTiles) { return cpImage(in, out, readSeparateStripsIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig strips -> contig tiles. */ DECLAREcpFunc(cpContigTiles2ContigTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> separate tiles. */ DECLAREcpFunc(cpContigTiles2SeparateTiles) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> contig tiles. */ DECLAREcpFunc(cpSeparateTiles2ContigTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigTiles, imagelength, imagewidth, spp); } /* * Separate tiles -> separate tiles (tile dimension change). */ DECLAREcpFunc(cpSeparateTiles2SeparateTiles) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateTiles, imagelength, imagewidth, spp); } /* * Contig tiles -> contig tiles (tile dimension change). */ DECLAREcpFunc(cpContigTiles2ContigStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Contig tiles -> separate strips. */ DECLAREcpFunc(cpContigTiles2SeparateStrips) { return cpImage(in, out, readContigTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> contig strips. */ DECLAREcpFunc(cpSeparateTiles2ContigStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToContigStrips, imagelength, imagewidth, spp); } /* * Separate tiles -> separate strips. */ DECLAREcpFunc(cpSeparateTiles2SeparateStrips) { return cpImage(in, out, readSeparateTilesIntoBuffer, writeBufferToSeparateStrips, imagelength, imagewidth, spp); } /* * Select the appropriate copy function to use. */ static copyFunc pickCopyFunc(TIFF* in, TIFF* out, uint16 bitspersample, uint16 samplesperpixel) { uint16 shortv; uint32 w, l, tw, tl; int bychunk; (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); if (shortv != config && bitspersample != 8 && samplesperpixel > 1) { fprintf(stderr, "%s: Cannot handle different planar configuration w/ bits/sample != 8\n", TIFFFileName(in)); return (NULL); } TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &w); TIFFGetField(in, TIFFTAG_IMAGELENGTH, &l); if (!(TIFFIsTiled(out) || TIFFIsTiled(in))) { uint32 irps = (uint32) -1L; TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &irps); /* if biased, force decoded copying to allow image subtraction */ bychunk = !bias && (rowsperstrip == irps); }else{ /* either in or out is tiled */ if (bias) { fprintf(stderr, "%s: Cannot handle tiled configuration w/bias image\n", TIFFFileName(in)); return (NULL); } if (TIFFIsTiled(out)) { if (!TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw)) tw = w; if (!TIFFGetField(in, TIFFTAG_TILELENGTH, &tl)) tl = l; bychunk = (tw == tilewidth && tl == tilelength); } else { /* out's not, so in must be tiled */ TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); bychunk = (tw == w && tl == rowsperstrip); } } #define T 1 #define F 0 #define pack(a,b,c,d,e) ((long)(((a)<<11)|((b)<<3)|((c)<<2)|((d)<<1)|(e))) switch(pack(shortv,config,TIFFIsTiled(in),TIFFIsTiled(out),bychunk)) { /* Strips -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,T,T): return cpContigStrips2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,T,T): return cpContigStrips2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,T,T): return cpSeparateStrips2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,T,T): return cpSeparateStrips2SeparateTiles; /* Tiles -> Tiles */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,T,T): return cpContigTiles2ContigTiles; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,T,T): return cpContigTiles2SeparateTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,T,T): return cpSeparateTiles2ContigTiles; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,T,T): return cpSeparateTiles2SeparateTiles; /* Tiles -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, T,F,T): return cpContigTiles2ContigStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, T,F,T): return cpContigTiles2SeparateStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, T,F,T): return cpSeparateTiles2ContigStrips; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, T,F,T): return cpSeparateTiles2SeparateStrips; /* Strips -> Strips */ case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,F): return bias ? cpBiasedContig2Contig : cpContig2ContigByRow; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_CONTIG, F,F,T): return cpDecodedStrips; case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_CONTIG, PLANARCONFIG_SEPARATE, F,F,T): return cpContig2SeparateByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_CONTIG, F,F,T): return cpSeparate2ContigByRow; case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,F): case pack(PLANARCONFIG_SEPARATE, PLANARCONFIG_SEPARATE, F,F,T): return cpSeparate2SeparateByRow; } #undef pack #undef F #undef T fprintf(stderr, "tiffcp: %s: Don't know how to copy/convert image.\n", TIFFFileName(in)); return (NULL); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-190/c/good_4799_1
crossvul-cpp_data_good_5167_1
#include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" #include "gdhelpers.h" #include "php.h" #ifdef _MSC_VER # if _MSC_VER >= 1300 /* in MSVC.NET these are available but only for __cplusplus and not _MSC_EXTENSIONS */ # if !defined(_MSC_EXTENSIONS) && defined(__cplusplus) # define HAVE_FABSF 1 extern float fabsf(float x); # define HAVE_FLOORF 1 extern float floorf(float x); # endif /*MSVC.NET */ # endif /* MSC */ #endif #ifndef HAVE_FABSF # define HAVE_FABSF 0 #endif #ifndef HAVE_FLOORF # define HAVE_FLOORF 0 #endif #if HAVE_FABSF == 0 /* float fabsf(float x); */ # ifndef fabsf # define fabsf(x) ((float)(fabs(x))) # endif #endif #if HAVE_FLOORF == 0 # ifndef floorf /* float floorf(float x);*/ # define floorf(x) ((float)(floor(x))) # endif #endif #ifdef _OSD_POSIX /* BS2000 uses the EBCDIC char set instead of ASCII */ #define CHARSET_EBCDIC #define __attribute__(any) /*nothing */ #endif /*_OSD_POSIX*/ #ifndef CHARSET_EBCDIC #define ASC(ch) ch #else /*CHARSET_EBCDIC */ #define ASC(ch) gd_toascii[(unsigned char)ch] static const unsigned char gd_toascii[256] = { /*00 */ 0x00, 0x01, 0x02, 0x03, 0x85, 0x09, 0x86, 0x7f, 0x87, 0x8d, 0x8e, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, /*................ */ /*10 */ 0x10, 0x11, 0x12, 0x13, 0x8f, 0x0a, 0x08, 0x97, 0x18, 0x19, 0x9c, 0x9d, 0x1c, 0x1d, 0x1e, 0x1f, /*................ */ /*20 */ 0x80, 0x81, 0x82, 0x83, 0x84, 0x92, 0x17, 0x1b, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x05, 0x06, 0x07, /*................ */ /*30 */ 0x90, 0x91, 0x16, 0x93, 0x94, 0x95, 0x96, 0x04, 0x98, 0x99, 0x9a, 0x9b, 0x14, 0x15, 0x9e, 0x1a, /*................ */ /*40 */ 0x20, 0xa0, 0xe2, 0xe4, 0xe0, 0xe1, 0xe3, 0xe5, 0xe7, 0xf1, 0x60, 0x2e, 0x3c, 0x28, 0x2b, 0x7c, /* .........`.<(+| */ /*50 */ 0x26, 0xe9, 0xea, 0xeb, 0xe8, 0xed, 0xee, 0xef, 0xec, 0xdf, 0x21, 0x24, 0x2a, 0x29, 0x3b, 0x9f, /*&.........!$*);. */ /*60 */ 0x2d, 0x2f, 0xc2, 0xc4, 0xc0, 0xc1, 0xc3, 0xc5, 0xc7, 0xd1, 0x5e, 0x2c, 0x25, 0x5f, 0x3e, 0x3f, /*-/........^,%_>?*/ /*70 */ 0xf8, 0xc9, 0xca, 0xcb, 0xc8, 0xcd, 0xce, 0xcf, 0xcc, 0xa8, 0x3a, 0x23, 0x40, 0x27, 0x3d, 0x22, /*..........:#@'=" */ /*80 */ 0xd8, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0xab, 0xbb, 0xf0, 0xfd, 0xfe, 0xb1, /*.abcdefghi...... */ /*90 */ 0xb0, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xaa, 0xba, 0xe6, 0xb8, 0xc6, 0xa4, /*.jklmnopqr...... */ /*a0 */ 0xb5, 0xaf, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0xa1, 0xbf, 0xd0, 0xdd, 0xde, 0xae, /*..stuvwxyz...... */ /*b0 */ 0xa2, 0xa3, 0xa5, 0xb7, 0xa9, 0xa7, 0xb6, 0xbc, 0xbd, 0xbe, 0xac, 0x5b, 0x5c, 0x5d, 0xb4, 0xd7, /*...........[\].. */ /*c0 */ 0xf9, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0xad, 0xf4, 0xf6, 0xf2, 0xf3, 0xf5, /*.ABCDEFGHI...... */ /*d0 */ 0xa6, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0xb9, 0xfb, 0xfc, 0xdb, 0xfa, 0xff, /*.JKLMNOPQR...... */ /*e0 */ 0xd9, 0xf7, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0xb2, 0xd4, 0xd6, 0xd2, 0xd3, 0xd5, /*..STUVWXYZ...... */ /*f0 */ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0xb3, 0x7b, 0xdc, 0x7d, 0xda, 0x7e /*0123456789.{.}.~ */ }; #endif /*CHARSET_EBCDIC */ /* 2.0.10: cast instead of floor() yields 35% performance improvement. Thanks to John Buckman. */ #define floor_cast(exp) ((long) exp) extern int gdCosT[]; extern int gdSinT[]; static void gdImageBrushApply(gdImagePtr im, int x, int y); static void gdImageTileApply(gdImagePtr im, int x, int y); static void gdImageAntiAliasedApply(gdImagePtr im, int x, int y); static int gdLayerOverlay(int dst, int src); static int gdAlphaOverlayColor(int src, int dst, int max); int gdImageGetTrueColorPixel(gdImagePtr im, int x, int y); void php_gd_error_ex(int type, const char *format, ...) { va_list args; TSRMLS_FETCH(); va_start(args, format); php_verror(NULL, "", type, format, args TSRMLS_CC); va_end(args); } void php_gd_error(const char *format, ...) { va_list args; TSRMLS_FETCH(); va_start(args, format); php_verror(NULL, "", E_WARNING, format, args TSRMLS_CC); va_end(args); } gdImagePtr gdImageCreate (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sx)) { return NULL; } im = (gdImage *) gdCalloc(1, sizeof(gdImage)); /* Row-major ever since gd 1.3 */ im->pixels = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; i < sy; i++) { /* Row-major ever since gd 1.3 */ im->pixels[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); } im->sx = sx; im->sy = sy; im->colorsTotal = 0; im->transparent = (-1); im->interlace = 0; im->thick = 1; im->AA = 0; im->AA_polygon = 0; for (i = 0; i < gdMaxColors; i++) { im->open[i] = 1; im->red[i] = 0; im->green[i] = 0; im->blue[i] = 0; } im->trueColor = 0; im->tpixels = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } gdImagePtr gdImageCreateTrueColor (int sx, int sy) { int i; gdImagePtr im; if (overflow2(sx, sy)) { return NULL; } if (overflow2(sizeof(unsigned char *), sy)) { return NULL; } if (overflow2(sizeof(int), sx)) { return NULL; } im = (gdImage *) gdMalloc(sizeof(gdImage)); memset(im, 0, sizeof(gdImage)); im->tpixels = (int **) gdMalloc(sizeof(int *) * sy); im->AA_opacity = (unsigned char **) gdMalloc(sizeof(unsigned char *) * sy); im->polyInts = 0; im->polyAllocated = 0; im->brush = 0; im->tile = 0; im->style = 0; for (i = 0; i < sy; i++) { im->tpixels[i] = (int *) gdCalloc(sx, sizeof(int)); im->AA_opacity[i] = (unsigned char *) gdCalloc(sx, sizeof(unsigned char)); } im->sx = sx; im->sy = sy; im->transparent = (-1); im->interlace = 0; im->trueColor = 1; /* 2.0.2: alpha blending is now on by default, and saving of alpha is * off by default. This allows font antialiasing to work as expected * on the first try in JPEGs -- quite important -- and also allows * for smaller PNGs when saving of alpha channel is not really * desired, which it usually isn't! */ im->saveAlphaFlag = 0; im->alphaBlendingFlag = 1; im->thick = 1; im->AA = 0; im->AA_polygon = 0; im->cx1 = 0; im->cy1 = 0; im->cx2 = im->sx - 1; im->cy2 = im->sy - 1; im->interpolation = NULL; im->interpolation_id = GD_BILINEAR_FIXED; return im; } void gdImageDestroy (gdImagePtr im) { int i; if (im->pixels) { for (i = 0; i < im->sy; i++) { gdFree(im->pixels[i]); } gdFree(im->pixels); } if (im->tpixels) { for (i = 0; i < im->sy; i++) { gdFree(im->tpixels[i]); } gdFree(im->tpixels); } if (im->AA_opacity) { for (i = 0; i < im->sy; i++) { gdFree(im->AA_opacity[i]); } gdFree(im->AA_opacity); } if (im->polyInts) { gdFree(im->polyInts); } if (im->style) { gdFree(im->style); } gdFree(im); } int gdImageColorClosest (gdImagePtr im, int r, int g, int b) { return gdImageColorClosestAlpha (im, r, g, b, gdAlphaOpaque); } int gdImageColorClosestAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; long rd, gd, bd, ad; int ct = (-1); int first = 1; long mindist = 0; if (im->trueColor) { return gdTrueColorAlpha(r, g, b, a); } for (i = 0; i < im->colorsTotal; i++) { long dist; if (im->open[i]) { continue; } rd = im->red[i] - r; gd = im->green[i] - g; bd = im->blue[i] - b; /* gd 2.02: whoops, was - b (thanks to David Marwood) */ ad = im->alpha[i] - a; dist = rd * rd + gd * gd + bd * bd + ad * ad; if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } /* This code is taken from http://www.acm.org/jgt/papers/SmithLyons96/hwb_rgb.html, an article * on colour conversion to/from RBG and HWB colour systems. * It has been modified to return the converted value as a * parameter. */ #define RETURN_HWB(h, w, b) {HWB->H = h; HWB->W = w; HWB->B = b; return HWB;} #define RETURN_RGB(r, g, b) {RGB->R = r; RGB->G = g; RGB->B = b; return RGB;} #define HWB_UNDEFINED -1 #define SETUP_RGB(s, r, g, b) {s.R = r/255.0f; s.G = g/255.0f; s.B = b/255.0f;} #ifndef MIN #define MIN(a,b) ((a)<(b)?(a):(b)) #endif #define MIN3(a,b,c) ((a)<(b)?(MIN(a,c)):(MIN(b,c))) #ifndef MAX #define MAX(a,b) ((a)<(b)?(b):(a)) #endif #define MAX3(a,b,c) ((a)<(b)?(MAX(b,c)):(MAX(a,c))) /* * Theoretically, hue 0 (pure red) is identical to hue 6 in these transforms. Pure * red always maps to 6 in this implementation. Therefore UNDEFINED can be * defined as 0 in situations where only unsigned numbers are desired. */ typedef struct { float R, G, B; } RGBType; typedef struct { float H, W, B; } HWBType; static HWBType * RGB_to_HWB (RGBType RGB, HWBType * HWB) { /* * RGB are each on [0, 1]. W and B are returned on [0, 1] and H is * returned on [0, 6]. Exception: H is returned UNDEFINED if W == 1 - B. */ float R = RGB.R, G = RGB.G, B = RGB.B, w, v, b, f; int i; w = MIN3 (R, G, B); v = MAX3 (R, G, B); b = 1 - v; if (v == w) { RETURN_HWB(HWB_UNDEFINED, w, b); } f = (R == w) ? G - B : ((G == w) ? B - R : R - G); i = (R == w) ? 3 : ((G == w) ? 5 : 1); RETURN_HWB(i - f / (v - w), w, b); } static float HWB_Diff (int r1, int g1, int b1, int r2, int g2, int b2) { RGBType RGB1, RGB2; HWBType HWB1, HWB2; float diff; SETUP_RGB(RGB1, r1, g1, b1); SETUP_RGB(RGB2, r2, g2, b2); RGB_to_HWB(RGB1, &HWB1); RGB_to_HWB(RGB2, &HWB2); /* * I made this bit up; it seems to produce OK results, and it is certainly * more visually correct than the current RGB metric. (PJW) */ if ((HWB1.H == HWB_UNDEFINED) || (HWB2.H == HWB_UNDEFINED)) { diff = 0.0f; /* Undefined hues always match... */ } else { diff = fabsf(HWB1.H - HWB2.H); if (diff > 3.0f) { diff = 6.0f - diff; /* Remember, it's a colour circle */ } } diff = diff * diff + (HWB1.W - HWB2.W) * (HWB1.W - HWB2.W) + (HWB1.B - HWB2.B) * (HWB1.B - HWB2.B); return diff; } #if 0 /* * This is not actually used, but is here for completeness, in case someone wants to * use the HWB stuff for anything else... */ static RGBType * HWB_to_RGB (HWBType HWB, RGBType * RGB) { /* * H is given on [0, 6] or UNDEFINED. W and B are given on [0, 1]. * RGB are each returned on [0, 1]. */ float h = HWB.H, w = HWB.W, b = HWB.B, v, n, f; int i; v = 1 - b; if (h == HWB_UNDEFINED) { RETURN_RGB(v, v, v); } i = floor(h); f = h - i; if (i & 1) { f = 1 - f; /* if i is odd */ } n = w + f * (v - w); /* linear interpolation between w and v */ switch (i) { case 6: case 0: RETURN_RGB(v, n, w); case 1: RETURN_RGB(n, v, w); case 2: RETURN_RGB(w, v, n); case 3: RETURN_RGB(w, n, v); case 4: RETURN_RGB(n, w, v); case 5: RETURN_RGB(v, w, n); } return RGB; } #endif int gdImageColorClosestHWB (gdImagePtr im, int r, int g, int b) { int i; /* long rd, gd, bd; */ int ct = (-1); int first = 1; float mindist = 0; if (im->trueColor) { return gdTrueColor(r, g, b); } for (i = 0; i < im->colorsTotal; i++) { float dist; if (im->open[i]) { continue; } dist = HWB_Diff(im->red[i], im->green[i], im->blue[i], r, g, b); if (first || (dist < mindist)) { mindist = dist; ct = i; first = 0; } } return ct; } int gdImageColorExact (gdImagePtr im, int r, int g, int b) { return gdImageColorExactAlpha (im, r, g, b, gdAlphaOpaque); } int gdImageColorExactAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; if (im->trueColor) { return gdTrueColorAlpha(r, g, b, a); } for (i = 0; i < im->colorsTotal; i++) { if (im->open[i]) { continue; } if ((im->red[i] == r) && (im->green[i] == g) && (im->blue[i] == b) && (im->alpha[i] == a)) { return i; } } return -1; } int gdImageColorAllocate (gdImagePtr im, int r, int g, int b) { return gdImageColorAllocateAlpha (im, r, g, b, gdAlphaOpaque); } int gdImageColorAllocateAlpha (gdImagePtr im, int r, int g, int b, int a) { int i; int ct = (-1); if (im->trueColor) { return gdTrueColorAlpha(r, g, b, a); } for (i = 0; i < im->colorsTotal; i++) { if (im->open[i]) { ct = i; break; } } if (ct == (-1)) { ct = im->colorsTotal; if (ct == gdMaxColors) { return -1; } im->colorsTotal++; } im->red[ct] = r; im->green[ct] = g; im->blue[ct] = b; im->alpha[ct] = a; im->open[ct] = 0; return ct; } /* * gdImageColorResolve is an alternative for the code fragment: * * if ((color=gdImageColorExact(im,R,G,B)) < 0) * if ((color=gdImageColorAllocate(im,R,G,B)) < 0) * color=gdImageColorClosest(im,R,G,B); * * in a single function. Its advantage is that it is guaranteed to * return a color index in one search over the color table. */ int gdImageColorResolve (gdImagePtr im, int r, int g, int b) { return gdImageColorResolveAlpha(im, r, g, b, gdAlphaOpaque); } int gdImageColorResolveAlpha (gdImagePtr im, int r, int g, int b, int a) { int c; int ct = -1; int op = -1; long rd, gd, bd, ad, dist; long mindist = 4 * 255 * 255; /* init to max poss dist */ if (im->trueColor) { return gdTrueColorAlpha (r, g, b, a); } for (c = 0; c < im->colorsTotal; c++) { if (im->open[c]) { op = c; /* Save open slot */ continue; /* Color not in use */ } if (c == im->transparent) { /* don't ever resolve to the color that has * been designated as the transparent color */ continue; } rd = (long) (im->red[c] - r); gd = (long) (im->green[c] - g); bd = (long) (im->blue[c] - b); ad = (long) (im->alpha[c] - a); dist = rd * rd + gd * gd + bd * bd + ad * ad; if (dist < mindist) { if (dist == 0) { return c; /* Return exact match color */ } mindist = dist; ct = c; } } /* no exact match. We now know closest, but first try to allocate exact */ if (op == -1) { op = im->colorsTotal; if (op == gdMaxColors) { /* No room for more colors */ return ct; /* Return closest available color */ } im->colorsTotal++; } im->red[op] = r; im->green[op] = g; im->blue[op] = b; im->alpha[op] = a; im->open[op] = 0; return op; /* Return newly allocated color */ } void gdImageColorDeallocate (gdImagePtr im, int color) { if (im->trueColor) { return; } /* Mark it open. */ im->open[color] = 1; } void gdImageColorTransparent (gdImagePtr im, int color) { if (!im->trueColor) { if (im->transparent != -1) { im->alpha[im->transparent] = gdAlphaOpaque; } if (color > -1 && color < im->colorsTotal && color < gdMaxColors) { im->alpha[color] = gdAlphaTransparent; } else { return; } } im->transparent = color; } void gdImagePaletteCopy (gdImagePtr to, gdImagePtr from) { int i; int x, y, p; int xlate[256]; if (to->trueColor || from->trueColor) { return; } for (i = 0; i < 256; i++) { xlate[i] = -1; } for (y = 0; y < to->sy; y++) { for (x = 0; x < to->sx; x++) { p = gdImageGetPixel(to, x, y); if (xlate[p] == -1) { /* This ought to use HWB, but we don't have an alpha-aware version of that yet. */ xlate[p] = gdImageColorClosestAlpha (from, to->red[p], to->green[p], to->blue[p], to->alpha[p]); } gdImageSetPixel(to, x, y, xlate[p]); } } for (i = 0; i < from->colorsTotal; i++) { to->red[i] = from->red[i]; to->blue[i] = from->blue[i]; to->green[i] = from->green[i]; to->alpha[i] = from->alpha[i]; to->open[i] = 0; } for (i = from->colorsTotal; i < to->colorsTotal; i++) { to->open[i] = 1; } to->colorsTotal = from->colorsTotal; } /* 2.0.10: before the drawing routines, some code to clip points that are * outside the drawing window. Nick Atty (nick@canalplan.org.uk) * * This is the Sutherland Hodgman Algorithm, as implemented by * Duvanenko, Robbins and Gyurcsik - SH(DRG) for short. See Dr Dobb's * Journal, January 1996, pp107-110 and 116-117 * * Given the end points of a line, and a bounding rectangle (which we * know to be from (0,0) to (SX,SY)), adjust the endpoints to be on * the edges of the rectangle if the line should be drawn at all, * otherwise return a failure code */ /* this does "one-dimensional" clipping: note that the second time it * is called, all the x parameters refer to height and the y to width * - the comments ignore this (if you can understand it when it's * looking at the X parameters, it should become clear what happens on * the second call!) The code is simplified from that in the article, * as we know that gd images always start at (0,0) */ static int clip_1d(int *x0, int *y0, int *x1, int *y1, int maxdim) { double m; /* gradient of line */ if (*x0 < 0) { /* start of line is left of window */ if(*x1 < 0) { /* as is the end, so the line never cuts the window */ return 0; } m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */ /* adjust x0 to be on the left boundary (ie to be zero), and y0 to match */ *y0 -= (int)(m * *x0); *x0 = 0; /* now, perhaps, adjust the far end of the line as well */ if (*x1 > maxdim) { *y1 += (int)(m * (maxdim - *x1)); *x1 = maxdim; } return 1; } if (*x0 > maxdim) { /* start of line is right of window - complement of above */ if (*x1 > maxdim) { /* as is the end, so the line misses the window */ return 0; } m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */ *y0 += (int)(m * (maxdim - *x0)); /* adjust so point is on the right boundary */ *x0 = maxdim; /* now, perhaps, adjust the end of the line */ if (*x1 < 0) { *y1 -= (int)(m * *x1); *x1 = 0; } return 1; } /* the final case - the start of the line is inside the window */ if (*x1 > maxdim) { /* other end is outside to the right */ m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */ *y1 += (int)(m * (maxdim - *x1)); *x1 = maxdim; return 1; } if (*x1 < 0) { /* other end is outside to the left */ m = (*y1 - *y0)/(double)(*x1 - *x0); /* calculate the slope of the line */ *y1 -= (int)(m * *x1); *x1 = 0; return 1; } /* only get here if both points are inside the window */ return 1; } void gdImageSetPixel (gdImagePtr im, int x, int y, int color) { int p; switch (color) { case gdStyled: if (!im->style) { /* Refuse to draw if no style is set. */ return; } else { p = im->style[im->stylePos++]; } if (p != gdTransparent) { gdImageSetPixel(im, x, y, p); } im->stylePos = im->stylePos % im->styleLength; break; case gdStyledBrushed: if (!im->style) { /* Refuse to draw if no style is set. */ return; } p = im->style[im->stylePos++]; if (p != gdTransparent && p != 0) { gdImageSetPixel(im, x, y, gdBrushed); } im->stylePos = im->stylePos % im->styleLength; break; case gdBrushed: gdImageBrushApply(im, x, y); break; case gdTiled: gdImageTileApply(im, x, y); break; case gdAntiAliased: gdImageAntiAliasedApply(im, x, y); break; default: if (gdImageBoundsSafe(im, x, y)) { if (im->trueColor) { switch (im->alphaBlendingFlag) { default: case gdEffectReplace: im->tpixels[y][x] = color; break; case gdEffectAlphaBlend: im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color); break; case gdEffectNormal: im->tpixels[y][x] = gdAlphaBlend(im->tpixels[y][x], color); break; case gdEffectOverlay : im->tpixels[y][x] = gdLayerOverlay(im->tpixels[y][x], color); break; } } else { im->pixels[y][x] = color; } } break; } } int gdImageGetTrueColorPixel (gdImagePtr im, int x, int y) { int p = gdImageGetPixel(im, x, y); if (!im->trueColor) { return gdTrueColorAlpha(im->red[p], im->green[p], im->blue[p], (im->transparent == p) ? gdAlphaTransparent : im->alpha[p]); } else { return p; } } static void gdImageBrushApply (gdImagePtr im, int x, int y) { int lx, ly; int hy, hx; int x1, y1, x2, y2; int srcx, srcy; if (!im->brush) { return; } hy = gdImageSY(im->brush) / 2; y1 = y - hy; y2 = y1 + gdImageSY(im->brush); hx = gdImageSX(im->brush) / 2; x1 = x - hx; x2 = x1 + gdImageSX(im->brush); srcy = 0; if (im->trueColor) { if (im->brush->trueColor) { for (ly = y1; ly < y2; ly++) { srcx = 0; for (lx = x1; (lx < x2); lx++) { int p; p = gdImageGetTrueColorPixel(im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent(im->brush)) { gdImageSetPixel(im, lx, ly, p); } srcx++; } srcy++; } } else { /* 2.0.12: Brush palette, image truecolor (thanks to Thorben Kundinger for pointing out the issue) */ for (ly = y1; ly < y2; ly++) { srcx = 0; for (lx = x1; lx < x2; lx++) { int p, tc; p = gdImageGetPixel(im->brush, srcx, srcy); tc = gdImageGetTrueColorPixel(im->brush, srcx, srcy); /* 2.0.9, Thomas Winzig: apply simple full transparency */ if (p != gdImageGetTransparent(im->brush)) { gdImageSetPixel(im, lx, ly, tc); } srcx++; } srcy++; } } } else { for (ly = y1; ly < y2; ly++) { srcx = 0; for (lx = x1; lx < x2; lx++) { int p; p = gdImageGetPixel(im->brush, srcx, srcy); /* Allow for non-square brushes! */ if (p != gdImageGetTransparent(im->brush)) { /* Truecolor brush. Very slow on a palette destination. */ if (im->brush->trueColor) { gdImageSetPixel(im, lx, ly, gdImageColorResolveAlpha(im, gdTrueColorGetRed(p), gdTrueColorGetGreen(p), gdTrueColorGetBlue(p), gdTrueColorGetAlpha(p))); } else { gdImageSetPixel(im, lx, ly, im->brushColorMap[p]); } } srcx++; } srcy++; } } } static void gdImageTileApply (gdImagePtr im, int x, int y) { gdImagePtr tile = im->tile; int srcx, srcy; int p; if (!tile) { return; } srcx = x % gdImageSX(tile); srcy = y % gdImageSY(tile); if (im->trueColor) { p = gdImageGetPixel(tile, srcx, srcy); if (p != gdImageGetTransparent (tile)) { if (!tile->trueColor) { p = gdTrueColorAlpha(tile->red[p], tile->green[p], tile->blue[p], tile->alpha[p]); } gdImageSetPixel(im, x, y, p); } } else { p = gdImageGetPixel(tile, srcx, srcy); /* Allow for transparency */ if (p != gdImageGetTransparent(tile)) { if (tile->trueColor) { /* Truecolor tile. Very slow on a palette destination. */ gdImageSetPixel(im, x, y, gdImageColorResolveAlpha(im, gdTrueColorGetRed(p), gdTrueColorGetGreen(p), gdTrueColorGetBlue(p), gdTrueColorGetAlpha(p))); } else { gdImageSetPixel(im, x, y, im->tileColorMap[p]); } } } } static int gdImageTileGet (gdImagePtr im, int x, int y) { int srcx, srcy; int tileColor,p; if (!im->tile) { return -1; } srcx = x % gdImageSX(im->tile); srcy = y % gdImageSY(im->tile); p = gdImageGetPixel(im->tile, srcx, srcy); if (im->trueColor) { if (im->tile->trueColor) { tileColor = p; } else { tileColor = gdTrueColorAlpha( gdImageRed(im->tile,p), gdImageGreen(im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } else { if (im->tile->trueColor) { tileColor = gdImageColorResolveAlpha(im, gdTrueColorGetRed (p), gdTrueColorGetGreen (p), gdTrueColorGetBlue (p), gdTrueColorGetAlpha (p)); } else { tileColor = p; tileColor = gdImageColorResolveAlpha(im, gdImageRed (im->tile,p), gdImageGreen (im->tile,p), gdImageBlue (im->tile,p), gdImageAlpha (im->tile,p)); } } return tileColor; } static void gdImageAntiAliasedApply (gdImagePtr im, int px, int py) { float p_dist, p_alpha; unsigned char opacity; /* * Find the perpendicular distance from point C (px, py) to the line * segment AB that is being drawn. (Adapted from an algorithm from the * comp.graphics.algorithms FAQ.) */ int LAC_2, LBC_2; int Ax_Cx = im->AAL_x1 - px; int Ay_Cy = im->AAL_y1 - py; int Bx_Cx = im->AAL_x2 - px; int By_Cy = im->AAL_y2 - py; /* 2.0.13: bounds check! AA_opacity is just as capable of * overflowing as the main pixel array. Arne Jorgensen. * 2.0.14: typo fixed. 2.0.15: moved down below declarations * to satisfy non-C++ compilers. */ if (!gdImageBoundsSafe(im, px, py)) { return; } /* Get the squares of the lengths of the segemnts AC and BC. */ LAC_2 = (Ax_Cx * Ax_Cx) + (Ay_Cy * Ay_Cy); LBC_2 = (Bx_Cx * Bx_Cx) + (By_Cy * By_Cy); if (((im->AAL_LAB_2 + LAC_2) >= LBC_2) && ((im->AAL_LAB_2 + LBC_2) >= LAC_2)) { /* The two angles are acute. The point lies inside the portion of the * plane spanned by the line segment. */ p_dist = fabs ((float) ((Ay_Cy * im->AAL_Bx_Ax) - (Ax_Cx * im->AAL_By_Ay)) / im->AAL_LAB); } else { /* The point is past an end of the line segment. It's length from the * segment is the shorter of the lengths from the endpoints, but call * the distance -1, so as not to compute the alpha nor draw the pixel. */ p_dist = -1; } if ((p_dist >= 0) && (p_dist <= (float) (im->thick))) { p_alpha = pow (1.0 - (p_dist / 1.5), 2); if (p_alpha > 0) { if (p_alpha >= 1) { opacity = 255; } else { opacity = (unsigned char) (p_alpha * 255.0); } if (!im->AA_polygon || (im->AA_opacity[py][px] < opacity)) { im->AA_opacity[py][px] = opacity; } } } } int gdImageGetPixel (gdImagePtr im, int x, int y) { if (gdImageBoundsSafe(im, x, y)) { if (im->trueColor) { return im->tpixels[y][x]; } else { return im->pixels[y][x]; } } else { return 0; } } void gdImageAABlend (gdImagePtr im) { float p_alpha, old_alpha; int color = im->AA_color, color_red, color_green, color_blue; int old_color, old_red, old_green, old_blue; int p_color, p_red, p_green, p_blue; int px, py; color_red = gdImageRed(im, color); color_green = gdImageGreen(im, color); color_blue = gdImageBlue(im, color); /* Impose the anti-aliased drawing on the image. */ for (py = 0; py < im->sy; py++) { for (px = 0; px < im->sx; px++) { if (im->AA_opacity[py][px] != 0) { old_color = gdImageGetPixel(im, px, py); if ((old_color != color) && ((old_color != im->AA_dont_blend) || (im->AA_opacity[py][px] == 255))) { /* Only blend with different colors that aren't the dont_blend color. */ p_alpha = (float) (im->AA_opacity[py][px]) / 255.0; old_alpha = 1.0 - p_alpha; if (p_alpha >= 1.0) { p_color = color; } else { old_red = gdImageRed(im, old_color); old_green = gdImageGreen(im, old_color); old_blue = gdImageBlue(im, old_color); p_red = (int) (((float) color_red * p_alpha) + ((float) old_red * old_alpha)); p_green = (int) (((float) color_green * p_alpha) + ((float) old_green * old_alpha)); p_blue = (int) (((float) color_blue * p_alpha) + ((float) old_blue * old_alpha)); p_color = gdImageColorResolve(im, p_red, p_green, p_blue); } gdImageSetPixel(im, px, py, p_color); } } } /* Clear the AA_opacity array behind us. */ memset(im->AA_opacity[py], 0, im->sx); } } static void gdImageHLine(gdImagePtr im, int y, int x1, int x2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; gdImageFilledRectangle(im, x1, y - thickhalf, x2, y + im->thick - thickhalf - 1, col); } else { if (x2 < x1) { int t = x2; x2 = x1; x1 = t; } for (;x1 <= x2; x1++) { gdImageSetPixel(im, x1, y, col); } } return; } static void gdImageVLine(gdImagePtr im, int x, int y1, int y2, int col) { if (im->thick > 1) { int thickhalf = im->thick >> 1; gdImageFilledRectangle(im, x - thickhalf, y1, x + im->thick - thickhalf - 1, y2, col); } else { if (y2 < y1) { int t = y1; y1 = y2; y2 = t; } for (;y1 <= y2; y1++) { gdImageSetPixel(im, x, y1, col); } } return; } /* Bresenham as presented in Foley & Van Dam */ void gdImageLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int wid; int w, wstart; int thick = im->thick; if (color == gdAntiAliased) { /* gdAntiAliased passed as color: use the much faster, much cheaper and equally attractive gdImageAALine implementation. That clips too, so don't clip twice. */ gdImageAALine(im, x1, y1, x2, y2, im->AA_color); return; } /* 2.0.10: Nick Atty: clip to edges of drawing rectangle, return if no points need to be drawn */ if (!clip_1d(&x1,&y1,&x2,&y2,gdImageSX(im)) || !clip_1d(&y1,&x1,&y2,&x2,gdImageSY(im))) { return; } dx = abs (x2 - x1); dy = abs (y2 - y1); if (dx == 0) { gdImageVLine(im, x1, y1, y2, color); return; } else if (dy == 0) { gdImageHLine(im, y1, x1, x2, color); return; } if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* Doug Claar: watch out for NaN in atan2 (2.0.5) */ if ((dx == 0) && (dy == 0)) { wid = 1; } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double ac = cos (atan2 (dy, dx)); if (ac != 0) { wid = thick / ac; } else { wid = 1; } if (wid == 0) { wid = 1; } } d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } /* Set up line thickness */ wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel(im, x, w, color); } if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, x, w, color); } } } } else { /* More-or-less vertical. use wid for horizontal stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } if (wid == 0) { wid = 1; } d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } /* Set up line thickness */ wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel (im, w, y, color); } } } } } /* * Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org) * */ #define BLEND_COLOR(a, nc, c, cc) \ nc = (cc) + (((((c) - (cc)) * (a)) + ((((c) - (cc)) * (a)) >> 8) + 0x80) >> 8); inline static void gdImageSetAAPixelColor(gdImagePtr im, int x, int y, int color, int t) { int dr,dg,db,p,r,g,b; dr = gdTrueColorGetRed(color); dg = gdTrueColorGetGreen(color); db = gdTrueColorGetBlue(color); p = gdImageGetPixel(im,x,y); r = gdTrueColorGetRed(p); g = gdTrueColorGetGreen(p); b = gdTrueColorGetBlue(p); BLEND_COLOR(t, dr, r, dr); BLEND_COLOR(t, dg, g, dg); BLEND_COLOR(t, db, b, db); im->tpixels[y][x]=gdTrueColorAlpha(dr, dg, db, gdAlphaOpaque); } /* * Added on 2003/12 by Pierre-Alain Joye (pajoye@pearfr.org) **/ void gdImageAALine (gdImagePtr im, int x1, int y1, int x2, int y2, int col) { /* keep them as 32bits */ long x, y, inc; long dx, dy,tmp; if (y1 < 0 && y2 < 0) { return; } if (y1 < 0) { x1 += (y1 * (x1 - x2)) / (y2 - y1); y1 = 0; } if (y2 < 0) { x2 += (y2 * (x1 - x2)) / (y2 - y1); y2 = 0; } /* bottom edge */ if (y1 >= im->sy && y2 >= im->sy) { return; } if (y1 >= im->sy) { x1 -= ((im->sy - y1) * (x1 - x2)) / (y2 - y1); y1 = im->sy - 1; } if (y2 >= im->sy) { x2 -= ((im->sy - y2) * (x1 - x2)) / (y2 - y1); y2 = im->sy - 1; } /* left edge */ if (x1 < 0 && x2 < 0) { return; } if (x1 < 0) { y1 += (x1 * (y1 - y2)) / (x2 - x1); x1 = 0; } if (x2 < 0) { y2 += (x2 * (y1 - y2)) / (x2 - x1); x2 = 0; } /* right edge */ if (x1 >= im->sx && x2 >= im->sx) { return; } if (x1 >= im->sx) { y1 -= ((im->sx - x1) * (y1 - y2)) / (x2 - x1); x1 = im->sx - 1; } if (x2 >= im->sx) { y2 -= ((im->sx - x2) * (y1 - y2)) / (x2 - x1); x2 = im->sx - 1; } dx = x2 - x1; dy = y2 - y1; if (dx == 0 && dy == 0) { return; } if (abs(dx) > abs(dy)) { if (dx < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } x = x1 << 16; y = y1 << 16; inc = (dy * 65536) / dx; while ((x >> 16) <= x2) { gdImageSetAAPixelColor(im, x >> 16, y >> 16, col, (y >> 8) & 0xFF); if ((y >> 16) + 1 < im->sy) { gdImageSetAAPixelColor(im, x >> 16, (y >> 16) + 1,col, (~y >> 8) & 0xFF); } x += (1 << 16); y += inc; } } else { if (dy < 0) { tmp = x1; x1 = x2; x2 = tmp; tmp = y1; y1 = y2; y2 = tmp; dx = x2 - x1; dy = y2 - y1; } x = x1 << 16; y = y1 << 16; inc = (dx * 65536) / dy; while ((y>>16) <= y2) { gdImageSetAAPixelColor(im, x >> 16, y >> 16, col, (x >> 8) & 0xFF); if ((x >> 16) + 1 < im->sx) { gdImageSetAAPixelColor(im, (x >> 16) + 1, (y >> 16),col, (~x >> 8) & 0xFF); } x += inc; y += (1<<16); } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert); void gdImageDashedLine (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int dx, dy, incr1, incr2, d, x, y, xend, yend, xdirflag, ydirflag; int dashStep = 0; int on = 1; int wid; int vert; int thick = im->thick; dx = abs(x2 - x1); dy = abs(y2 - y1); if (dy <= dx) { /* More-or-less horizontal. use wid for vertical stroke */ /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin(atan2(dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } wid = (int)(thick * sin(atan2(dy, dx))); vert = 1; d = 2 * dy - dx; incr1 = 2 * dy; incr2 = 2 * (dy - dx); if (x1 > x2) { x = x2; y = y2; ydirflag = (-1); xend = x1; } else { x = x1; y = y1; ydirflag = 1; xend = x2; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); if (((y2 - y1) * ydirflag) > 0) { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y++; d += incr2; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); } } else { while (x < xend) { x++; if (d < 0) { d += incr1; } else { y--; d += incr2; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); } } } else { /* 2.0.12: Michael Schwartz: divide rather than multiply; TBB: but watch out for /0! */ double as = sin (atan2 (dy, dx)); if (as != 0) { wid = thick / as; } else { wid = 1; } vert = 0; d = 2 * dx - dy; incr1 = 2 * dx; incr2 = 2 * (dx - dy); if (y1 > y2) { y = y2; x = x2; yend = y1; xdirflag = (-1); } else { y = y1; x = x1; yend = y2; xdirflag = 1; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); if (((x2 - x1) * xdirflag) > 0) { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x++; d += incr2; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); } } else { while (y < yend) { y++; if (d < 0) { d += incr1; } else { x--; d += incr2; } dashedSet(im, x, y, color, &on, &dashStep, wid, vert); } } } } static void dashedSet (gdImagePtr im, int x, int y, int color, int *onP, int *dashStepP, int wid, int vert) { int dashStep = *dashStepP; int on = *onP; int w, wstart; dashStep++; if (dashStep == gdDashSize) { dashStep = 0; on = !on; } if (on) { if (vert) { wstart = y - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel(im, x, w, color); } } else { wstart = x - wid / 2; for (w = wstart; w < wstart + wid; w++) { gdImageSetPixel(im, w, y, color); } } } *dashStepP = dashStep; *onP = on; } void gdImageChar (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py < (y + f->h)); py++) { for (px = x; (px < (x + f->w)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cx++; } cx = 0; cy++; } } void gdImageCharUp (gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy; int px, py; int fline; cx = 0; cy = 0; #ifdef CHARSET_EBCDIC c = ASC (c); #endif /*CHARSET_EBCDIC */ if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; py > (y - f->w); py--) { for (px = x; px < (x + f->h); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } void gdImageString (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageChar(im, f, x, y, s[i], color); x += f->w; } } void gdImageStringUp (gdImagePtr im, gdFontPtr f, int x, int y, unsigned char *s, int color) { int i; int l; l = strlen ((char *) s); for (i = 0; (i < l); i++) { gdImageCharUp(im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s); void gdImageString16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16(s); for (i = 0; (i < l); i++) { gdImageChar(im, f, x, y, s[i], color); x += f->w; } } void gdImageStringUp16 (gdImagePtr im, gdFontPtr f, int x, int y, unsigned short *s, int color) { int i; int l; l = strlen16(s); for (i = 0; i < l; i++) { gdImageCharUp(im, f, x, y, s[i], color); y -= f->w; } } static int strlen16 (unsigned short *s) { int len = 0; while (*s) { s++; len++; } return len; } #ifndef HAVE_LSQRT /* If you don't have a nice square root function for longs, you can use ** this hack */ long lsqrt (long n) { long result = (long) sqrt ((double) n); return result; } #endif /* s and e are integers modulo 360 (degrees), with 0 degrees being the rightmost extreme and degrees changing clockwise. cx and cy are the center in pixels; w and h are the horizontal and vertical diameter in pixels. Nice interface, but slow. See gd_arc_f_buggy.c for a better version that doesn't seem to be bug-free yet. */ void gdImageArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color) { if ((s % 360) == (e % 360)) { gdImageEllipse(im, cx, cy, w, h, color); } else { gdImageFilledArc(im, cx, cy, w, h, s, e, color, gdNoFill); } } void gdImageFilledArc (gdImagePtr im, int cx, int cy, int w, int h, int s, int e, int color, int style) { gdPoint pts[3]; int i; int lx = 0, ly = 0; int fx = 0, fy = 0; if ((s % 360) == (e % 360)) { s = 0; e = 360; } else { if (s > 360) { s = s % 360; } if (e > 360) { e = e % 360; } while (s < 0) { s += 360; } while (e < s) { e += 360; } if (s == e) { s = 0; e = 360; } } for (i = s; i <= e; i++) { int x, y; x = ((long) gdCosT[i % 360] * (long) w / (2 * 1024)) + cx; y = ((long) gdSinT[i % 360] * (long) h / (2 * 1024)) + cy; if (i != s) { if (!(style & gdChord)) { if (style & gdNoFill) { gdImageLine(im, lx, ly, x, y, color); } else { /* This is expensive! */ pts[0].x = lx; pts[0].y = ly; pts[1].x = x; pts[1].y = y; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon(im, pts, 3, color); } } } else { fx = x; fy = y; } lx = x; ly = y; } if (style & gdChord) { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine(im, cx, cy, lx, ly, color); gdImageLine(im, cx, cy, fx, fy, color); } gdImageLine(im, fx, fy, lx, ly, color); } else { pts[0].x = fx; pts[0].y = fy; pts[1].x = lx; pts[1].y = ly; pts[2].x = cx; pts[2].y = cy; gdImageFilledPolygon(im, pts, 3, color); } } else { if (style & gdNoFill) { if (style & gdEdged) { gdImageLine(im, cx, cy, lx, ly, color); gdImageLine(im, cx, cy, fx, fy, color); } } } } void gdImageFillToBorder (gdImagePtr im, int x, int y, int border, int color) { int lastBorder; /* Seek left */ int leftLimit = -1, rightLimit; int i, restoreAlphaBlending = 0; if (border < 0) { /* Refuse to fill to a non-solid border */ return; } restoreAlphaBlending = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (x >= im->sx) { x = im->sx - 1; } else if (x < 0) { x = 0; } if (y >= im->sy) { y = im->sy - 1; } else if (y < 0) { y = 0; } for (i = x; i >= 0; i--) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); leftLimit = i; } if (leftLimit == -1) { im->alphaBlendingFlag = restoreAlphaBlending; return; } /* Seek right */ rightLimit = x; for (i = (x + 1); i < im->sx; i++) { if (gdImageGetPixel(im, i, y) == border) { break; } gdImageSetPixel(im, i, y, color); rightLimit = i; } /* Look at lines above and below and start paints */ /* Above */ if (y > 0) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y - 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y - 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } /* Below */ if (y < ((im->sy) - 1)) { lastBorder = 1; for (i = leftLimit; i <= rightLimit; i++) { int c = gdImageGetPixel(im, i, y + 1); if (lastBorder) { if ((c != border) && (c != color)) { gdImageFillToBorder(im, i, y + 1, border, color); lastBorder = 0; } } else if ((c == border) || (c == color)) { lastBorder = 1; } } } im->alphaBlendingFlag = restoreAlphaBlending; } /* * set the pixel at (x,y) and its 4-connected neighbors * with the same pixel value to the new pixel value nc (new color). * A 4-connected neighbor: pixel above, below, left, or right of a pixel. * ideas from comp.graphics discussions. * For tiled fill, the use of a flag buffer is mandatory. As the tile image can * contain the same color as the color to fill. To do not bloat normal filling * code I added a 2nd private function. */ /* horizontal segment of scan line y */ struct seg {int y, xl, xr, dy;}; /* max depth of stack */ #define FILL_MAX ((int)(im->sy*im->sx)/4) #define FILL_PUSH(Y, XL, XR, DY) \ if (sp<stack+FILL_MAX && Y+(DY)>=0 && Y+(DY)<wy2) \ {sp->y = Y; sp->xl = XL; sp->xr = XR; sp->dy = DY; sp++;} #define FILL_POP(Y, XL, XR, DY) \ {sp--; Y = sp->y+(DY = sp->dy); XL = sp->xl; XR = sp->xr;} static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc); void gdImageFill(gdImagePtr im, int x, int y, int nc) { int l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; int alphablending_bak; /* stack of filled segments */ /* struct seg stack[FILL_MAX],*sp = stack;; */ struct seg *stack = NULL; struct seg *sp; if (!im->trueColor && nc > (im->colorsTotal -1)) { return; } alphablending_bak = im->alphaBlendingFlag; im->alphaBlendingFlag = 0; if (nc==gdTiled){ _gdImageFillTiled(im,x,y,nc); im->alphaBlendingFlag = alphablending_bak; return; } wx2=im->sx;wy2=im->sy; oc = gdImageGetPixel(im, x, y); if (oc==nc || x<0 || x>wx2 || y<0 || y>wy2) { im->alphaBlendingFlag = alphablending_bak; return; } /* Do not use the 4 neighbors implementation with * small images */ if (im->sx < 4) { int ix = x, iy = y, c; do { do { c = gdImageGetPixel(im, ix, iy); if (c != oc) { goto done; } gdImageSetPixel(im, ix, iy, nc); } while(ix++ < (im->sx -1)); ix = x; } while(iy++ < (im->sy -1)); goto done; } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && gdImageGetPixel(im,x, y)==oc; x--) { gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for (; x<=wx2 && gdImageGetPixel(im,x, y)==oc; x++) { gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for (x++; x<=x2 && (gdImageGetPixel(im, x, y)!=oc); x++); l = x; } while (x<=x2); } efree(stack); done: im->alphaBlendingFlag = alphablending_bak; } static void _gdImageFillTiled(gdImagePtr im, int x, int y, int nc) { int i, l, x1, x2, dy; int oc; /* old pixel value */ int wx2,wy2; /* stack of filled segments */ struct seg *stack; struct seg *sp; char **pts; if (!im->tile) { return; } wx2=im->sx;wy2=im->sy; nc = gdImageTileGet(im,x,y); pts = (char **) ecalloc(im->sy + 1, sizeof(char *)); for (i = 0; i < im->sy + 1; i++) { pts[i] = (char *) ecalloc(im->sx + 1, sizeof(char)); } stack = (struct seg *)safe_emalloc(sizeof(struct seg), ((int)(im->sy*im->sx)/4), 1); sp = stack; oc = gdImageGetPixel(im, x, y); /* required! */ FILL_PUSH(y,x,x,1); /* seed segment (popped 1st) */ FILL_PUSH(y+1, x, x, -1); while (sp>stack) { FILL_POP(y, x1, x2, dy); for (x=x1; x>=0 && (!pts[y][x] && gdImageGetPixel(im,x,y)==oc); x--) { nc = gdImageTileGet(im,x,y); pts[y][x] = 1; gdImageSetPixel(im,x, y, nc); } if (x>=x1) { goto skip; } l = x+1; /* leak on left? */ if (l<x1) { FILL_PUSH(y, l, x1-1, -dy); } x = x1+1; do { for(; x<wx2 && (!pts[y][x] && gdImageGetPixel(im,x, y)==oc); x++) { nc = gdImageTileGet(im,x,y); pts[y][x] = 1; gdImageSetPixel(im, x, y, nc); } FILL_PUSH(y, l, x-1, dy); /* leak on right? */ if (x>x2+1) { FILL_PUSH(y, x2+1, x-1, -dy); } skip: for(x++; x<=x2 && (pts[y][x] || gdImageGetPixel(im,x, y)!=oc); x++); l = x; } while (x<=x2); } for(i = 0; i < im->sy + 1; i++) { efree(pts[i]); } efree(pts); efree(stack); } void gdImageRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x1h = x1, x1v = x1, y1h = y1, y1v = y1, x2h = x2, x2v = x2, y2h = y2, y2v = y2; int thick = im->thick; int t; if (x1 == x2 && y1 == y2 && thick == 1) { gdImageSetPixel(im, x1, y1, color); return; } if (y2 < y1) { t=y1; y1 = y2; y2 = t; t = x1; x1 = x2; x2 = t; } x1h = x1; x1v = x1; y1h = y1; y1v = y1; x2h = x2; x2v = x2; y2h = y2; y2v = y2; if (thick > 1) { int cx, cy, x1ul, y1ul, x2lr, y2lr; int half = thick >> 1; x1ul = x1 - half; y1ul = y1 - half; x2lr = x2 + half; y2lr = y2 + half; cy = y1ul + thick; while (cy-- > y1ul) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y2lr - thick; while (cy++ < y2lr) { cx = x1ul - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x1ul - 1; while (cx++ < x1ul + thick) { gdImageSetPixel(im, cx, cy, color); } } cy = y1ul + thick - 1; while (cy++ < y2lr -thick) { cx = x2lr - thick - 1; while (cx++ < x2lr) { gdImageSetPixel(im, cx, cy, color); } } return; } else { y1v = y1h + 1; y2v = y2h - 1; gdImageLine(im, x1h, y1h, x2h, y1h, color); gdImageLine(im, x1h, y2h, x2h, y2h, color); gdImageLine(im, x1v, y1v, x1v, y2v, color); gdImageLine(im, x2v, y1v, x2v, y2v, color); } } void gdImageFilledRectangle (gdImagePtr im, int x1, int y1, int x2, int y2, int color) { int x, y; if (x1 == x2 && y1 == y2) { gdImageSetPixel(im, x1, y1, color); return; } if (x1 > x2) { x = x1; x1 = x2; x2 = x; } if (y1 > y2) { y = y1; y1 = y2; y2 = y; } if (x1 < 0) { x1 = 0; } if (x2 >= gdImageSX(im)) { x2 = gdImageSX(im) - 1; } if (y1 < 0) { y1 = 0; } if (y2 >= gdImageSY(im)) { y2 = gdImageSY(im) - 1; } for (y = y1; (y <= y2); y++) { for (x = x1; (x <= x2); x++) { gdImageSetPixel (im, x, y, color); } } } void gdImageCopy (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h) { int c; int x, y; int tox, toy; int i; int colorMap[gdMaxColors]; if (dst->trueColor) { /* 2.0: much easier when the destination is truecolor. */ /* 2.0.10: needs a transparent-index check that is still valid if * the source is not truecolor. Thanks to Frank Warmerdam. */ if (src->trueColor) { for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetTrueColorPixel (src, srcX + x, srcY + y); gdImageSetPixel (dst, dstX + x, dstY + y, c); } } } else { /* source is palette based */ for (y = 0; (y < h); y++) { for (x = 0; (x < w); x++) { int c = gdImageGetPixel (src, srcX + x, srcY + y); if (c != src->transparent) { gdImageSetPixel(dst, dstX + x, dstY + y, gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c])); } } } } return; } /* Destination is palette based */ if (src->trueColor) { /* But source is truecolor (Ouch!) */ toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Get best match possible. */ nc = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c), gdTrueColorGetGreen(c), gdTrueColorGetBlue(c), gdTrueColorGetAlpha(c)); gdImageSetPixel(dst, tox, toy, nc); tox++; } toy++; } return; } /* Palette based to palette based */ for (i = 0; i < gdMaxColors; i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; int mapTo; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox++; continue; } /* Have we established a mapping for this color? */ if (src->trueColor) { /* 2.05: remap to the palette available in the destination image. This is slow and * works badly, but it beats crashing! Thanks to Padhrig McCarthy. */ mapTo = gdImageColorResolveAlpha (dst, gdTrueColorGetRed (c), gdTrueColorGetGreen (c), gdTrueColorGetBlue (c), gdTrueColorGetAlpha (c)); } else if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Get best match possible. This function never returns error. */ nc = gdImageColorResolveAlpha (dst, src->red[c], src->green[c], src->blue[c], src->alpha[c]); } colorMap[c] = nc; mapTo = colorMap[c]; } else { mapTo = colorMap[c]; } gdImageSetPixel (dst, tox, toy, mapTo); tox++; } toy++; } } /* This function is a substitute for real alpha channel operations, so it doesn't pay attention to the alpha channel. */ void gdImageCopyMerge (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; toy = dstY; for (y = srcY; y < (srcY + h); y++) { tox = dstX; for (x = srcX; x < (srcX + w); x++) { int nc; c = gdImageGetPixel(src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); ncR = (int)(gdImageRed (src, c) * (pct / 100.0) + gdImageRed (dst, dc) * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0) + gdImageGreen (dst, dc) * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0) + gdImageBlue (dst, dc) * ((100 - pct) / 100.0)); /* Find a reasonable color */ nc = gdImageColorResolve (dst, ncR, ncG, ncB); } gdImageSetPixel (dst, tox, toy, nc); tox++; } toy++; } } /* This function is a substitute for real alpha channel operations, so it doesn't pay attention to the alpha channel. */ void gdImageCopyMergeGray (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int w, int h, int pct) { int c, dc; int x, y; int tox, toy; int ncR, ncG, ncB; float g; toy = dstY; for (y = srcY; (y < (srcY + h)); y++) { tox = dstX; for (x = srcX; (x < (srcX + w)); x++) { int nc; c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent(src) == c) { tox++; continue; } /* * If it's the same image, mapping is NOT trivial since we * merge with greyscale target, but if pct is 100, the grey * value is not used, so it becomes trivial. pjw 2.0.12. */ if (dst == src && pct == 100) { nc = c; } else { dc = gdImageGetPixel(dst, tox, toy); g = (0.29900f * gdImageRed(dst, dc)) + (0.58700f * gdImageGreen(dst, dc)) + (0.11400f * gdImageBlue(dst, dc)); ncR = (int)(gdImageRed (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0)); ncG = (int)(gdImageGreen (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0)); ncB = (int)(gdImageBlue (src, c) * (pct / 100.0f) + g * ((100 - pct) / 100.0)); /* First look for an exact match */ nc = gdImageColorExact(dst, ncR, ncG, ncB); if (nc == (-1)) { /* No, so try to allocate it */ nc = gdImageColorAllocate(dst, ncR, ncG, ncB); /* If we're out of colors, go for the closest color */ if (nc == (-1)) { nc = gdImageColorClosest(dst, ncR, ncG, ncB); } } } gdImageSetPixel(dst, tox, toy, nc); tox++; } toy++; } } void gdImageCopyResized (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int c; int x, y; int tox, toy; int ydest; int i; int colorMap[gdMaxColors]; /* Stretch vectors */ int *stx, *sty; if (overflow2(sizeof(int), srcW)) { return; } if (overflow2(sizeof(int), srcH)) { return; } stx = (int *) gdMalloc (sizeof (int) * srcW); sty = (int *) gdMalloc (sizeof (int) * srcH); /* Fixed by Mao Morimoto 2.0.16 */ for (i = 0; (i < srcW); i++) { stx[i] = dstW * (i+1) / srcW - dstW * i / srcW ; } for (i = 0; (i < srcH); i++) { sty[i] = dstH * (i+1) / srcH - dstH * i / srcH ; } for (i = 0; (i < gdMaxColors); i++) { colorMap[i] = (-1); } toy = dstY; for (y = srcY; (y < (srcY + srcH)); y++) { for (ydest = 0; (ydest < sty[y - srcY]); ydest++) { tox = dstX; for (x = srcX; (x < (srcX + srcW)); x++) { int nc = 0; int mapTo; if (!stx[x - srcX]) { continue; } if (dst->trueColor) { /* 2.0.9: Thorben Kundinger: Maybe the source image is not a truecolor image */ if (!src->trueColor) { int tmp = gdImageGetPixel (src, x, y); mapTo = gdImageGetTrueColorPixel (src, x, y); if (gdImageGetTransparent (src) == tmp) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } else { /* TK: old code follows */ mapTo = gdImageGetTrueColorPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == mapTo) { /* 2.0.21, TK: not tox++ */ tox += stx[x - srcX]; continue; } } } else { c = gdImageGetPixel (src, x, y); /* Added 7/24/95: support transparent copies */ if (gdImageGetTransparent (src) == c) { tox += stx[x - srcX]; continue; } if (src->trueColor) { /* Remap to the palette available in the destination image. This is slow and works badly. */ mapTo = gdImageColorResolveAlpha(dst, gdTrueColorGetRed(c), gdTrueColorGetGreen(c), gdTrueColorGetBlue(c), gdTrueColorGetAlpha (c)); } else { /* Have we established a mapping for this color? */ if (colorMap[c] == (-1)) { /* If it's the same image, mapping is trivial */ if (dst == src) { nc = c; } else { /* Find or create the best match */ /* 2.0.5: can't use gdTrueColorGetRed, etc with palette */ nc = gdImageColorResolveAlpha(dst, gdImageRed(src, c), gdImageGreen(src, c), gdImageBlue(src, c), gdImageAlpha(src, c)); } colorMap[c] = nc; } mapTo = colorMap[c]; } } for (i = 0; (i < stx[x - srcX]); i++) { gdImageSetPixel (dst, tox, toy, mapTo); tox++; } } toy++; } } gdFree (stx); gdFree (sty); } /* When gd 1.x was first created, floating point was to be avoided. These days it is often faster than table lookups or integer arithmetic. The routine below is shamelessly, gloriously floating point. TBB */ void gdImageCopyResampled (gdImagePtr dst, gdImagePtr src, int dstX, int dstY, int srcX, int srcY, int dstW, int dstH, int srcW, int srcH) { int x, y; double sy1, sy2, sx1, sx2; if (!dst->trueColor) { gdImageCopyResized (dst, src, dstX, dstY, srcX, srcY, dstW, dstH, srcW, srcH); return; } for (y = dstY; (y < dstY + dstH); y++) { sy1 = ((double) y - (double) dstY) * (double) srcH / (double) dstH; sy2 = ((double) (y + 1) - (double) dstY) * (double) srcH / (double) dstH; for (x = dstX; (x < dstX + dstW); x++) { double sx, sy; double spixels = 0; double red = 0.0, green = 0.0, blue = 0.0, alpha = 0.0; double alpha_factor, alpha_sum = 0.0, contrib_sum = 0.0; sx1 = ((double) x - (double) dstX) * (double) srcW / dstW; sx2 = ((double) (x + 1) - (double) dstX) * (double) srcW / dstW; sy = sy1; do { double yportion; if (floor_cast(sy) == floor_cast(sy1)) { yportion = 1.0f - (sy - floor_cast(sy)); if (yportion > sy2 - sy1) { yportion = sy2 - sy1; } sy = floor_cast(sy); } else if (sy == floorf(sy2)) { yportion = sy2 - floor_cast(sy2); } else { yportion = 1.0f; } sx = sx1; do { double xportion; double pcontribution; int p; if (floorf(sx) == floor_cast(sx1)) { xportion = 1.0f - (sx - floor_cast(sx)); if (xportion > sx2 - sx1) { xportion = sx2 - sx1; } sx = floor_cast(sx); } else if (sx == floorf(sx2)) { xportion = sx2 - floor_cast(sx2); } else { xportion = 1.0f; } pcontribution = xportion * yportion; p = gdImageGetTrueColorPixel(src, (int) sx + srcX, (int) sy + srcY); alpha_factor = ((gdAlphaMax - gdTrueColorGetAlpha(p))) * pcontribution; red += gdTrueColorGetRed (p) * alpha_factor; green += gdTrueColorGetGreen (p) * alpha_factor; blue += gdTrueColorGetBlue (p) * alpha_factor; alpha += gdTrueColorGetAlpha (p) * pcontribution; alpha_sum += alpha_factor; contrib_sum += pcontribution; spixels += xportion * yportion; sx += 1.0f; } while (sx < sx2); sy += 1.0f; } while (sy < sy2); if (spixels != 0.0f) { red /= spixels; green /= spixels; blue /= spixels; alpha /= spixels; alpha += 0.5; } if ( alpha_sum != 0.0f) { if( contrib_sum != 0.0f) { alpha_sum /= contrib_sum; } red /= alpha_sum; green /= alpha_sum; blue /= alpha_sum; } /* Clamping to allow for rounding errors above */ if (red > 255.0f) { red = 255.0f; } if (green > 255.0f) { green = 255.0f; } if (blue > 255.0f) { blue = 255.0f; } if (alpha > gdAlphaMax) { alpha = gdAlphaMax; } gdImageSetPixel(dst, x, y, gdTrueColorAlpha ((int) red, (int) green, (int) blue, (int) alpha)); } } } void gdImagePolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int lx, ly; typedef void (*image_line)(gdImagePtr im, int x1, int y1, int x2, int y2, int color); image_line draw_line; if (n <= 0) { return; } /* Let it be known that we are drawing a polygon so that the opacity * mask doesn't get cleared after each line. */ if (c == gdAntiAliased) { im->AA_polygon = 1; } if ( im->antialias) { draw_line = gdImageAALine; } else { draw_line = gdImageLine; } lx = p->x; ly = p->y; draw_line(im, lx, ly, p[n - 1].x, p[n - 1].y, c); for (i = 1; i < n; i++) { p++; draw_line(im, lx, ly, p->x, p->y, c); lx = p->x; ly = p->y; } if (c == gdAntiAliased) { im->AA_polygon = 0; gdImageAABlend(im); } } int gdCompareInt (const void *a, const void *b); /* THANKS to Kirsten Schulz for the polygon fixes! */ /* The intersection finding technique of this code could be improved * by remembering the previous intertersection, and by using the slope. * That could help to adjust intersections to produce a nice * interior_extrema. */ void gdImageFilledPolygon (gdImagePtr im, gdPointPtr p, int n, int c) { int i; int y; int miny, maxy, pmaxy; int x1, y1; int x2, y2; int ind1, ind2; int ints; int fill_color; if (n <= 0) { return; } if (overflow2(sizeof(int), n)) { return; } if (c == gdAntiAliased) { fill_color = im->AA_color; } else { fill_color = c; } if (!im->polyAllocated) { im->polyInts = (int *) gdMalloc(sizeof(int) * n); im->polyAllocated = n; } if (im->polyAllocated < n) { while (im->polyAllocated < n) { im->polyAllocated *= 2; } if (overflow2(sizeof(int), im->polyAllocated)) { return; } im->polyInts = (int *) gdRealloc(im->polyInts, sizeof(int) * im->polyAllocated); } miny = p[0].y; maxy = p[0].y; for (i = 1; i < n; i++) { if (p[i].y < miny) { miny = p[i].y; } if (p[i].y > maxy) { maxy = p[i].y; } } pmaxy = maxy; /* 2.0.16: Optimization by Ilia Chipitsine -- don't waste time offscreen */ if (miny < 0) { miny = 0; } if (maxy >= gdImageSY(im)) { maxy = gdImageSY(im) - 1; } /* Fix in 1.3: count a vertex only once */ for (y = miny; y <= maxy; y++) { /*1.4 int interLast = 0; */ /* int dirLast = 0; */ /* int interFirst = 1; */ ints = 0; for (i = 0; i < n; i++) { if (!i) { ind1 = n - 1; ind2 = 0; } else { ind1 = i - 1; ind2 = i; } y1 = p[ind1].y; y2 = p[ind2].y; if (y1 < y2) { x1 = p[ind1].x; x2 = p[ind2].x; } else if (y1 > y2) { y2 = p[ind1].y; y1 = p[ind2].y; x2 = p[ind1].x; x1 = p[ind2].x; } else { continue; } /* Do the following math as float intermediately, and round to ensure * that Polygon and FilledPolygon for the same set of points have the * same footprint. */ if (y >= y1 && y < y2) { im->polyInts[ints++] = (float) ((y - y1) * (x2 - x1)) / (float) (y2 - y1) + 0.5 + x1; } else if (y == pmaxy && y == y2) { im->polyInts[ints++] = x2; } } qsort(im->polyInts, ints, sizeof(int), gdCompareInt); for (i = 0; i < ints - 1; i += 2) { gdImageLine(im, im->polyInts[i], y, im->polyInts[i + 1], y, fill_color); } } /* If we are drawing this AA, then redraw the border with AA lines. */ if (c == gdAntiAliased) { gdImagePolygon(im, p, n, c); } } int gdCompareInt (const void *a, const void *b) { return (*(const int *) a) - (*(const int *) b); } void gdImageSetStyle (gdImagePtr im, int *style, int noOfPixels) { if (im->style) { gdFree(im->style); } im->style = (int *) gdMalloc(sizeof(int) * noOfPixels); memcpy(im->style, style, sizeof(int) * noOfPixels); im->styleLength = noOfPixels; im->stylePos = 0; } void gdImageSetThickness (gdImagePtr im, int thickness) { im->thick = thickness; } void gdImageSetBrush (gdImagePtr im, gdImagePtr brush) { int i; im->brush = brush; if (!im->trueColor && !im->brush->trueColor) { for (i = 0; i < gdImageColorsTotal(brush); i++) { int index; index = gdImageColorResolveAlpha(im, gdImageRed(brush, i), gdImageGreen(brush, i), gdImageBlue(brush, i), gdImageAlpha(brush, i)); im->brushColorMap[i] = index; } } } void gdImageSetTile (gdImagePtr im, gdImagePtr tile) { int i; im->tile = tile; if (!im->trueColor && !im->tile->trueColor) { for (i = 0; i < gdImageColorsTotal(tile); i++) { int index; index = gdImageColorResolveAlpha(im, gdImageRed(tile, i), gdImageGreen(tile, i), gdImageBlue(tile, i), gdImageAlpha(tile, i)); im->tileColorMap[i] = index; } } } void gdImageSetAntiAliased (gdImagePtr im, int c) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = -1; } void gdImageSetAntiAliasedDontBlend (gdImagePtr im, int c, int dont_blend) { im->AA = 1; im->AA_color = c; im->AA_dont_blend = dont_blend; } void gdImageInterlace (gdImagePtr im, int interlaceArg) { im->interlace = interlaceArg; } int gdImageCompare (gdImagePtr im1, gdImagePtr im2) { int x, y; int p1, p2; int cmpStatus = 0; int sx, sy; if (im1->interlace != im2->interlace) { cmpStatus |= GD_CMP_INTERLACE; } if (im1->transparent != im2->transparent) { cmpStatus |= GD_CMP_TRANSPARENT; } if (im1->trueColor != im2->trueColor) { cmpStatus |= GD_CMP_TRUECOLOR; } sx = im1->sx; if (im1->sx != im2->sx) { cmpStatus |= GD_CMP_SIZE_X + GD_CMP_IMAGE; if (im2->sx < im1->sx) { sx = im2->sx; } } sy = im1->sy; if (im1->sy != im2->sy) { cmpStatus |= GD_CMP_SIZE_Y + GD_CMP_IMAGE; if (im2->sy < im1->sy) { sy = im2->sy; } } if (im1->colorsTotal != im2->colorsTotal) { cmpStatus |= GD_CMP_NUM_COLORS; } for (y = 0; y < sy; y++) { for (x = 0; x < sx; x++) { p1 = im1->trueColor ? gdImageTrueColorPixel(im1, x, y) : gdImagePalettePixel(im1, x, y); p2 = im2->trueColor ? gdImageTrueColorPixel(im2, x, y) : gdImagePalettePixel(im2, x, y); if (gdImageRed(im1, p1) != gdImageRed(im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageGreen(im1, p1) != gdImageGreen(im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } if (gdImageBlue(im1, p1) != gdImageBlue(im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #if 0 /* Soon we'll add alpha channel to palettes */ if (gdImageAlpha(im1, p1) != gdImageAlpha(im2, p2)) { cmpStatus |= GD_CMP_COLOR + GD_CMP_IMAGE; break; } #endif } if (cmpStatus & GD_CMP_COLOR) { break; } } return cmpStatus; } int gdAlphaBlendOld (int dst, int src) { /* 2.0.12: TBB: alpha in the destination should be a * component of the result. Thanks to Frank Warmerdam for * pointing out the issue. */ return ((((gdTrueColorGetAlpha (src) * gdTrueColorGetAlpha (dst)) / gdAlphaMax) << 24) + ((((gdAlphaTransparent - gdTrueColorGetAlpha (src)) * gdTrueColorGetRed (src) / gdAlphaMax) + (gdTrueColorGetAlpha (src) * gdTrueColorGetRed (dst)) / gdAlphaMax) << 16) + ((((gdAlphaTransparent - gdTrueColorGetAlpha (src)) * gdTrueColorGetGreen (src) / gdAlphaMax) + (gdTrueColorGetAlpha (src) * gdTrueColorGetGreen (dst)) / gdAlphaMax) << 8) + (((gdAlphaTransparent - gdTrueColorGetAlpha (src)) * gdTrueColorGetBlue (src) / gdAlphaMax) + (gdTrueColorGetAlpha (src) * gdTrueColorGetBlue (dst)) / gdAlphaMax)); } int gdAlphaBlend (int dst, int src) { int src_alpha = gdTrueColorGetAlpha(src); int dst_alpha, alpha, red, green, blue; int src_weight, dst_weight, tot_weight; /* -------------------------------------------------------------------- */ /* Simple cases we want to handle fast. */ /* -------------------------------------------------------------------- */ if( src_alpha == gdAlphaOpaque ) return src; dst_alpha = gdTrueColorGetAlpha(dst); if( src_alpha == gdAlphaTransparent ) return dst; if( dst_alpha == gdAlphaTransparent ) return src; /* -------------------------------------------------------------------- */ /* What will the source and destination alphas be? Note that */ /* the destination weighting is substantially reduced as the */ /* overlay becomes quite opaque. */ /* -------------------------------------------------------------------- */ src_weight = gdAlphaTransparent - src_alpha; dst_weight = (gdAlphaTransparent - dst_alpha) * src_alpha / gdAlphaMax; tot_weight = src_weight + dst_weight; /* -------------------------------------------------------------------- */ /* What red, green and blue result values will we use? */ /* -------------------------------------------------------------------- */ alpha = src_alpha * dst_alpha / gdAlphaMax; red = (gdTrueColorGetRed(src) * src_weight + gdTrueColorGetRed(dst) * dst_weight) / tot_weight; green = (gdTrueColorGetGreen(src) * src_weight + gdTrueColorGetGreen(dst) * dst_weight) / tot_weight; blue = (gdTrueColorGetBlue(src) * src_weight + gdTrueColorGetBlue(dst) * dst_weight) / tot_weight; /* -------------------------------------------------------------------- */ /* Return merged result. */ /* -------------------------------------------------------------------- */ return ((alpha << 24) + (red << 16) + (green << 8) + blue); } void gdImageAlphaBlending (gdImagePtr im, int alphaBlendingArg) { im->alphaBlendingFlag = alphaBlendingArg; } void gdImageAntialias (gdImagePtr im, int antialias) { if (im->trueColor){ im->antialias = antialias; } } void gdImageSaveAlpha (gdImagePtr im, int saveAlphaArg) { im->saveAlphaFlag = saveAlphaArg; } static int gdLayerOverlay (int dst, int src) { int a1, a2; a1 = gdAlphaMax - gdTrueColorGetAlpha(dst); a2 = gdAlphaMax - gdTrueColorGetAlpha(src); return ( ((gdAlphaMax - a1*a2/gdAlphaMax) << 24) + (gdAlphaOverlayColor( gdTrueColorGetRed(src), gdTrueColorGetRed(dst), gdRedMax ) << 16) + (gdAlphaOverlayColor( gdTrueColorGetGreen(src), gdTrueColorGetGreen(dst), gdGreenMax ) << 8) + (gdAlphaOverlayColor( gdTrueColorGetBlue(src), gdTrueColorGetBlue(dst), gdBlueMax )) ); } static int gdAlphaOverlayColor (int src, int dst, int max ) { /* this function implements the algorithm * * for dst[rgb] < 0.5, * c[rgb] = 2.src[rgb].dst[rgb] * and for dst[rgb] > 0.5, * c[rgb] = -2.src[rgb].dst[rgb] + 2.dst[rgb] + 2.src[rgb] - 1 * */ dst = dst << 1; if( dst > max ) { /* in the "light" zone */ return dst + (src << 1) - (dst * src / max) - max; } else { /* in the "dark" zone */ return dst * src / max; } } void gdImageSetClip (gdImagePtr im, int x1, int y1, int x2, int y2) { if (x1 < 0) { x1 = 0; } if (x1 >= im->sx) { x1 = im->sx - 1; } if (x2 < 0) { x2 = 0; } if (x2 >= im->sx) { x2 = im->sx - 1; } if (y1 < 0) { y1 = 0; } if (y1 >= im->sy) { y1 = im->sy - 1; } if (y2 < 0) { y2 = 0; } if (y2 >= im->sy) { y2 = im->sy - 1; } im->cx1 = x1; im->cy1 = y1; im->cx2 = x2; im->cy2 = y2; } void gdImageGetClip (gdImagePtr im, int *x1P, int *y1P, int *x2P, int *y2P) { *x1P = im->cx1; *y1P = im->cy1; *x2P = im->cx2; *y2P = im->cy2; } /* convert a palette image to true color */ int gdImagePaletteToTrueColor(gdImagePtr src) { unsigned int y; unsigned int yy; if (src == NULL) { return 0; } if (src->trueColor == 1) { return 1; } else { unsigned int x; const unsigned int sy = gdImageSY(src); const unsigned int sx = gdImageSX(src); src->tpixels = (int **) gdMalloc(sizeof(int *) * sy); if (src->tpixels == NULL) { return 0; } for (y = 0; y < sy; y++) { const unsigned char *src_row = src->pixels[y]; int * dst_row; /* no need to calloc it, we overwrite all pxl anyway */ src->tpixels[y] = (int *) gdMalloc(sx * sizeof(int)); if (src->tpixels[y] == NULL) { goto clean_on_error; } dst_row = src->tpixels[y]; for (x = 0; x < sx; x++) { const unsigned char c = *(src_row + x); if (c == src->transparent) { *(dst_row + x) = gdTrueColorAlpha(0, 0, 0, 127); } else { *(dst_row + x) = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]); } } } } /* free old palette buffer (y is sy) */ for (yy = 0; yy < y; yy++) { gdFree(src->pixels[yy]); } gdFree(src->pixels); src->trueColor = 1; src->pixels = NULL; src->alphaBlendingFlag = 0; src->saveAlphaFlag = 1; if (src->transparent >= 0) { const unsigned char c = src->transparent; src->transparent = gdTrueColorAlpha(src->red[c], src->green[c], src->blue[c], src->alpha[c]); } return 1; clean_on_error: if (y > 0) { for (yy = y; yy >= yy - 1; y--) { gdFree(src->tpixels[y]); } gdFree(src->tpixels); } return 0; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_5167_1
crossvul-cpp_data_bad_5177_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y % % P P R R O O P P E R R T Y Y % % PPPP RRRR O O PPPP EEE RRRR T Y % % P R R O O P E R R T Y % % P R R OOO P EEEEE R R T Y % % % % % % MagickCore Property Methods % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/fx-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/locale-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/signature.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS2_LCMS2_H) #include <lcms2/lcms2.h> #elif defined(MAGICKCORE_HAVE_LCMS2_H) #include "lcms2.h" #elif defined(MAGICKCORE_HAVE_LCMS_LCMS_H) #include <lcms/lcms.h> #else #include "lcms.h" #endif #endif /* Define declarations. */ #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProperties() clones all the image properties to another image. % % The format of the CloneImageProperties method is: % % MagickBooleanType CloneImageProperties(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProperties(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", clone_image->filename); (void) CopyMagickString(image->filename,clone_image->filename,MagickPathExtent); (void) CopyMagickString(image->magick_filename,clone_image->magick_filename, MagickPathExtent); image->compression=clone_image->compression; image->quality=clone_image->quality; image->depth=clone_image->depth; image->alpha_color=clone_image->alpha_color; image->background_color=clone_image->background_color; image->border_color=clone_image->border_color; image->transparent_color=clone_image->transparent_color; image->gamma=clone_image->gamma; image->chromaticity=clone_image->chromaticity; image->rendering_intent=clone_image->rendering_intent; image->black_point_compensation=clone_image->black_point_compensation; image->units=clone_image->units; image->montage=(char *) NULL; image->directory=(char *) NULL; (void) CloneString(&image->geometry,clone_image->geometry); image->offset=clone_image->offset; image->resolution.x=clone_image->resolution.x; image->resolution.y=clone_image->resolution.y; image->page=clone_image->page; image->tile_offset=clone_image->tile_offset; image->extract_info=clone_image->extract_info; image->filter=clone_image->filter; image->fuzz=clone_image->fuzz; image->intensity=clone_image->intensity; image->interlace=clone_image->interlace; image->interpolate=clone_image->interpolate; image->endian=clone_image->endian; image->gravity=clone_image->gravity; image->compose=clone_image->compose; image->orientation=clone_image->orientation; image->scene=clone_image->scene; image->dispose=clone_image->dispose; image->delay=clone_image->delay; image->ticks_per_second=clone_image->ticks_per_second; image->iterations=clone_image->iterations; image->total_colors=clone_image->total_colors; image->taint=clone_image->taint; image->progress_monitor=clone_image->progress_monitor; image->client_data=clone_image->client_data; image->start_loop=clone_image->start_loop; image->error=clone_image->error; image->signature=clone_image->signature; if (clone_image->properties != (void *) NULL) { if (image->properties != (void *) NULL) DestroyImageProperties(image); image->properties=CloneSplayTree((SplayTreeInfo *) clone_image->properties,(void *(*)(void *)) ConstantString, (void *(*)(void *)) ConstantString); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e f i n e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageProperty() associates an assignment string of the form % "key=value" with an artifact or options. It is equivelent to % SetImageProperty() % % The format of the DefineImageProperty method is: % % MagickBooleanType DefineImageProperty(Image *image,const char *property, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DefineImageProperty(Image *image, const char *property,ExceptionInfo *exception) { char key[MagickPathExtent], value[MagickPathExtent]; register char *p; assert(image != (Image *) NULL); assert(property != (const char *) NULL); (void) CopyMagickString(key,property,MagickPathExtent-1); for (p=key; *p != '\0'; p++) if (*p == '=') break; *value='\0'; if (*p == '=') (void) CopyMagickString(value,p+1,MagickPathExtent); *p='\0'; return(SetImageProperty(image,key,value,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProperty() deletes an image property. % % The format of the DeleteImageProperty method is: % % MagickBooleanType DeleteImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport MagickBooleanType DeleteImageProperty(Image *image, const char *property) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return(MagickFalse); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->properties,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProperties() destroys all properties and associated memory % attached to the given image. % % The format of the DestroyDefines method is: % % void DestroyImageProperties(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProperties(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties != (void *) NULL) image->properties=(void *) DestroySplayTree((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatImageProperty() permits formatted property/value pairs to be saved as % an image property. % % The format of the FormatImageProperty method is: % % MagickBooleanType FormatImageProperty(Image *image,const char *property, % const char *format,...) % % A description of each parameter follows. % % o image: The image. % % o property: The attribute property. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport MagickBooleanType FormatImageProperty(Image *image, const char *property,const char *format,...) { char value[MagickPathExtent]; ExceptionInfo *exception; MagickBooleanType status; ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(value,MagickPathExtent,format,operands); (void) n; va_end(operands); exception=AcquireExceptionInfo(); status=SetImageProperty(image,property,value,exception); exception=DestroyExceptionInfo(exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProperty() gets a value associated with an image property. % % This includes, profile prefixes, such as "exif:", "iptc:" and "8bim:" % It does not handle non-prifile prefixes, such as "fx:", "option:", or % "artifact:". % % The returned string is stored as a properity of the same name for faster % lookup later. It should NOT be freed by the caller. % % The format of the GetImageProperty method is: % % const char *GetImageProperty(const Image *image,const char *key, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static char *TracePSClippath(const unsigned char *,size_t), *TraceSVGClippath(const unsigned char *,size_t,const size_t, const size_t); static MagickBooleanType GetIPTCProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, *message; const StringInfo *profile; long count, dataset, record; register ssize_t i; size_t length; profile=GetImageProfile(image,"iptc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=sscanf(key,"IPTC:%ld:%ld",&dataset,&record); if (count != 2) return(MagickFalse); attribute=(char *) NULL; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=(ssize_t) length) { length=1; if ((ssize_t) GetStringInfoDatum(profile)[i] != 0x1c) continue; length=(size_t) (GetStringInfoDatum(profile)[i+3] << 8); length|=GetStringInfoDatum(profile)[i+4]; if (((long) GetStringInfoDatum(profile)[i+1] == dataset) && ((long) GetStringInfoDatum(profile)[i+2] == record)) { message=(char *) NULL; if (~length >= 1) message=(char *) AcquireQuantumMemory(length+1UL,sizeof(*message)); if (message != (char *) NULL) { (void) CopyMagickString(message,(char *) GetStringInfoDatum( profile)+i+5,length+1); (void) ConcatenateString(&attribute,message); (void) ConcatenateString(&attribute,";"); message=DestroyString(message); } } i+=5; } if ((attribute == (char *) NULL) || (*attribute == ';')) { if (attribute != (char *) NULL) attribute=DestroyString(attribute); return(MagickFalse); } attribute[strlen(attribute)-1]='\0'; (void) SetImageProperty((Image *) image,key,(const char *) attribute, exception); attribute=DestroyString(attribute); return(MagickTrue); } static inline int ReadPropertyByte(const unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; size_t value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(size_t) (buffer[0] << 24); value|=buffer[1] << 16; value|=buffer[2] << 8; value|=buffer[3]; quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) (buffer[0] << 8); value|=buffer[1]; quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; ssize_t count, id, sub_number; size_t length; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,"SVG",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,"svg") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); } static inline signed int ReadPropertySignedLong(const EndianType endian, const unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); quantum.unsigned_value=(value & 0xffffffff); return(quantum.signed_value); } static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) ((buffer[3] << 24) | (buffer[2] << 16) | (buffer[1] << 8 ) | (buffer[0])); return((unsigned int) (value & 0xffffffff)); } value=(unsigned int) ((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); return((unsigned int) (value & 0xffffffff)); } static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); quantum.unsigned_value=(value & 0xffff); return(quantum.signed_value); } static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) ((buffer[1] << 8) | buffer[0]); return((unsigned short) (value & 0xffff)); } value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) | ((unsigned char *) buffer)[1]); return((unsigned short) (value & 0xffff)); } static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } static MagickBooleanType GetICCProperty(const Image *image,const char *property, ExceptionInfo *exception) { const StringInfo *profile; magick_unreferenced(property); profile=GetImageProfile(image,"icc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"icm"); if (profile == (StringInfo *) NULL) return(MagickFalse); if (GetStringInfoLength(profile) < 128) return(MagickFalse); /* minimum ICC profile length */ #if defined(MAGICKCORE_LCMS_DELEGATE) { cmsHPROFILE icc_profile; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) const char *name; name=cmsTakeProductName(icc_profile); if (name != (const char *) NULL) (void) SetImageProperty((Image *) image,"icc:name",name,exception); #else char info[MagickPathExtent]; (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:description",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:manufacturer",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en", "US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:model",info,exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:copyright",info,exception); #endif (void) cmsCloseProfile(icc_profile); } } #endif return(MagickTrue); } static MagickBooleanType SkipXMPValue(const char *value) { if (value == (const char*) NULL) return(MagickTrue); while (*value != '\0') { if (isspace((int) ((unsigned char) *value)) == 0) return(MagickFalse); value++; } return(MagickTrue); } static MagickBooleanType GetXMPProperty(const Image *image,const char *property) { char *xmp_profile; const char *content; const StringInfo *profile; ExceptionInfo *exception; MagickBooleanType status; register const char *p; XMLTreeInfo *child, *description, *node, *rdf, *xmp; profile=GetImageProfile(image,"xmp"); if (profile == (StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); xmp_profile=StringInfoToString(profile); if (xmp_profile == (char *) NULL) return(MagickFalse); for (p=xmp_profile; *p != '\0'; p++) if ((*p == '<') && (*(p+1) == 'x')) break; exception=AcquireExceptionInfo(); xmp=NewXMLTree((char *) p,exception); xmp_profile=DestroyString(xmp_profile); exception=DestroyExceptionInfo(exception); if (xmp == (XMLTreeInfo *) NULL) return(MagickFalse); status=MagickFalse; rdf=GetXMLTreeChild(xmp,"rdf:RDF"); if (rdf != (XMLTreeInfo *) NULL) { if (image->properties == (void *) NULL) ((Image *) image)->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); description=GetXMLTreeChild(rdf,"rdf:Description"); while (description != (XMLTreeInfo *) NULL) { node=GetXMLTreeChild(description,(const char *) NULL); while (node != (XMLTreeInfo *) NULL) { child=GetXMLTreeChild(node,(const char *) NULL); content=GetXMLTreeContent(node); if ((child == (XMLTreeInfo *) NULL) && (SkipXMPValue(content) == MagickFalse)) (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(GetXMLTreeTag(node)),ConstantString(content)); while (child != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(child); if (SkipXMPValue(content) == MagickFalse) (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(GetXMLTreeTag(child)),ConstantString(content)); child=GetXMLTreeSibling(child); } node=GetXMLTreeSibling(node); } description=GetNextXMLTreeTag(description); } } xmp=DestroyXMLTree(xmp); return(status); } static char *TracePSClippath(const unsigned char *blob,size_t length) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i, x; ssize_t knot_count, selector, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent,"/ClipImage\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"{\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /c {curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /l {lineto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /m {moveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /v {currentpoint 6 2 roll curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /y {2 copy curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /z {closepath} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," newpath\n"); (void) ConcatenateString(&path,message); /* The clipping path format is defined in "Adobe Photoshop File Formats Specification" version 6.0 downloadable from adobe.com. */ (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length > 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { size_t xx, yy; yy=(size_t) ReadPropertyMSBLong(&blob,&length); xx=(size_t) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x/4096/4096; point[i].y=1.0-(double) y/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent," %g %g m\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l\n",point[1].x,point[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v\n",point[0].x,point[0].y, point[1].x,point[1].y); else if ((point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y\n",last[2].x,last[2].y, point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l z\n",first[1].x,first[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v z\n",first[0].x,first[0].y, first[1].x,first[1].y); else if ((first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y z\n",last[2].x,last[2].y, first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Returns an empty PS path if the path has no knots. */ (void) FormatLocaleString(message,MagickPathExtent," eoclip\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"} bind def"); (void) ConcatenateString(&path,message); message=DestroyString(message); return(path); } static char *TraceSVGClippath(const unsigned char *blob,size_t length, const size_t columns,const size_t rows) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i; ssize_t knot_count, selector, x, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent, ("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" "<svg xmlns=\"http://www.w3.org/2000/svg\"" " width=\"%.20g\" height=\"%.20g\">\n" "<g>\n" "<path fill-rule=\"evenodd\" style=\"fill:#00000000;stroke:#00000000;" "stroke-width:0;stroke-antialiasing:false\" d=\"\n"), (double) columns,(double) rows); (void) ConcatenateString(&path,message); (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length != 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot. */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { unsigned int xx, yy; yy=(unsigned int) ReadPropertyMSBLong(&blob,&length); xx=(unsigned int) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x*columns/4096/4096; point[i].y=(double) y*rows/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g\n",point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g Z\n",first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g Z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Return an empty SVG image if the path does not have knots. */ (void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n"); message=DestroyString(message); return(path); } MagickExport const char *GetImageProperty(const Image *image, const char *property,ExceptionInfo *exception) { register const char *p; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); p=(const char *) NULL; if (image->properties != (void *) NULL) { if (property == (const char *) NULL) { ResetSplayTreeIterator((SplayTreeInfo *) image->properties); p=(const char *) GetNextValueInSplayTree((SplayTreeInfo *) image->properties); return(p); } p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); if (p != (const char *) NULL) return(p); } if ((property == (const char *) NULL) || (strchr(property,':') == (char *) NULL)) return(p); switch (*property) { case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) Get8BIMProperty(image,property,exception); break; } break; } case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) GetEXIFProperty(image,property,exception); break; } break; } case 'I': case 'i': { if ((LocaleNCompare("icc:",property,4) == 0) || (LocaleNCompare("icm:",property,4) == 0)) { (void) GetICCProperty(image,property,exception); break; } if (LocaleNCompare("iptc:",property,5) == 0) { (void) GetIPTCProperty(image,property,exception); break; } break; } case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) GetXMPProperty(image,property); break; } break; } default: break; } if (image->properties != (void *) NULL) { p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); return(p); } return((const char *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t M a g i c k P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickProperty() gets attributes or calculated values that is associated % with a fixed known property name, or single letter property. It may be % called if no image is defined (IMv7), in which case only global image_info % values are available: % % \n newline % \r carriage return % < less-than character. % > greater-than character. % & ampersand character. % %% a percent sign % %b file size of image read in % %c comment meta-data property % %d directory component of path % %e filename extension or suffix % %f filename (including suffix) % %g layer canvas page geometry (equivalent to "%Wx%H%X%Y") % %h current image height in pixels % %i image filename (note: becomes output filename for "info:") % %k CALCULATED: number of unique colors % %l label meta-data property % %m image file format (file magic) % %n number of images in current image sequence % %o output filename (used for delegates) % %p index of image in current image list % %q quantum depth (compile-time constant) % %r image class and colorspace % %s scene number (from input unless re-assigned) % %t filename without directory or extension (suffix) % %u unique temporary filename (used for delegates) % %w current width in pixels % %x x resolution (density) % %y y resolution (density) % %z image depth (as read in unless modified, image save depth) % %A image transparency channel enabled (true/false) % %C image compression type % %D image GIF dispose method % %G original image size (%wx%h; before any resizes) % %H page (canvas) height % %M Magick filename (original file exactly as given, including read mods) % %O page (canvas) offset ( = %X%Y ) % %P page (canvas) size ( = %Wx%H ) % %Q image compression quality ( 0 = default ) % %S ?? scenes ?? % %T image time delay (in centi-seconds) % %U image resolution units % %W page (canvas) width % %X page (canvas) x offset (including sign) % %Y page (canvas) y offset (including sign) % %Z unique filename (used for delegates) % %@ CALCULATED: trim bounding box (without actually trimming) % %# CALCULATED: 'signature' hash of image values % % This routine only handles specifically known properties. It does not % handle special prefixed properties, profiles, or expressions. Nor does % it return any free-form property strings. % % The returned string is stored in a structure somewhere, and should not be % directly freed. If the string was generated (common) the string will be % stored as as either as artifact or option 'get-property'. These may be % deleted (cleaned up) when no longer required, but neither artifact or % option is guranteed to exist. % % The format of the GetMagickProperty method is: % % const char *GetMagickProperty(ImageInfo *image_info,Image *image, % const char *property,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info (optional) % % o image: the image (optional) % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static const char *GetMagickPropertyLetter(ImageInfo *image_info, Image *image,const char letter,ExceptionInfo *exception) { #define WarnNoImageReturn(format,arg) \ if (image == (Image *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageForProperty",format,arg); \ return((const char *) NULL); \ } #define WarnNoImageInfoReturn(format,arg) \ if (image_info == (ImageInfo *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageInfoForProperty",format,arg); \ return((const char *) NULL); \ } char value[MagickPathExtent]; /* formated string to store as a returned artifact */ const char *string; /* return a string already stored somewher */ if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formatted string */ string=(char *) NULL; /* constant string reference */ /* Get properities that are directly defined by images. */ switch (letter) { case 'b': /* image size read in - in bytes */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatMagickSize(image->extent,MagickFalse,"B",MagickPathExtent, value); if (image->extent == 0) (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } case 'c': /* image comment property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"comment",exception); if ( string == (const char *) NULL ) string=""; break; } case 'd': /* Directory component of filename */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } case 'e': /* Filename extension (suffix) of image file */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } case 'f': /* Filename without directory component */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,TailPath,value); if (*value == '\0') string=""; break; } case 'g': /* Image geometry, canvas and offset %Wx%H+%X+%Y */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); break; } case 'h': /* Image height (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->rows != 0 ? image->rows : image->magick_rows)); break; } case 'i': /* Filename last used for an image (read or write) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->filename; break; } case 'k': /* Number of unique colors */ { /* FUTURE: ensure this does not generate the formatted comment! */ WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetNumberColors(image,(FILE *) NULL,exception)); break; } case 'l': /* Image label property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"label",exception); if ( string == (const char *) NULL) string=""; break; } case 'm': /* Image format (file magick) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick; break; } case 'n': /* Number of images in the list. */ { if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); else string="0"; /* no images or scenes */ break; } case 'o': /* Output Filename - for delegate use only */ WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->filename; break; case 'p': /* Image index in current image list */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageIndexInList(image)); break; } case 'q': /* Quantum depth of image in memory */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) MAGICKCORE_QUANTUM_DEPTH); break; } case 'r': /* Image storage class, colorspace, and alpha enabled. */ { ColorspaceType colorspace; WarnNoImageReturn("\"%%%c\"",letter); colorspace=image->colorspace; if (SetImageGray(image,exception) != MagickFalse) colorspace=GRAYColorspace; /* FUTURE: this is IMv6 not IMv7 */ (void) FormatLocaleString(value,MagickPathExtent,"%s %s %s", CommandOptionToMnemonic(MagickClassOptions,(ssize_t) image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions, (ssize_t) colorspace),image->alpha_trait != UndefinedPixelTrait ? "Alpha" : ""); break; } case 's': /* Image scene number */ { #if 0 /* this seems non-sensical -- simplifing */ if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else if (image != (Image *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); else string="0"; #else WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); #endif break; } case 't': /* Base filename without directory or extention */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } case 'u': /* Unique filename */ { WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->unique; break; } case 'w': /* Image width (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->columns != 0 ? image->columns : image->magick_columns)); break; } case 'x': /* Image horizontal resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.x) > MagickEpsilon ? image->resolution.x : 72.0); break; } case 'y': /* Image vertical resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.y) > MagickEpsilon ? image->resolution.y : 72.0); break; } case 'z': /* Image depth as read in */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) image->depth); break; } case 'A': /* Image alpha channel */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickPixelTraitOptions,(ssize_t) image->alpha_trait); break; } case 'C': /* Image compression method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickCompressOptions, (ssize_t) image->compression); break; } case 'D': /* Image dispose method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickDisposeOptions, (ssize_t) image->dispose); break; } case 'G': /* Image size as geometry = "%wx%h" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g", (double)image->magick_columns,(double) image->magick_rows); break; } case 'H': /* layer canvas height */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) image->page.height); break; } case 'M': /* Magick filename - filename given incl. coder & read mods */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick_filename; break; } case 'O': /* layer canvas offset with sign = "+%X+%Y" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+ld%+ld",(long) image->page.x,(long) image->page.y); break; } case 'P': /* layer canvas page size = "%Wx%H" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g", (double) image->page.width,(double) image->page.height); break; } case 'Q': /* image compression quality */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->quality == 0 ? 92 : image->quality)); break; } case 'S': /* Number of scenes in image list. */ { WarnNoImageInfoReturn("\"%%%c\"",letter); #if 0 /* What is this number? -- it makes no sense - simplifing */ if (image_info->number_scenes == 0) string="2147483647"; else if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene+image_info->number_scenes); else string="0"; #else (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image_info->number_scenes == 0 ? 2147483647 : image_info->number_scenes)); #endif break; } case 'T': /* image time delay for animations */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->delay); break; } case 'U': /* Image resolution units. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickResolutionOptions, (ssize_t) image->units); break; } case 'W': /* layer canvas width */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->page.width); break; } case 'X': /* layer canvas X offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.x); break; } case 'Y': /* layer canvas Y offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.y); break; } case '%': /* percent escaped */ { string="%"; break; } case '@': /* Trim bounding box, without actually Trimming! */ { RectangleInfo page; WarnNoImageReturn("\"%%%c\"",letter); page=GetImageBoundingBox(image,exception); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) page.width,(double) page.height, (double) page.x,(double)page.y); break; } case '#': { /* Image signature. */ WarnNoImageReturn("\"%%%c\"",letter); (void) SignatureImage(image,exception); string=GetImageProperty(image,"signature",exception); break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* Create a cloned copy of result. */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } MagickExport const char *GetMagickProperty(ImageInfo *image_info, Image *image,const char *property,ExceptionInfo *exception) { char value[MagickPathExtent]; const char *string; assert(property[0] != '\0'); assert(image != (Image *) NULL || image_info != (ImageInfo *) NULL ); if (property[1] == '\0') /* single letter property request */ return(GetMagickPropertyLetter(image_info,image,*property,exception)); if (image != (Image *) NULL && image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if( image_info != (ImageInfo *) NULL && image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formated string */ string=(char *) NULL; /* constant string reference */ switch (*property) { case 'b': { if (LocaleCompare("basename",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } if (LocaleCompare("bit-depth",property) == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageDepth(image, exception)); break; } break; } case 'c': { if (LocaleCompare("channels",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual image channels */ (void) FormatLocaleString(value,MagickPathExtent,"%s", CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace)); LocaleLower(value); if( image->alpha_trait != UndefinedPixelTrait ) (void) ConcatenateMagickString(value,"a",MagickPathExtent); break; } if (LocaleCompare("colorspace",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual colorspace - no 'gray' stuff */ string=CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace); break; } if (LocaleCompare("copyright",property) == 0) { (void) CopyMagickString(value,GetMagickCopyright(),MagickPathExtent); break; } break; } case 'd': { if (LocaleCompare("depth",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->depth); break; } if (LocaleCompare("directory",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } break; } case 'e': { if (LocaleCompare("entropy",property) == 0) { double entropy; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageEntropy(image,&entropy,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),entropy); break; } if (LocaleCompare("extension",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } break; } case 'g': { if (LocaleCompare("gamma",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),image->gamma); break; } break; } case 'h': { if (LocaleCompare("height",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", image->magick_rows != 0 ? (double) image->magick_rows : 256.0); break; } break; } case 'i': { if (LocaleCompare("input",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->filename; break; } break; } case 'k': { if (LocaleCompare("kurtosis",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),kurtosis); break; } break; } case 'm': { if (LocaleCompare("magick",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->magick; break; } if ((LocaleCompare("maxima",property) == 0) || (LocaleCompare("max",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),maximum); break; } if (LocaleCompare("mean",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),mean); break; } if ((LocaleCompare("minima",property) == 0) || (LocaleCompare("min",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),minimum); break; } break; } case 'o': { if (LocaleCompare("opaque",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) IsImageOpaque(image,exception)); break; } if (LocaleCompare("orientation",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickOrientationOptions,(ssize_t) image->orientation); break; } if (LocaleCompare("output",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); (void) CopyMagickString(value,image_info->filename,MagickPathExtent); break; } break; } case 'p': { #if defined(MAGICKCORE_LCMS_DELEGATE) if (LocaleCompare("profile:icc",property) == 0 || LocaleCompare("profile:icm",property) == 0) { #if !defined(LCMS_VERSION) || (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif const StringInfo *profile; cmsHPROFILE icc_profile; profile=GetImageProfile(image,property+8); if (profile == (StringInfo *) NULL) break; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) string=cmsTakeProductName(icc_profile); #else (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription, "en","US",value,MagickPathExtent); #endif (void) cmsCloseProfile(icc_profile); } } #endif if (LocaleCompare("profiles",property) == 0) { const char *name; ResetImageProfileIterator(image); name=GetNextImageProfile(image); if (name != (char *) NULL) { (void) CopyMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); while (name != (char *) NULL) { ConcatenateMagickString(value,",",MagickPathExtent); ConcatenateMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); } } break; } break; } case 'r': { if (LocaleCompare("resolution.x",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); break; } if (LocaleCompare("resolution.y",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); break; } break; } case 's': { if (LocaleCompare("scene",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); } break; } if (LocaleCompare("scenes",property) == 0) { /* FUTURE: equivelent to %n? */ WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); break; } if (LocaleCompare("size",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } if (LocaleCompare("skewness",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),skewness); break; } if (LocaleCompare("standard-deviation",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),standard_deviation); break; } break; } case 't': { if (LocaleCompare("type",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) IdentifyImageType(image,exception)); break; } break; } case 'u': { if (LocaleCompare("unique",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); string=image_info->unique; break; } if (LocaleCompare("units",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t) image->units); break; } if (LocaleCompare("copyright",property) == 0) break; } case 'v': { if (LocaleCompare("version",property) == 0) { string=GetMagickVersion((size_t *) NULL); break; } break; } case 'w': { if (LocaleCompare("width",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->magick_columns != 0 ? image->magick_columns : 256)); break; } break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* create a cloned copy of result, that will get cleaned up, eventually */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } #undef WarnNoImageReturn /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProperty() gets the next free-form string property name. % % The format of the GetNextImageProperty method is: % % char *GetNextImageProperty(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetNextImageProperty(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return((const char *) NULL); return((const char *) GetNextKeyInSplayTree( (SplayTreeInfo *) image->properties)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageProperties() replaces any embedded formatting characters with % the appropriate image property and returns the interpreted text. % % This searches for and replaces % \n \r \% replaced by newline, return, and percent resp. % &lt; &gt; &amp; replaced by '<', '>', '&' resp. % %% replaced by percent % % %x %[x] where 'x' is a single letter properity, case sensitive). % %[type:name] where 'type' a is special and known prefix. % %[name] where 'name' is a specifically known attribute, calculated % value, or a per-image property string name, or a per-image % 'artifact' (as generated from a global option). % It may contain ':' as long as the prefix is not special. % % Single letter % substitutions will only happen if the character before the % percent is NOT a number. But braced substitutions will always be performed. % This prevents the typical usage of percent in a interpreted geometry % argument from being substituted when the percent is a geometry flag. % % If 'glob-expresions' ('*' or '?' characters) is used for 'name' it may be % used as a search pattern to print multiple lines of "name=value\n" pairs of % the associacted set of properties. % % The returned string must be freed using DestoryString() by the caller. % % The format of the InterpretImageProperties method is: % % char *InterpretImageProperties(ImageInfo *image_info, % Image *image,const char *embed_text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. (required) % % o image: the image. (optional) % % o embed_text: the address of a character string containing the embedded % formatting characters. % % o exception: return any errors or warnings in this structure. % */ MagickExport char *InterpretImageProperties(ImageInfo *image_info, Image *image,const char *embed_text,ExceptionInfo *exception) { #define ExtendInterpretText(string_length) \ DisableMSCWarning(4127) \ { \ size_t length=(string_length); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ } \ RestoreMSCWarning #define AppendKeyValue2Text(key,value)\ DisableMSCWarning(4127) \ { \ size_t length=strlen(key)+strlen(value)+2; \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \ } \ RestoreMSCWarning #define AppendString2Text(string) \ DisableMSCWarning(4127) \ { \ size_t length=strlen((string)); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ (void) CopyMagickString(q,(string),extent); \ q+=length; \ } \ RestoreMSCWarning char *interpret_text; register char *q; /* current position in interpret_text */ register const char *p; /* position in embed_text string being expanded */ size_t extent; /* allocated length of interpret_text */ MagickBooleanType number; assert(image == NULL || image->signature == MagickCoreSignature); assert(image_info == NULL || image_info->signature == MagickCoreSignature); if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image"); if (embed_text == (const char *) NULL) return(ConstantString("")); p=embed_text; while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0')) p++; if (*p == '\0') return(ConstantString("")); if ((*p == '@') && (IsPathAccessible(p+1) != MagickFalse)) { /* Handle a '@' replace string from file. */ if (IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,p) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",p); return(ConstantString("")); } interpret_text=FileToString(p+1,~0UL,exception); if (interpret_text != (char *) NULL) return(interpret_text); } /* Translate any embedded format characters. */ interpret_text=AcquireString(embed_text); /* new string with extra space */ extent=MagickPathExtent; /* allocated space in string */ number=MagickFalse; /* is last char a number? */ for (q=interpret_text; *p!='\0'; number=isdigit(*p) ? MagickTrue : MagickFalse,p++) { /* Look for the various escapes, (and handle other specials) */ *q='\0'; ExtendInterpretText(MagickPathExtent); switch (*p) { case '\\': { switch (*(p+1)) { case '\0': continue; case 'r': /* convert to RETURN */ { *q++='\r'; p++; continue; } case 'n': /* convert to NEWLINE */ { *q++='\n'; p++; continue; } case '\n': /* EOL removal UNIX,MacOSX */ { p++; continue; } case '\r': /* EOL removal DOS,Windows */ { p++; if (*p == '\n') /* return-newline EOL */ p++; continue; } default: { p++; *q++=(*p); } } continue; } case '&': { if (LocaleNCompare("&lt;",p,4) == 0) { *q++='<'; p+=3; } else if (LocaleNCompare("&gt;",p,4) == 0) { *q++='>'; p+=3; } else if (LocaleNCompare("&amp;",p,5) == 0) { *q++='&'; p+=4; } else *q++=(*p); continue; } case '%': break; /* continue to next set of handlers */ default: { *q++=(*p); /* any thing else is 'as normal' */ continue; } } p++; /* advance beyond the percent */ /* Doubled Percent - or percent at end of string. */ if ((*p == '\0') || (*p == '\'') || (*p == '"')) p--; if (*p == '%') { *q++='%'; continue; } /* Single letter escapes %c. */ if (*p != '[') { const char *string; if (number != MagickFalse) { /* But only if not preceeded by a number! */ *q++='%'; /* do NOT substitute the percent */ p--; /* back up one */ continue; } string=GetMagickPropertyLetter(image_info,image,*p, exception); if (string != (char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void) DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void) DeleteImageOption(image_info,"get-property"); continue; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%%c\"",*p); continue; } { char pattern[2*MagickPathExtent]; const char *key, *string; register ssize_t len; ssize_t depth; /* Braced Percent Escape %[...]. */ p++; /* advance p to just inside the opening brace */ depth=1; if (*p == ']') { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[]\""); break; } for (len=0; len<(MagickPathExtent-1L) && (*p != '\0');) { if ((*p == '\\') && (*(p+1) != '\0')) { /* Skip escaped braces within braced pattern. */ pattern[len++]=(*p++); pattern[len++]=(*p++); continue; } if (*p == '[') depth++; if (*p == ']') depth--; if (depth <= 0) break; pattern[len++]=(*p++); } pattern[len]='\0'; if (depth != 0) { /* Check for unmatched final ']' for "%[...]". */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnbalancedBraces","\"%%[%s\"",pattern); interpret_text=DestroyString(interpret_text); return((char *) NULL); } /* Special Lookup Prefixes %[prefix:...]. */ if (LocaleNCompare("fx:",pattern,3) == 0) { FxInfo *fx_info; double value; MagickBooleanType status; /* FX - value calculator. */ if (image == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } fx_info=AcquireFxInfo(image,pattern+3,exception); status=FxEvaluateChannelExpression(fx_info,IntensityPixelChannel,0,0, &value,exception); fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,"%.*g", GetMagickPrecision(),(double) value); AppendString2Text(result); } continue; } if (LocaleNCompare("pixel:",pattern,6) == 0) { FxInfo *fx_info; double value; MagickStatusType status; PixelInfo pixel; /* Pixel - color value calculator. */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } GetPixelInfo(image,&pixel); fx_info=AcquireFxInfo(image,pattern+6,exception); status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0, &value,exception); pixel.red=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0, &value,exception); pixel.green=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0, &value,exception); pixel.blue=(double) QuantumRange*value; if (image->colorspace == CMYKColorspace) { status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0, &value,exception); pixel.black=(double) QuantumRange*value; } status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0, &value,exception); pixel.alpha=(double) QuantumRange*value; fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char name[MagickPathExtent]; (void) QueryColorname(image,&pixel,SVGCompliance,name, exception); AppendString2Text(name); } continue; } if (LocaleNCompare("option:",pattern,7) == 0) { /* Option - direct global option lookup (with globbing). */ if (image_info == (ImageInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+7) != MagickFalse) { ResetImageOptionIterator(image_info); while ((key=GetNextImageOption(image_info)) != (const char *) NULL) if (GlobExpression(key,pattern+7,MagickTrue) != MagickFalse) { string=GetImageOption(image_info,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageOption(image_info,pattern+7); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("artifact:",pattern,9) == 0) { /* Artifact - direct image artifact lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImageArtifactIterator(image); while ((key=GetNextImageArtifact(image)) != (const char *) NULL) if (GlobExpression(key,pattern+9,MagickTrue) != MagickFalse) { string=GetImageArtifact(image,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageArtifact(image,pattern+9); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("property:",pattern,9) == 0) { /* Property - direct image property lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } string=GetImageProperty(image,pattern+9,exception); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (image != (Image *) NULL) { /* Properties without special prefix. This handles attributes, properties, and profiles such as %[exif:...]. Note the profile properties may also include a glob expansion pattern. */ string=GetImageProperty(image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void)DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void)DeleteImageOption(image_info,"get-property"); continue; } } if (IsGlob(pattern) != MagickFalse) { /* Handle property 'glob' patterns such as: %[*] %[user:array_??] %[filename:e*]> */ if (image == (Image *) NULL) continue; /* else no image to retrieve proprty - no list */ ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } /* Look for a known property or image attribute such as %[basename] %[denisty] %[delay]. Also handles a braced single letter: %[b] %[G] %[g]. */ string=GetMagickProperty(image_info,image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); continue; } /* Look for a per-image artifact. This includes option lookup (FUTURE: interpreted according to image). */ if (image != (Image *) NULL) { string=GetImageArtifact(image,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } else if (image_info != (ImageInfo *) NULL) { /* No image, so direct 'option' lookup (no delayed percent escapes). */ string=GetImageOption(image_info,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } PropertyLookupFailure: /* Failed to find any match anywhere! */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[%s]\"",pattern); } } *q='\0'; return(interpret_text); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProperty() removes a property from the image and returns its % value. % % In this case the ConstantString() value returned should be freed by the % caller when finished. % % The format of the RemoveImageProperty method is: % % char *RemoveImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport char *RemoveImageProperty(Image *image, const char *property) { char *value; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return((char *) NULL); value=(char *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->properties, property); return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P r o p e r t y I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePropertyIterator() resets the image properties iterator. Use it % in conjunction with GetNextImageProperty() to iterate over all the values % associated with an image property. % % The format of the ResetImagePropertyIterator method is: % % ResetImagePropertyIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImagePropertyIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProperty() saves the given string value either to specific known % attribute or to a freeform property string. % % Attempting to set a property that is normally calculated will produce % an exception. % % The format of the SetImageProperty method is: % % MagickBooleanType SetImageProperty(Image *image,const char *property, % const char *value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o values: the image property values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageProperty(Image *image, const char *property,const char *value,ExceptionInfo *exception) { MagickBooleanType status; MagickStatusType flags; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) image->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */ if (value == (const char *) NULL) return(DeleteImageProperty(image,property)); /* delete if NULL */ status=MagickTrue; if (strlen(property) <= 1) { /* Do not 'set' single letter properties - read only shorthand. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } /* FUTURE: binary chars or quotes in key should produce a error */ /* Set attributes with known names or special prefixes return result is found, or break to set a free form properity */ switch (*property) { #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; } #endif case 'B': case 'b': { if (LocaleCompare("background",property) == 0) { (void) QueryColorCompliance(value,AllCompliance, &image->background_color,exception); /* check for FUTURE: value exception?? */ /* also add user input to splay tree */ } break; /* not an attribute, add as a property */ } case 'C': case 'c': { if (LocaleCompare("channels",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("colorspace",property) == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, value); if (colorspace < 0) return(MagickFalse); /* FUTURE: value exception?? */ return(SetImageColorspace(image,(ColorspaceType) colorspace,exception)); } if (LocaleCompare("compose",property) == 0) { ssize_t compose; compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value); if (compose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compose=(CompositeOperator) compose; return(MagickTrue); } if (LocaleCompare("compress",property) == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions,MagickFalse, value); if (compression < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compression=(CompressionType) compression; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'D': case 'd': { if (LocaleCompare("delay",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->delay=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); return(MagickTrue); } if (LocaleCompare("delay_units",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("density",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; return(MagickTrue); } if (LocaleCompare("depth",property) == 0) { image->depth=StringToUnsignedLong(value); return(MagickTrue); } if (LocaleCompare("dispose",property) == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value); if (dispose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->dispose=(DisposeType) dispose; return(MagickTrue); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'F': case 'f': { if (LocaleNCompare("fx:",property,3) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif case 'G': case 'g': { if (LocaleCompare("gamma",property) == 0) { image->gamma=StringToDouble(value,(char **) NULL); return(MagickTrue); } if (LocaleCompare("gravity",property) == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); if (gravity < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->gravity=(GravityType) gravity; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'H': case 'h': { if (LocaleCompare("height",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'I': case 'i': { if (LocaleCompare("intensity",property) == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (intensity < 0) return(MagickFalse); image->intensity=(PixelIntensityMethod) intensity; return(MagickTrue); } if (LocaleCompare("intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } if (LocaleCompare("interpolate",property) == 0) { ssize_t interpolate; interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, value); if (interpolate < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->interpolate=(PixelInterpolateMethod) interpolate; return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("iptc:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif break; /* not an attribute, add as a property */ } case 'K': case 'k': if (LocaleCompare("kurtosis",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'L': case 'l': { if (LocaleCompare("loop",property) == 0) { image->iterations=StringToUnsignedLong(value); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'M': case 'm': if ( (LocaleCompare("magick",property) == 0) || (LocaleCompare("max",property) == 0) || (LocaleCompare("mean",property) == 0) || (LocaleCompare("min",property) == 0) || (LocaleCompare("min",property) == 0) ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'O': case 'o': if (LocaleCompare("opaque",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'P': case 'p': { if (LocaleCompare("page",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("pixel:",property,6) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif if (LocaleCompare("profile",property) == 0) { ImageInfo *image_info; StringInfo *profile; image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,value,MagickPathExtent); (void) SetImageInfo(image_info,1,exception); profile=FileToStringInfo(image_info->filename,~0UL,exception); if (profile != (StringInfo *) NULL) status=SetImageProfile(image,image_info->magick,profile,exception); image_info=DestroyImageInfo(image_info); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'R': case 'r': { if (LocaleCompare("rendering-intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'S': case 's': if ( (LocaleCompare("size",property) == 0) || (LocaleCompare("skewness",property) == 0) || (LocaleCompare("scenes",property) == 0) || (LocaleCompare("standard-deviation",property) == 0) ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'T': case 't': { if (LocaleCompare("tile-offset",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'U': case 'u': { if (LocaleCompare("units",property) == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value); if (units < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->units=(ResolutionType) units; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'V': case 'v': { if (LocaleCompare("version",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'W': case 'w': { if (LocaleCompare("width",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif } /* Default: not an attribute, add as a property */ status=AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(property),ConstantString(value)); /* FUTURE: error if status is bad? */ return(status); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_5177_1
crossvul-cpp_data_bad_402_1
/* * Description: * History: yang@haipo.me, 2016/03/30, create */ # include <stdlib.h> # include <assert.h> # include "ut_rpc.h" # include "ut_crc32.h" # include "ut_misc.h" int rpc_decode(nw_ses *ses, void *data, size_t max) { if (max < RPC_PKG_HEAD_SIZE) return 0; rpc_pkg *pkg = data; if (le32toh(pkg->magic) != RPC_PKG_MAGIC) return -1; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + le16toh(pkg->ext_size) + le32toh(pkg->body_size); if (max < pkg_size) return 0; uint32_t crc32 = le32toh(pkg->crc32); pkg->crc32 = 0; if (crc32 != generate_crc32c(data, pkg_size)) return -3; pkg->crc32 = crc32; pkg->magic = le32toh(pkg->magic); pkg->command = le32toh(pkg->command); pkg->pkg_type = le16toh(pkg->pkg_type); pkg->result = le32toh(pkg->result); pkg->sequence = le32toh(pkg->sequence); pkg->req_id = le64toh(pkg->req_id); pkg->body_size = le32toh(pkg->body_size); pkg->ext_size = le16toh(pkg->ext_size); return pkg_size; } int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } int rpc_send(nw_ses *ses, rpc_pkg *pkg) { void *data; uint32_t size; int ret = rpc_pack(pkg, &data, &size); if (ret < 0) return ret; return nw_ses_send(ses, data, size); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_402_1
crossvul-cpp_data_bad_1185_0
/* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library * * Read and return a packed RGBA image. */ #include "tiffiop.h" #include <stdio.h> static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int PickContigCase(TIFFRGBAImage*); static int PickSeparateCase(TIFFRGBAImage*); static int BuildMapUaToAa(TIFFRGBAImage* img); static int BuildMapBitdepth16To8(TIFFRGBAImage* img); static const char photoTag[] = "PhotometricInterpretation"; /* * Helper constants used in Orientation tag handling */ #define FLIP_VERTICALLY 0x01 #define FLIP_HORIZONTALLY 0x02 /* * Color conversion constants. We will define display types here. */ static const TIFFDisplay display_sRGB = { { /* XYZ -> luminance matrix */ { 3.2410F, -1.5374F, -0.4986F }, { -0.9692F, 1.8760F, 0.0416F }, { 0.0556F, -0.2040F, 1.0570F } }, 100.0F, 100.0F, 100.0F, /* Light o/p for reference white */ 255, 255, 255, /* Pixel values for ref. white */ 1.0F, 1.0F, 1.0F, /* Residual light o/p for black pixel */ 2.4F, 2.4F, 2.4F, /* Gamma values for the three guns */ }; /* * Check the image to see if TIFFReadRGBAImage can deal with it. * 1/0 is returned according to whether or not the image can * be handled. If 0 is returned, emsg contains the reason * why it is being rejected. */ int TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) { TIFFDirectory* td = &tif->tif_dir; uint16 photometric; int colorchannels; if (!tif->tif_decodestatus) { sprintf(emsg, "Sorry, requested compression method is not configured"); return (0); } switch (td->td_bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", td->td_bitspersample); return (0); } if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP) { sprintf(emsg, "Sorry, can not handle images with IEEE floating-point samples"); return (0); } colorchannels = td->td_samplesperpixel - td->td_extrasamples; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { switch (colorchannels) { case 1: photometric = PHOTOMETRIC_MINISBLACK; break; case 3: photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); return (0); } } switch (photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_samplesperpixel != 1 && td->td_bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, photometric, "Samples/pixel", td->td_samplesperpixel, td->td_bitspersample); return (0); } /* * We should likely validate that any extra samples are either * to be ignored, or are alpha, and if alpha we should try to use * them. But for now we won't bother with this. */ break; case PHOTOMETRIC_YCBCR: /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); return (0); } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); return 0; } if (td->td_samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; } case PHOTOMETRIC_LOGL: if (td->td_compression != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); return (0); } break; case PHOTOMETRIC_LOGLUV: if (td->td_compression != COMPRESSION_SGILOG && td->td_compression != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); return (0); } if (td->td_planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", td->td_planarconfig); return (0); } if ( td->td_samplesperpixel != 3 || colorchannels != 3 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels); return 0; } break; case PHOTOMETRIC_CIELAB: if ( td->td_samplesperpixel != 3 || colorchannels != 3 || td->td_bitspersample != 8 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d and %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels, "Bits/sample", td->td_bitspersample); return 0; } break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, photometric); return (0); } return (1); } void TIFFRGBAImageEnd(TIFFRGBAImage* img) { if (img->Map) { _TIFFfree(img->Map); img->Map = NULL; } if (img->BWmap) { _TIFFfree(img->BWmap); img->BWmap = NULL; } if (img->PALmap) { _TIFFfree(img->PALmap); img->PALmap = NULL; } if (img->ycbcr) { _TIFFfree(img->ycbcr); img->ycbcr = NULL; } if (img->cielab) { _TIFFfree(img->cielab); img->cielab = NULL; } if (img->UaToAa) { _TIFFfree(img->UaToAa); img->UaToAa = NULL; } if (img->Bitdepth16To8) { _TIFFfree(img->Bitdepth16To8); img->Bitdepth16To8 = NULL; } if( img->redcmap ) { _TIFFfree( img->redcmap ); _TIFFfree( img->greencmap ); _TIFFfree( img->bluecmap ); img->redcmap = img->greencmap = img->bluecmap = NULL; } } static int isCCITTCompression(TIFF* tif) { uint16 compress; TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); return (compress == COMPRESSION_CCITTFAX3 || compress == COMPRESSION_CCITTFAX4 || compress == COMPRESSION_CCITTRLE || compress == COMPRESSION_CCITTRLEW); } int TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024]) { uint16* sampleinfo; uint16 extrasamples; uint16 planarconfig; uint16 compress; int colorchannels; uint16 *red_orig, *green_orig, *blue_orig; int n_color; if( !TIFFRGBAImageOK(tif, emsg) ) return 0; /* Initialize to normal values */ img->row_offset = 0; img->col_offset = 0; img->redcmap = NULL; img->greencmap = NULL; img->bluecmap = NULL; img->Map = NULL; img->BWmap = NULL; img->PALmap = NULL; img->ycbcr = NULL; img->cielab = NULL; img->UaToAa = NULL; img->Bitdepth16To8 = NULL; img->req_orientation = ORIENTATION_BOTLEFT; /* It is the default */ img->tif = tif; img->stoponerr = stop; TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample); switch (img->bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", img->bitspersample); goto fail_return; } img->alpha = 0; TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel); TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo); if (extrasamples >= 1) { switch (sampleinfo[0]) { case EXTRASAMPLE_UNSPECIFIED: /* Workaround for some images without */ if (img->samplesperpixel > 3) /* correct info about alpha channel */ img->alpha = EXTRASAMPLE_ASSOCALPHA; break; case EXTRASAMPLE_ASSOCALPHA: /* data is pre-multiplied */ case EXTRASAMPLE_UNASSALPHA: /* data is not pre-multiplied */ img->alpha = sampleinfo[0]; break; } } #ifdef DEFAULT_EXTRASAMPLE_AS_ALPHA if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) img->photometric = PHOTOMETRIC_MINISWHITE; if( extrasamples == 0 && img->samplesperpixel == 4 && img->photometric == PHOTOMETRIC_RGB ) { img->alpha = EXTRASAMPLE_ASSOCALPHA; extrasamples = 1; } #endif colorchannels = img->samplesperpixel - extrasamples; TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress); TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig); if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) { switch (colorchannels) { case 1: if (isCCITTCompression(tif)) img->photometric = PHOTOMETRIC_MINISWHITE; else img->photometric = PHOTOMETRIC_MINISBLACK; break; case 3: img->photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); goto fail_return; } } switch (img->photometric) { case PHOTOMETRIC_PALETTE: if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &red_orig, &green_orig, &blue_orig)) { sprintf(emsg, "Missing required \"Colormap\" tag"); goto fail_return; } /* copy the colormaps so we can modify them */ n_color = (1U << img->bitspersample); img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); if( !img->redcmap || !img->greencmap || !img->bluecmap ) { sprintf(emsg, "Out of memory for colormap copy"); goto fail_return; } _TIFFmemcpy( img->redcmap, red_orig, n_color * 2 ); _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 ); _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 ); /* fall through... */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (planarconfig == PLANARCONFIG_CONTIG && img->samplesperpixel != 1 && img->bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, img->photometric, "Samples/pixel", img->samplesperpixel, img->bitspersample); goto fail_return; } break; case PHOTOMETRIC_YCBCR: /* It would probably be nice to have a reality check here. */ if (planarconfig == PLANARCONFIG_CONTIG) /* can rely on libjpeg to convert to RGB */ /* XXX should restore current state on exit */ switch (compress) { case COMPRESSION_JPEG: /* * TODO: when complete tests verify complete desubsampling * and YCbCr handling, remove use of TIFFTAG_JPEGCOLORMODE in * favor of tif_getimage.c native handling */ TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); img->photometric = PHOTOMETRIC_RGB; break; default: /* do nothing */; break; } /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); goto fail_return; } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); goto fail_return; } if (img->samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", img->samplesperpixel); goto fail_return; } } break; case PHOTOMETRIC_LOGL: if (compress != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); goto fail_return; } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_MINISBLACK; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_LOGLUV: if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); goto fail_return; } if (planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", planarconfig); return (0); } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_RGB; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_CIELAB: break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, img->photometric); goto fail_return; } TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height); TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation); img->isContig = !(planarconfig == PLANARCONFIG_SEPARATE && img->samplesperpixel > 1); if (img->isContig) { if (!PickContigCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } else { if (!PickSeparateCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } return 1; fail_return: TIFFRGBAImageEnd( img ); return 0; } int TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { if (img->get == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"get\" routine setup"); return (0); } if (img->put.any == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"put\" routine setupl; probably can not handle image format"); return (0); } return (*img->get)(img, raster, w, h); } /* * Read the specified image into an ABGR-format rastertaking in account * specified orientation. */ int TIFFReadRGBAImageOriented(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int orientation, int stop) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) { img.req_orientation = (uint16)orientation; /* XXX verify rwidth and rheight against width and height */ ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth, rwidth, img.height); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read the specified image into an ABGR-format raster. Use bottom left * origin for raster by default. */ int TIFFReadRGBAImage(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int stop) { return TIFFReadRGBAImageOriented(tif, rwidth, rheight, raster, ORIENTATION_BOTLEFT, stop); } static int setorientation(TIFFRGBAImage* img) { switch (img->orientation) { case ORIENTATION_TOPLEFT: case ORIENTATION_LEFTTOP: if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_VERTICALLY; else return 0; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else return 0; case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY; else return 0; case ORIENTATION_BOTLEFT: case ORIENTATION_LEFTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY; else return 0; default: /* NOTREACHED */ return 0; } } /* * Get an tile-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; int32 fromskew, toskew; uint32 nrow; int ret = 1, flip; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tmsize_t bufsize; bufsize = TIFFTileSize(tif); if (bufsize == 0) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer"); return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col, row+img->row_offset, 0, 0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } _TIFFfree(buf); if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } return (ret); } /* * Get an tile-organized image that has * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; unsigned char* p0 = NULL; unsigned char* p1 = NULL; unsigned char* p2 = NULL; unsigned char* pa = NULL; tmsize_t tilesize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; uint32 nrow; int ret = 1, flip; uint16 colorchannels; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tilesize = TIFFTileSize(tif); bufsize = _TIFFMultiplySSize(tif, alpha?4:3,tilesize, "gtTileSeparate"); if (bufsize == 0) { return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if( buf == NULL ) { if (_TIFFReadTileAndAllocBuffer( tif, (void**) &buf, bufsize, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*tilesize):NULL); } else { p1 = p0 + tilesize; p2 = p1 + tilesize; pa = (alpha?(p2+tilesize):NULL); } } else if (TIFFReadTile(tif, p0, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p1, col, row+img->row_offset,0,1) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p2, col, row+img->row_offset,0,2) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha && TIFFReadTile(tif,pa,col, row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \ p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ?-(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 row, y, nrow, nrowsub, rowstoread; tmsize_t pos; unsigned char* buf = NULL; uint32 rowsperstrip; uint16 subsamplinghor,subsamplingver; uint32 imagewidth = img->width; tmsize_t scanline; int32 fromskew, toskew; int ret = 1, flip; tmsize_t maxstripsize; TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if( subsamplingver == 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling"); return (0); } maxstripsize = TIFFStripSize(tif); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); nrowsub = nrow; if ((nrowsub%subsamplingver)!=0) nrowsub+=subsamplingver-nrowsub%subsamplingver; if (_TIFFReadEncodedStripAndAllocBuffer(tif, TIFFComputeStrip(tif,row+img->row_offset, 0), (void**)(&buf), maxstripsize, ((row + img->row_offset)%rowsperstrip + nrowsub) * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image with * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; unsigned char *buf = NULL; unsigned char *p0 = NULL, *p1 = NULL, *p2 = NULL, *pa = NULL; uint32 row, y, nrow, rowstoread; tmsize_t pos; tmsize_t scanline; uint32 rowsperstrip, offset_row; uint32 imagewidth = img->width; tmsize_t stripsize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; int ret = 1, flip; uint16 colorchannels; stripsize = TIFFStripSize(tif); bufsize = _TIFFMultiplySSize(tif,alpha?4:3,stripsize, "gtStripSeparate"); if (bufsize == 0) { return (0); } flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); offset_row = row + img->row_offset; if( buf == NULL ) { if (_TIFFReadEncodedStripAndAllocBuffer( tif, TIFFComputeStrip(tif, offset_row, 0), (void**) &buf, bufsize, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*stripsize):NULL); } else { p1 = p0 + stripsize; p2 = p1 + stripsize; pa = (alpha?(p2+stripsize):NULL); } } else if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0), p0, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1), p1, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2), p2, ((row + img->row_offset)%rowsperstrip + nrow) * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha) { if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels), pa, ((row + img->row_offset)%rowsperstrip + nrow) * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * The following routines move decoded data returned * from the TIFF library into rasters filled with packed * ABGR pixels (i.e. suitable for passing to lrecwrite.) * * The routines have been created according to the most * important cases and optimized. PickContigCase and * PickSeparateCase analyze the parameters and select * the appropriate "get" and "put" routine to use. */ #define REPEAT8(op) REPEAT4(op); REPEAT4(op) #define REPEAT4(op) REPEAT2(op); REPEAT2(op) #define REPEAT2(op) op; op #define CASE8(x,op) \ switch (x) { \ case 7: op; /*-fallthrough*/ \ case 6: op; /*-fallthrough*/ \ case 5: op; /*-fallthrough*/ \ case 4: op; /*-fallthrough*/ \ case 3: op; /*-fallthrough*/ \ case 2: op; /*-fallthrough*/ \ case 1: op; \ } #define CASE4(x,op) switch (x) { case 3: op; /*-fallthrough*/ case 2: op; /*-fallthrough*/ case 1: op; } #define NOP #define UNROLL8(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 8; _x -= 8) { \ op1; \ REPEAT8(op2); \ } \ if (_x > 0) { \ op1; \ CASE8(_x,op2); \ } \ } #define UNROLL4(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 4; _x -= 4) { \ op1; \ REPEAT4(op2); \ } \ if (_x > 0) { \ op1; \ CASE4(_x,op2); \ } \ } #define UNROLL2(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 2; _x -= 2) { \ op1; \ REPEAT2(op2); \ } \ if (_x) { \ op1; \ op2; \ } \ } #define SKEW(r,g,b,skew) { r += skew; g += skew; b += skew; } #define SKEW4(r,g,b,a,skew) { r += skew; g += skew; b += skew; a+= skew; } #define A1 (((uint32)0xffL)<<24) #define PACK(r,g,b) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1) #define PACK4(r,g,b,a) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24)) #define W2B(v) (((v)>>8)&0xff) /* TODO: PACKW should have be made redundant in favor of Bitdepth16To8 LUT */ #define PACKW(r,g,b) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1) #define PACKW4(r,g,b,a) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24)) #define DECLAREContigPutFunc(name) \ static void name(\ TIFFRGBAImage* img, \ uint32* cp, \ uint32 x, uint32 y, \ uint32 w, uint32 h, \ int32 fromskew, int32 toskew, \ unsigned char* pp \ ) /* * 8-bit palette => colormap/RGB */ DECLAREContigPutFunc(put8bitcmaptile) { uint32** PALmap = img->PALmap; int samplesperpixel = img->samplesperpixel; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PALmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 4-bit palette => colormap/RGB */ DECLAREContigPutFunc(put4bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit palette => colormap/RGB */ DECLAREContigPutFunc(put2bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 1-bit palette => colormap/RGB */ DECLAREContigPutFunc(put1bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(putgreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 8-bit greyscale with associated alpha => colormap/RGBA */ DECLAREContigPutFunc(putagreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0] & ((uint32)*(pp+1) << 24 | ~A1); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put16bitbwtile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { uint16 *wp = (uint16 *) pp; for (x = w; x > 0; --x) { /* use high order byte of 16bit value */ *cp++ = BWmap[*wp >> 8][0]; pp += 2 * samplesperpixel; wp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 1-bit bilevel => colormap/RGB */ DECLAREContigPutFunc(put1bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put2bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 4-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put4bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples, no Map => RGB */ DECLAREContigPutFunc(putRGBcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(pp[0], pp[1], pp[2]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r, g, b, a; uint8* m; for (x = w; x > 0; --x) { a = pp[3]; m = img->UaToAa+((size_t) a<<8); r = m[pp[0]]; g = m[pp[1]]; b = m[pp[2]]; *cp++ = PACK4(r,g,b,a); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit packed samples => RGB */ DECLAREContigPutFunc(putRGBcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK4(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]], img->Bitdepth16To8[wp[3]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r,g,b,a; uint8* m; for (x = w; x > 0; --x) { a = img->Bitdepth16To8[wp[3]]; m = img->UaToAa+((size_t) a<<8); r = m[img->Bitdepth16To8[wp[0]]]; g = m[img->Bitdepth16To8[wp[1]]]; b = m[img->Bitdepth16To8[wp[2]]]; *cp++ = PACK4(r,g,b,a); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 8-bit packed CMYK samples w/o Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKtile) { int samplesperpixel = img->samplesperpixel; uint16 r, g, b, k; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(r, g, b); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed CMYK samples w/Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile) { int samplesperpixel = img->samplesperpixel; TIFFRGBValue* Map = img->Map; uint16 r, g, b, k; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(Map[r], Map[g], Map[b]); pp += samplesperpixel; } pp += fromskew; cp += toskew; } } #define DECLARESepPutFunc(name) \ static void name(\ TIFFRGBAImage* img,\ uint32* cp,\ uint32 x, uint32 y, \ uint32 w, uint32 h,\ int32 fromskew, int32 toskew,\ unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a\ ) /* * 8-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate8bittile) { (void) img; (void) x; (void) y; (void) a; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++)); SKEW(r, g, b, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate8bittile) { (void) img; (void) x; (void) y; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++)); SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked CMYK samples => RGBA */ DECLARESepPutFunc(putCMYKseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, kv; for (x = w; x > 0; --x) { kv = 255 - *a++; rv = (kv*(255-*r++))/255; gv = (kv*(255-*g++))/255; bv = (kv*(255-*b++))/255; *cp++ = PACK4(rv,gv,bv,255); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, av; uint8* m; for (x = w; x > 0; --x) { av = *a++; m = img->UaToAa+((size_t) av<<8); rv = m[*r++]; gv = m[*g++]; bv = m[*b++]; *cp++ = PACK4(rv,gv,bv,av); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; (void) img; (void) y; (void) a; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++]); SKEW(wr, wg, wb, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK4(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++], img->Bitdepth16To8[*wa++]); SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { uint32 r2,g2,b2,a2; uint8* m; for (x = w; x > 0; --x) { a2 = img->Bitdepth16To8[*wa++]; m = img->UaToAa+((size_t) a2<<8); r2 = m[img->Bitdepth16To8[*wr++]]; g2 = m[img->Bitdepth16To8[*wg++]]; b2 = m[img->Bitdepth16To8[*wb++]]; *cp++ = PACK4(r2,g2,b2,a2); } SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 8-bit packed CIE L*a*b 1976 samples => RGB */ DECLAREContigPutFunc(putcontig8bitCIELab) { float X, Y, Z; uint32 r, g, b; (void) y; fromskew *= 3; for( ; h > 0; --h) { for (x = w; x > 0; --x) { TIFFCIELabToXYZ(img->cielab, (unsigned char)pp[0], (signed char)pp[1], (signed char)pp[2], &X, &Y, &Z); TIFFXYZToRGB(img->cielab, X, Y, Z, &r, &g, &b); *cp++ = PACK(r, g, b); pp += 3; } cp += toskew; pp += fromskew; } } /* * YCbCr -> RGB conversion and packing routines. */ #define YCbCrtoRGB(dst, Y) { \ uint32 r, g, b; \ TIFFYCbCrtoRGB(img->ycbcr, (Y), Cb, Cr, &r, &g, &b); \ dst = PACK(r, g, b); \ } /* * 8-bit packed YCbCr samples => RGB * This function is generic for different sampling sizes, * and can handle blocks sizes that aren't multiples of the * sampling size. However, it is substantially less optimized * than the specific sampling cases. It is used as a fallback * for difficult blocks. */ #ifdef notdef static void putcontig8bitYCbCrGenericTile( TIFFRGBAImage* img, uint32* cp, uint32 x, uint32 y, uint32 w, uint32 h, int32 fromskew, int32 toskew, unsigned char* pp, int h_group, int v_group ) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; int32 Cb, Cr; int group_size = v_group * h_group + 2; (void) y; fromskew = (fromskew * group_size) / h_group; for( yy = 0; yy < h; yy++ ) { unsigned char *pp_line; int y_line_group = yy / v_group; int y_remainder = yy - y_line_group * v_group; pp_line = pp + v_line_group * for( xx = 0; xx < w; xx++ ) { Cb = pp } } for (; h >= 4; h -= 4) { x = w>>2; do { Cb = pp[16]; Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; pp += 18; } while (--x); cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; pp += fromskew; } } #endif /* * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr44tile) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; (void) y; /* adjust fromskew */ fromskew = (fromskew / 4) * (4*2+2); if ((h & 3) == 0 && (w & 3) == 0) { for (; h >= 4; h -= 4) { x = w>>2; do { int32 Cb = pp[16]; int32 Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; pp += 18; } while (--x); cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[16]; int32 Cr = pp[17]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; cp2 += x; cp3 += x; x = 0; } else { cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; x -= 4; } pp += 18; } if (h <= 4) break; h -= 4; cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr42tile) { uint32* cp1 = cp+w+toskew; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 4) * (4*2+2); if ((w & 3) == 0 && (h & 1) == 0) { for (; h >= 2; h -= 2) { x = w>>2; do { int32 Cb = pp[8]; int32 Cr = pp[9]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); YCbCrtoRGB(cp1[0], pp[4]); YCbCrtoRGB(cp1[1], pp[5]); YCbCrtoRGB(cp1[2], pp[6]); YCbCrtoRGB(cp1[3], pp[7]); cp += 4; cp1 += 4; pp += 10; } while (--x); cp += incr; cp1 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[8]; int32 Cr = pp[9]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; x = 0; } else { cp += 4; cp1 += 4; x -= 4; } pp += 10; } if (h <= 2) break; h -= 2; cp += incr; cp1 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr41tile) { (void) y; fromskew = (fromskew / 4) * (4*1+2); do { x = w>>2; while(x>0) { int32 Cb = pp[4]; int32 Cr = pp[5]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); cp += 4; pp += 6; x--; } if( (w&3) != 0 ) { int32 Cb = pp[4]; int32 Cr = pp[5]; switch( (w&3) ) { case 3: YCbCrtoRGB(cp [2], pp[2]); /*-fallthrough*/ case 2: YCbCrtoRGB(cp [1], pp[1]); /*-fallthrough*/ case 1: YCbCrtoRGB(cp [0], pp[0]); /*-fallthrough*/ case 0: break; } cp += (w&3); pp += 6; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr22tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 2) * (2*2+2); cp2 = cp+w+toskew; while (h>=2) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); YCbCrtoRGB(cp2[0], pp[2]); YCbCrtoRGB(cp2[1], pp[3]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[2]); cp ++ ; cp2 ++ ; pp += 6; } cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); } } } /* * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr21tile) { (void) y; fromskew = (fromskew / 2) * (2*1+2); do { x = w>>1; while(x>0) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; pp += 4; x --; } if( (w&1) != 0 ) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp += 1; pp += 4; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 1,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr12tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 1) * (1 * 2 + 2); cp2 = cp+w+toskew; while (h>=2) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[1]); cp ++; cp2 ++; pp += 4; } while (--x); cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp ++; pp += 4; } while (--x); } } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr11tile) { (void) y; fromskew = (fromskew / 1) * (1 * 1 + 2); do { x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */ do { int32 Cb = pp[1]; int32 Cr = pp[2]; YCbCrtoRGB(*cp++, pp[0]); pp += 3; } while (--x); cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLARESepPutFunc(putseparate8bitYCbCr11tile) { (void) y; (void) a; /* TODO: naming of input vars is still off, change obfuscating declaration inside define, or resolve obfuscation */ for( ; h > 0; --h) { x = w; do { uint32 dr, dg, db; TIFFYCbCrtoRGB(img->ycbcr,*r++,*g++,*b++,&dr,&dg,&db); *cp++ = PACK(dr,dg,db); } while (--x); SKEW(r, g, b, fromskew); cp += toskew; } } #undef YCbCrtoRGB static int isInRefBlackWhiteRange(float f) { return f > (float)(-0x7FFFFFFF + 128) && f < (float)0x7FFFFFFF; } static int initYCbCrConversion(TIFFRGBAImage* img) { static const char module[] = "initYCbCrConversion"; float *luma, *refBlackWhite; if (img->ycbcr == NULL) { img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc( TIFFroundup_32(sizeof (TIFFYCbCrToRGB), sizeof (long)) + 4*256*sizeof (TIFFRGBValue) + 2*256*sizeof (int) + 3*256*sizeof (int32) ); if (img->ycbcr == NULL) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for YCbCr->RGB conversion state"); return (0); } } TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &luma); TIFFGetFieldDefaulted(img->tif, TIFFTAG_REFERENCEBLACKWHITE, &refBlackWhite); /* Do some validation to avoid later issues. Detect NaN for now */ /* and also if lumaGreen is zero since we divide by it later */ if( luma[0] != luma[0] || luma[1] != luma[1] || luma[1] == 0.0 || luma[2] != luma[2] ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for YCbCrCoefficients tag"); return (0); } if( !isInRefBlackWhiteRange(refBlackWhite[0]) || !isInRefBlackWhiteRange(refBlackWhite[1]) || !isInRefBlackWhiteRange(refBlackWhite[2]) || !isInRefBlackWhiteRange(refBlackWhite[3]) || !isInRefBlackWhiteRange(refBlackWhite[4]) || !isInRefBlackWhiteRange(refBlackWhite[5]) ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for ReferenceBlackWhite tag"); return (0); } if (TIFFYCbCrToRGBInit(img->ycbcr, luma, refBlackWhite) < 0) return(0); return (1); } static tileContigRoutine initCIELabConversion(TIFFRGBAImage* img) { static const char module[] = "initCIELabConversion"; float *whitePoint; float refWhite[3]; TIFFGetFieldDefaulted(img->tif, TIFFTAG_WHITEPOINT, &whitePoint); if (whitePoint[1] == 0.0f ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid value for WhitePoint tag."); return NULL; } if (!img->cielab) { img->cielab = (TIFFCIELabToRGB *) _TIFFmalloc(sizeof(TIFFCIELabToRGB)); if (!img->cielab) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for CIE L*a*b*->RGB conversion state."); return NULL; } } refWhite[1] = 100.0F; refWhite[0] = whitePoint[0] / whitePoint[1] * refWhite[1]; refWhite[2] = (1.0F - whitePoint[0] - whitePoint[1]) / whitePoint[1] * refWhite[1]; if (TIFFCIELabToRGBInit(img->cielab, &display_sRGB, refWhite) < 0) { TIFFErrorExt(img->tif->tif_clientdata, module, "Failed to initialize CIE L*a*b*->RGB conversion state."); _TIFFfree(img->cielab); return NULL; } return putcontig8bitCIELab; } /* * Greyscale images with less than 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*bwtile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makebwmap(TIFFRGBAImage* img) { TIFFRGBValue* Map = img->Map; int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; int i; uint32* p; if( nsamples == 0 ) nsamples = 1; img->BWmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->BWmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for B&W mapping table"); return (0); } p = (uint32*)(img->BWmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->BWmap[i] = p; switch (bitspersample) { #define GREY(x) c = Map[x]; *p++ = PACK(c,c,c); case 1: GREY(i>>7); GREY((i>>6)&1); GREY((i>>5)&1); GREY((i>>4)&1); GREY((i>>3)&1); GREY((i>>2)&1); GREY((i>>1)&1); GREY(i&1); break; case 2: GREY(i>>6); GREY((i>>4)&3); GREY((i>>2)&3); GREY(i&3); break; case 4: GREY(i>>4); GREY(i&0xf); break; case 8: case 16: GREY(i); break; } #undef GREY } return (1); } /* * Construct a mapping table to convert from the range * of the data samples to [0,255] --for display. This * process also handles inverting B&W images when needed. */ static int setupMap(TIFFRGBAImage* img) { int32 x, range; range = (int32)((1L<<img->bitspersample)-1); /* treat 16 bit the same as eight bit */ if( img->bitspersample == 16 ) range = (int32) 255; img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue)); if (img->Map == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for photometric conversion table"); return (0); } if (img->photometric == PHOTOMETRIC_MINISWHITE) { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range); } else { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) ((x * 255) / range); } if (img->bitspersample <= 16 && (img->photometric == PHOTOMETRIC_MINISBLACK || img->photometric == PHOTOMETRIC_MINISWHITE)) { /* * Use photometric mapping table to construct * unpacking tables for samples <= 8 bits. */ if (!makebwmap(img)) return (0); /* no longer need Map, free it */ _TIFFfree(img->Map); img->Map = NULL; } return (1); } static int checkcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long n = 1L<<img->bitspersample; while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); return (8); } static void cvtcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long i; for (i = (1L<<img->bitspersample)-1; i >= 0; i--) { #define CVT(x) ((uint16)((x)>>8)) r[i] = CVT(r[i]); g[i] = CVT(g[i]); b[i] = CVT(b[i]); #undef CVT } } /* * Palette images with <= 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*cmaptile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makecmap(TIFFRGBAImage* img) { int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; uint32 *p; int i; img->PALmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->PALmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for Palette mapping table"); return (0); } p = (uint32*)(img->PALmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->PALmap[i] = p; #define CMAP(x) c = (TIFFRGBValue) x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff); switch (bitspersample) { case 1: CMAP(i>>7); CMAP((i>>6)&1); CMAP((i>>5)&1); CMAP((i>>4)&1); CMAP((i>>3)&1); CMAP((i>>2)&1); CMAP((i>>1)&1); CMAP(i&1); break; case 2: CMAP(i>>6); CMAP((i>>4)&3); CMAP((i>>2)&3); CMAP(i&3); break; case 4: CMAP(i>>4); CMAP(i&0xf); break; case 8: CMAP(i); break; } #undef CMAP } return (1); } /* * Construct any mapping table used * by the associated put routine. */ static int buildMap(TIFFRGBAImage* img) { switch (img->photometric) { case PHOTOMETRIC_RGB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8) break; /* fall through... */ case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_MINISWHITE: if (!setupMap(img)) return (0); break; case PHOTOMETRIC_PALETTE: /* * Convert 16-bit colormap to 8-bit (unless it looks * like an old-style 8-bit colormap). */ if (checkcmap(img) == 16) cvtcmap(img); else TIFFWarningExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "Assuming 8-bit colormap"); /* * Use mapping table and colormap to construct * unpacking tables for samples < 8 bits. */ if (img->bitspersample <= 8 && !makecmap(img)) return (0); break; } return (1); } /* * Select the appropriate conversion routine for packed data. */ static int PickContigCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileContig : gtStripContig; img->put.contig = NULL; switch (img->photometric) { case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >= 4) img->put.contig = putRGBAAcontig8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >= 4) { if (BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig8bittile; } else if( img->samplesperpixel >= 3 ) img->put.contig = putRGBcontig8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBAAcontig16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig16bittile; } else if( img->samplesperpixel >=3 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBcontig16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->samplesperpixel >=4 && buildMap(img)) { if (img->bitspersample == 8) { if (!img->Map) img->put.contig = putRGBcontig8bitCMYKtile; else img->put.contig = putRGBcontig8bitCMYKMaptile; } } break; case PHOTOMETRIC_PALETTE: if (buildMap(img)) { switch (img->bitspersample) { case 8: img->put.contig = put8bitcmaptile; break; case 4: img->put.contig = put4bitcmaptile; break; case 2: img->put.contig = put2bitcmaptile; break; case 1: img->put.contig = put1bitcmaptile; break; } } break; case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (buildMap(img)) { switch (img->bitspersample) { case 16: img->put.contig = put16bitbwtile; break; case 8: if (img->alpha && img->samplesperpixel == 2) img->put.contig = putagreytile; else img->put.contig = putgreytile; break; case 4: img->put.contig = put4bitbwtile; break; case 2: img->put.contig = put2bitbwtile; break; case 1: img->put.contig = put1bitbwtile; break; } } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { /* * The 6.0 spec says that subsampling must be * one of 1, 2, or 4, and that vertical subsampling * must always be <= horizontal subsampling; so * there are only a few possibilities and we just * enumerate the cases. * Joris: added support for the [1,2] case, nonetheless, to accommodate * some OJPEG files */ uint16 SubsamplingHor; uint16 SubsamplingVer; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &SubsamplingHor, &SubsamplingVer); switch ((SubsamplingHor<<4)|SubsamplingVer) { case 0x44: img->put.contig = putcontig8bitYCbCr44tile; break; case 0x42: img->put.contig = putcontig8bitYCbCr42tile; break; case 0x41: img->put.contig = putcontig8bitYCbCr41tile; break; case 0x22: img->put.contig = putcontig8bitYCbCr22tile; break; case 0x21: img->put.contig = putcontig8bitYCbCr21tile; break; case 0x12: img->put.contig = putcontig8bitYCbCr12tile; break; case 0x11: img->put.contig = putcontig8bitYCbCr11tile; break; } } } break; case PHOTOMETRIC_CIELAB: if (img->samplesperpixel == 3 && buildMap(img)) { if (img->bitspersample == 8) img->put.contig = initCIELabConversion(img); break; } } return ((img->get!=NULL) && (img->put.contig!=NULL)); } /* * Select the appropriate conversion routine for unpacked data. * * NB: we assume that unpacked single channel data is directed * to the "packed routines. */ static int PickSeparateCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileSeparate : gtStripSeparate; img->put.separate = NULL; switch (img->photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: /* greyscale images processed pretty much as RGB by gtTileSeparate */ case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) img->put.separate = putRGBAAseparate8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate8bittile; } else img->put.separate = putRGBseparate8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBAAseparate16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate16bittile; } else { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBseparate16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8 && img->samplesperpixel == 4) { img->alpha = 1; // Not alpha, but seems like the only way to get 4th band img->put.separate = putCMYKseparate8bittile; } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { uint16 hs, vs; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs); switch ((hs<<4)|vs) { case 0x11: img->put.separate = putseparate8bitYCbCr11tile; break; /* TODO: add other cases here */ } } } break; } return ((img->get!=NULL) && (img->put.separate!=NULL)); } static int BuildMapUaToAa(TIFFRGBAImage* img) { static const char module[]="BuildMapUaToAa"; uint8* m; uint16 na,nv; assert(img->UaToAa==NULL); img->UaToAa=_TIFFmalloc(65536); if (img->UaToAa==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->UaToAa; for (na=0; na<256; na++) { for (nv=0; nv<256; nv++) *m++=(uint8)((nv*na+127)/255); } return(1); } static int BuildMapBitdepth16To8(TIFFRGBAImage* img) { static const char module[]="BuildMapBitdepth16To8"; uint8* m; uint32 n; assert(img->Bitdepth16To8==NULL); img->Bitdepth16To8=_TIFFmalloc(65536); if (img->Bitdepth16To8==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->Bitdepth16To8; for (n=0; n<65536; n++) *m++=(uint8)((n+128)/257); return(1); } /* * Read a whole strip off data from the file, and convert to RGBA form. * If this is the last strip, then it will only contain the portion of * the strip that is actually within the image space. The result is * organized in bottom to top form. */ int TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster ) { return TIFFReadRGBAStripExt(tif, row, raster, 0 ); } int TIFFReadRGBAStripExt(TIFF* tif, uint32 row, uint32 * raster, int stop_on_error) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 rowsperstrip, rows_to_read; if( TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBAStrip() with tiled file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); if( (row % rowsperstrip) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row passed to TIFFReadRGBAStrip() must be first in a strip."); return (0); } if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { img.row_offset = row; img.col_offset = 0; if( row + rowsperstrip > img.height ) rows_to_read = img.height - row; else rows_to_read = rowsperstrip; ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read ); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read a whole tile off data from the file, and convert to RGBA form. * The returned RGBA data is organized from bottom to top of tile, * and may include zeroed areas if the tile extends off the image. */ int TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster) { return TIFFReadRGBATileExt(tif, col, row, raster, 0 ); } int TIFFReadRGBATileExt(TIFF* tif, uint32 col, uint32 row, uint32 * raster, int stop_on_error ) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 tile_xsize, tile_ysize; uint32 read_xsize, read_ysize; uint32 i_row; /* * Verify that our request is legal - on a tile file, and on a * tile boundary. */ if( !TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBATile() with striped file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize); TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize); if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row/col passed to TIFFReadRGBATile() must be top" "left corner of a tile."); return (0); } /* * Setup the RGBA reader. */ if (!TIFFRGBAImageOK(tif, emsg) || !TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); return( 0 ); } /* * The TIFFRGBAImageGet() function doesn't allow us to get off the * edge of the image, even to fill an otherwise valid tile. So we * figure out how much we can read, and fix up the tile buffer to * a full tile configuration afterwards. */ if( row + tile_ysize > img.height ) read_ysize = img.height - row; else read_ysize = tile_ysize; if( col + tile_xsize > img.width ) read_xsize = img.width - col; else read_xsize = tile_xsize; /* * Read the chunk of imagery. */ img.row_offset = row; img.col_offset = col; ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize ); TIFFRGBAImageEnd(&img); /* * If our read was incomplete we will need to fix up the tile by * shifting the data around as if a full tile of data is being returned. * * This is all the more complicated because the image is organized in * bottom to top format. */ if( read_xsize == tile_xsize && read_ysize == tile_ysize ) return( ok ); for( i_row = 0; i_row < read_ysize; i_row++ ) { memmove( raster + (tile_ysize - i_row - 1) * tile_xsize, raster + (read_ysize - i_row - 1) * read_xsize, read_xsize * sizeof(uint32) ); _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize, 0, sizeof(uint32) * (tile_xsize - read_xsize) ); } for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) { _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize, 0, sizeof(uint32) * tile_xsize ); } return (ok); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1185_0
crossvul-cpp_data_good_4852_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Tier-2 Coding Library * * $Id$ */ #include "jasper/jas_math.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" #include "jpc_cs.h" #include "jpc_t2cod.h" #include "jpc_math.h" static int jpc_pi_nextlrcp(jpc_pi_t *pi); static int jpc_pi_nextrlcp(jpc_pi_t *pi); static int jpc_pi_nextrpcl(jpc_pi_t *pi); static int jpc_pi_nextpcrl(jpc_pi_t *pi); static int jpc_pi_nextcprl(jpc_pi_t *pi); int jpc_pi_next(jpc_pi_t *pi) { jpc_pchg_t *pchg; int ret; for (;;) { pi->valid = false; if (!pi->pchg) { ++pi->pchgno; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->prgvolfirst = true; if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno); } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = &pi->defaultpchg; } else { return 1; } } pchg = pi->pchg; switch (pchg->prgord) { case JPC_COD_LRCPPRG: ret = jpc_pi_nextlrcp(pi); break; case JPC_COD_RLCPPRG: ret = jpc_pi_nextrlcp(pi); break; case JPC_COD_RPCLPRG: ret = jpc_pi_nextrpcl(pi); break; case JPC_COD_PCRLPRG: ret = jpc_pi_nextpcrl(pi); break; case JPC_COD_CPRLPRG: ret = jpc_pi_nextcprl(pi); break; default: ret = -1; break; } if (!ret) { pi->valid = true; ++pi->pktno; return 0; } pi->pchg = 0; } } static int jpc_pi_nextlrcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = false; } for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (1 << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (1 << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextpcrl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; pi->xstep = pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (JAS_CAST(uint_fast32_t, 1) << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static void pirlvl_destroy(jpc_pirlvl_t *rlvl) { if (rlvl->prclyrnos) { jas_free(rlvl->prclyrnos); } } static void jpc_picomp_destroy(jpc_picomp_t *picomp) { int rlvlno; jpc_pirlvl_t *pirlvl; if (picomp->pirlvls) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl_destroy(pirlvl); } jas_free(picomp->pirlvls); } } void jpc_pi_destroy(jpc_pi_t *pi) { jpc_picomp_t *picomp; int compno; if (pi->picomps) { for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { jpc_picomp_destroy(picomp); } jas_free(pi->picomps); } if (pi->pchglist) { jpc_pchglist_destroy(pi->pchglist); } jas_free(pi); } jpc_pi_t *jpc_pi_create0() { jpc_pi_t *pi; if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) { return 0; } pi->picomps = 0; pi->pchgno = 0; if (!(pi->pchglist = jpc_pchglist_create())) { jas_free(pi); return 0; } return pi; } int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg) { return jpc_pchglist_insert(pi->pchglist, -1, pchg); } jpc_pchglist_t *jpc_pchglist_create() { jpc_pchglist_t *pchglist; if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) { return 0; } pchglist->numpchgs = 0; pchglist->maxpchgs = 0; pchglist->pchgs = 0; return pchglist; } int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) { int i; int newmaxpchgs; jpc_pchg_t **newpchgs; if (pchgno < 0) { pchgno = pchglist->numpchgs; } if (pchglist->numpchgs >= pchglist->maxpchgs) { newmaxpchgs = pchglist->maxpchgs + 128; if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs, sizeof(jpc_pchg_t *)))) { return -1; } pchglist->maxpchgs = newmaxpchgs; pchglist->pchgs = newpchgs; } for (i = pchglist->numpchgs; i > pchgno; --i) { pchglist->pchgs[i] = pchglist->pchgs[i - 1]; } pchglist->pchgs[pchgno] = pchg; ++pchglist->numpchgs; return 0; } jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno) { int i; jpc_pchg_t *pchg; assert(pchgno < pchglist->numpchgs); pchg = pchglist->pchgs[pchgno]; for (i = pchgno + 1; i < pchglist->numpchgs; ++i) { pchglist->pchgs[i - 1] = pchglist->pchgs[i]; } --pchglist->numpchgs; return pchg; } jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg) { jpc_pchg_t *newpchg; if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) { return 0; } *newpchg = *pchg; return newpchg; } jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist) { jpc_pchglist_t *newpchglist; jpc_pchg_t *newpchg; int pchgno; if (!(newpchglist = jpc_pchglist_create())) { return 0; } for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) || jpc_pchglist_insert(newpchglist, -1, newpchg)) { jpc_pchglist_destroy(newpchglist); return 0; } } return newpchglist; } void jpc_pchglist_destroy(jpc_pchglist_t *pchglist) { int pchgno; if (pchglist->pchgs) { for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { jpc_pchg_destroy(pchglist->pchgs[pchgno]); } jas_free(pchglist->pchgs); } jas_free(pchglist); } void jpc_pchg_destroy(jpc_pchg_t *pchg) { jas_free(pchg); } jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno) { return pchglist->pchgs[pchgno]; } int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist) { return pchglist->numpchgs; } int jpc_pi_init(jpc_pi_t *pi) { int compno; int rlvlno; int prcno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; int *prclyrno; pi->prgvolfirst = 0; pi->valid = 0; pi->pktno = -1; pi->pchgno = -1; pi->pchg = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } } } return 0; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_4852_0
crossvul-cpp_data_bad_5400_1
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Image Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <ctype.h> #include <inttypes.h> #include <stdbool.h> #include "jasper/jas_math.h" #include "jasper/jas_image.h" #include "jasper/jas_malloc.h" #include "jasper/jas_string.h" #include "jasper/jas_debug.h" /******************************************************************************\ * Types. \******************************************************************************/ #define FLOORDIV(x, y) ((x) / (y)) /******************************************************************************\ * Local prototypes. \******************************************************************************/ static jas_image_cmpt_t *jas_image_cmpt_create0(void); static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt); static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem); static void jas_image_setbbox(jas_image_t *image); static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt); static int jas_image_growcmpts(jas_image_t *image, int maxcmpts); static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd); static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd); static int putint(jas_stream_t *out, int sgnd, int prec, long val); static int getint(jas_stream_t *in, int sgnd, int prec, long *val); static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry); static long uptomult(long x, long y); static long downtomult(long x, long y); static long convert(long val, int oldsgnd, int oldprec, int newsgnd, int newprec); static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry); /******************************************************************************\ * Global data. \******************************************************************************/ static int jas_image_numfmts = 0; static jas_image_fmtinfo_t jas_image_fmtinfos[JAS_IMAGE_MAXFMTS]; /******************************************************************************\ * Create and destroy operations. \******************************************************************************/ jas_image_t *jas_image_create(int numcmpts, jas_image_cmptparm_t *cmptparms, int clrspc) { jas_image_t *image; uint_fast32_t rawsize; uint_fast32_t inmem; int cmptno; jas_image_cmptparm_t *cmptparm; if (!(image = jas_image_create0())) { return 0; } image->clrspc_ = clrspc; image->maxcmpts_ = numcmpts; image->inmem_ = true; /* Allocate memory for the per-component information. */ if (!(image->cmpts_ = jas_alloc2(image->maxcmpts_, sizeof(jas_image_cmpt_t *)))) { jas_image_destroy(image); return 0; } /* Initialize in case of failure. */ for (cmptno = 0; cmptno < image->maxcmpts_; ++cmptno) { image->cmpts_[cmptno] = 0; } /* Compute the approximate raw size of the image. */ rawsize = 0; for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { rawsize += cmptparm->width * cmptparm->height * (cmptparm->prec + 7) / 8; } /* Decide whether to buffer the image data in memory, based on the raw size of the image. */ inmem = (rawsize < JAS_IMAGE_INMEMTHRESH); /* Create the individual image components. */ for (cmptno = 0, cmptparm = cmptparms; cmptno < numcmpts; ++cmptno, ++cmptparm) { if (!(image->cmpts_[cmptno] = jas_image_cmpt_create(cmptparm->tlx, cmptparm->tly, cmptparm->hstep, cmptparm->vstep, cmptparm->width, cmptparm->height, cmptparm->prec, cmptparm->sgnd, inmem))) { jas_image_destroy(image); return 0; } ++image->numcmpts_; } /* Determine the bounding box for all of the components on the reference grid (i.e., the image area) */ jas_image_setbbox(image); return image; } jas_image_t *jas_image_create0() { jas_image_t *image; if (!(image = jas_malloc(sizeof(jas_image_t)))) { return 0; } image->tlx_ = 0; image->tly_ = 0; image->brx_ = 0; image->bry_ = 0; image->clrspc_ = JAS_CLRSPC_UNKNOWN; image->numcmpts_ = 0; image->maxcmpts_ = 0; image->cmpts_ = 0; image->inmem_ = true; image->cmprof_ = 0; return image; } jas_image_t *jas_image_copy(jas_image_t *image) { jas_image_t *newimage; int cmptno; if (!(newimage = jas_image_create0())) { goto error; } if (jas_image_growcmpts(newimage, image->numcmpts_)) { goto error; } for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { if (!(newimage->cmpts_[cmptno] = jas_image_cmpt_copy(image->cmpts_[cmptno]))) { goto error; } ++newimage->numcmpts_; } jas_image_setbbox(newimage); if (image->cmprof_) { if (!(newimage->cmprof_ = jas_cmprof_copy(image->cmprof_))) goto error; } return newimage; error: if (newimage) { jas_image_destroy(newimage); } return 0; } static jas_image_cmpt_t *jas_image_cmpt_create0() { jas_image_cmpt_t *cmpt; if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { return 0; } memset(cmpt, 0, sizeof(jas_image_cmpt_t)); cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; return cmpt; } static jas_image_cmpt_t *jas_image_cmpt_copy(jas_image_cmpt_t *cmpt) { jas_image_cmpt_t *newcmpt; if (!(newcmpt = jas_image_cmpt_create0())) { return 0; } newcmpt->tlx_ = cmpt->tlx_; newcmpt->tly_ = cmpt->tly_; newcmpt->hstep_ = cmpt->hstep_; newcmpt->vstep_ = cmpt->vstep_; newcmpt->width_ = cmpt->width_; newcmpt->height_ = cmpt->height_; newcmpt->prec_ = cmpt->prec_; newcmpt->sgnd_ = cmpt->sgnd_; newcmpt->cps_ = cmpt->cps_; newcmpt->type_ = cmpt->type_; if (!(newcmpt->stream_ = jas_stream_memopen(0, 0))) { goto error; } if (jas_stream_seek(cmpt->stream_, 0, SEEK_SET)) { goto error; } if (jas_stream_copy(newcmpt->stream_, cmpt->stream_, -1)) { goto error; } if (jas_stream_seek(newcmpt->stream_, 0, SEEK_SET)) { goto error; } return newcmpt; error: if (newcmpt) { jas_image_cmpt_destroy(newcmpt); } return 0; } void jas_image_destroy(jas_image_t *image) { int i; if (image->cmpts_) { for (i = 0; i < image->numcmpts_; ++i) { jas_image_cmpt_destroy(image->cmpts_[i]); image->cmpts_[i] = 0; } jas_free(image->cmpts_); } if (image->cmprof_) jas_cmprof_destroy(image->cmprof_); jas_free(image); } static jas_image_cmpt_t *jas_image_cmpt_create(int_fast32_t tlx, int_fast32_t tly, int_fast32_t hstep, int_fast32_t vstep, int_fast32_t width, int_fast32_t height, uint_fast16_t depth, bool sgnd, uint_fast32_t inmem) { jas_image_cmpt_t *cmpt; size_t size; cmpt = 0; if (width < 0 || height < 0 || hstep <= 0 || vstep <= 0) { goto error; } if (!jas_safe_intfast32_add(tlx, width, 0) || !jas_safe_intfast32_add(tly, height, 0)) { goto error; } if (!(cmpt = jas_malloc(sizeof(jas_image_cmpt_t)))) { goto error; } cmpt->type_ = JAS_IMAGE_CT_UNKNOWN; cmpt->tlx_ = tlx; cmpt->tly_ = tly; cmpt->hstep_ = hstep; cmpt->vstep_ = vstep; cmpt->width_ = width; cmpt->height_ = height; cmpt->prec_ = depth; cmpt->sgnd_ = sgnd; cmpt->stream_ = 0; cmpt->cps_ = (depth + 7) / 8; // Compute the number of samples in the image component, while protecting // against overflow. // size = cmpt->width_ * cmpt->height_ * cmpt->cps_; if (!jas_safe_size_mul(cmpt->width_, cmpt->height_, &size) || !jas_safe_size_mul(size, cmpt->cps_, &size)) { goto error; } cmpt->stream_ = (inmem) ? jas_stream_memopen(0, size) : jas_stream_tmpfile(); if (!cmpt->stream_) { goto error; } /* Zero the component data. This isn't necessary, but it is convenient for debugging purposes. */ /* Note: conversion of size - 1 to long can overflow */ if (jas_stream_seek(cmpt->stream_, size - 1, SEEK_SET) < 0 || jas_stream_putc(cmpt->stream_, 0) == EOF || jas_stream_seek(cmpt->stream_, 0, SEEK_SET) < 0) { goto error; } return cmpt; error: if (cmpt) { jas_image_cmpt_destroy(cmpt); } return 0; } static void jas_image_cmpt_destroy(jas_image_cmpt_t *cmpt) { if (cmpt->stream_) { jas_stream_close(cmpt->stream_); } jas_free(cmpt); } /******************************************************************************\ * Load and save operations. \******************************************************************************/ jas_image_t *jas_image_decode(jas_stream_t *in, int fmt, char *optstr) { jas_image_fmtinfo_t *fmtinfo; jas_image_t *image; image = 0; /* If possible, try to determine the format of the input data. */ if (fmt < 0) { if ((fmt = jas_image_getfmt(in)) < 0) goto error; } /* Is it possible to decode an image represented in this format? */ if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) goto error; if (!fmtinfo->ops.decode) goto error; /* Decode the image. */ if (!(image = (*fmtinfo->ops.decode)(in, optstr))) goto error; /* Create a color profile if needed. */ if (!jas_clrspc_isunknown(image->clrspc_) && !jas_clrspc_isgeneric(image->clrspc_) && !image->cmprof_) { if (!(image->cmprof_ = jas_cmprof_createfromclrspc(jas_image_clrspc(image)))) goto error; } return image; error: if (image) jas_image_destroy(image); return 0; } int jas_image_encode(jas_image_t *image, jas_stream_t *out, int fmt, char *optstr) { jas_image_fmtinfo_t *fmtinfo; if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) { return -1; } return (fmtinfo->ops.encode) ? (*fmtinfo->ops.encode)(image, out, optstr) : (-1); } /******************************************************************************\ * Component read and write operations. \******************************************************************************/ int jas_image_readcmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, jas_matrix_t *data) { jas_image_cmpt_t *cmpt; jas_image_coord_t i; jas_image_coord_t j; int k; jas_seqent_t v; int c; jas_seqent_t *dr; jas_seqent_t *d; int drs; if (cmptno < 0 || cmptno >= image->numcmpts_) { return -1; } cmpt = image->cmpts_[cmptno]; if (x >= cmpt->width_ || y >= cmpt->height_ || x + width > cmpt->width_ || y + height > cmpt->height_) { return -1; } if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) { return -1; } if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) { if (jas_matrix_resize(data, height, width)) { return -1; } } dr = jas_matrix_getref(data, 0, 0); drs = jas_matrix_rowstep(data); for (i = 0; i < height; ++i, dr += drs) { d = dr; if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) * cmpt->cps_, SEEK_SET) < 0) { return -1; } for (j = width; j > 0; --j, ++d) { v = 0; for (k = cmpt->cps_; k > 0; --k) { if ((c = jas_stream_getc(cmpt->stream_)) == EOF) { return -1; } v = (v << 8) | (c & 0xff); } *d = bitstoint(v, cmpt->prec_, cmpt->sgnd_); } } return 0; } int jas_image_writecmpt(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, jas_matrix_t *data) { jas_image_cmpt_t *cmpt; jas_image_coord_t i; jas_image_coord_t j; jas_seqent_t *d; jas_seqent_t *dr; int drs; jas_seqent_t v; int k; int c; if (cmptno < 0 || cmptno >= image->numcmpts_) { return -1; } cmpt = image->cmpts_[cmptno]; if (x >= cmpt->width_ || y >= cmpt->height_ || x + width > cmpt->width_ || y + height > cmpt->height_) { return -1; } if (!jas_matrix_numrows(data) || !jas_matrix_numcols(data)) { return -1; } if (jas_matrix_numrows(data) != height || jas_matrix_numcols(data) != width) { return -1; } dr = jas_matrix_getref(data, 0, 0); drs = jas_matrix_rowstep(data); for (i = 0; i < height; ++i, dr += drs) { d = dr; if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) * cmpt->cps_, SEEK_SET) < 0) { return -1; } for (j = width; j > 0; --j, ++d) { v = inttobits(*d, cmpt->prec_, cmpt->sgnd_); for (k = cmpt->cps_; k > 0; --k) { c = (v >> (8 * (cmpt->cps_ - 1))) & 0xff; if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) { return -1; } v <<= 8; } } } return 0; } /******************************************************************************\ * File format operations. \******************************************************************************/ void jas_image_clearfmts() { int i; jas_image_fmtinfo_t *fmtinfo; for (i = 0; i < jas_image_numfmts; ++i) { fmtinfo = &jas_image_fmtinfos[i]; if (fmtinfo->name) { jas_free(fmtinfo->name); fmtinfo->name = 0; } if (fmtinfo->ext) { jas_free(fmtinfo->ext); fmtinfo->ext = 0; } if (fmtinfo->desc) { jas_free(fmtinfo->desc); fmtinfo->desc = 0; } } jas_image_numfmts = 0; } int jas_image_addfmt(int id, char *name, char *ext, char *desc, jas_image_fmtops_t *ops) { jas_image_fmtinfo_t *fmtinfo; assert(id >= 0 && name && ext && ops); if (jas_image_numfmts >= JAS_IMAGE_MAXFMTS) { return -1; } fmtinfo = &jas_image_fmtinfos[jas_image_numfmts]; fmtinfo->id = id; if (!(fmtinfo->name = jas_strdup(name))) { return -1; } if (!(fmtinfo->ext = jas_strdup(ext))) { jas_free(fmtinfo->name); return -1; } if (!(fmtinfo->desc = jas_strdup(desc))) { jas_free(fmtinfo->name); jas_free(fmtinfo->ext); return -1; } fmtinfo->ops = *ops; ++jas_image_numfmts; return 0; } int jas_image_strtofmt(char *name) { jas_image_fmtinfo_t *fmtinfo; if (!(fmtinfo = jas_image_lookupfmtbyname(name))) { return -1; } return fmtinfo->id; } char *jas_image_fmttostr(int fmt) { jas_image_fmtinfo_t *fmtinfo; if (!(fmtinfo = jas_image_lookupfmtbyid(fmt))) { return 0; } return fmtinfo->name; } int jas_image_getfmt(jas_stream_t *in) { jas_image_fmtinfo_t *fmtinfo; int found; int i; /* Check for data in each of the supported formats. */ found = 0; for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { if (fmtinfo->ops.validate) { /* Is the input data valid for this format? */ JAS_DBGLOG(20, ("testing for format %s ... ", fmtinfo->name)); if (!(*fmtinfo->ops.validate)(in)) { JAS_DBGLOG(20, ("test succeeded\n")); found = 1; break; } JAS_DBGLOG(20, ("test failed\n")); } } return found ? fmtinfo->id : (-1); } int jas_image_fmtfromname(char *name) { int i; char *ext; jas_image_fmtinfo_t *fmtinfo; /* Get the file name extension. */ if (!(ext = strrchr(name, '.'))) { return -1; } ++ext; /* Try to find a format that uses this extension. */ for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { /* Do we have a match? */ if (!strcmp(ext, fmtinfo->ext)) { return fmtinfo->id; } } return -1; } /******************************************************************************\ * Miscellaneous operations. \******************************************************************************/ bool jas_image_cmpt_domains_same(jas_image_t *image) { int cmptno; jas_image_cmpt_t *cmpt; jas_image_cmpt_t *cmpt0; cmpt0 = image->cmpts_[0]; for (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) { cmpt = image->cmpts_[cmptno]; if (cmpt->tlx_ != cmpt0->tlx_ || cmpt->tly_ != cmpt0->tly_ || cmpt->hstep_ != cmpt0->hstep_ || cmpt->vstep_ != cmpt0->vstep_ || cmpt->width_ != cmpt0->width_ || cmpt->height_ != cmpt0->height_) { return 0; } } return 1; } uint_fast32_t jas_image_rawsize(jas_image_t *image) { uint_fast32_t rawsize; int cmptno; jas_image_cmpt_t *cmpt; rawsize = 0; for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { cmpt = image->cmpts_[cmptno]; rawsize += (cmpt->width_ * cmpt->height_ * cmpt->prec_ + 7) / 8; } return rawsize; } void jas_image_delcmpt(jas_image_t *image, int cmptno) { if (cmptno >= image->numcmpts_) { return; } jas_image_cmpt_destroy(image->cmpts_[cmptno]); if (cmptno < image->numcmpts_) { memmove(&image->cmpts_[cmptno], &image->cmpts_[cmptno + 1], (image->numcmpts_ - 1 - cmptno) * sizeof(jas_image_cmpt_t *)); } --image->numcmpts_; jas_image_setbbox(image); } int jas_image_addcmpt(jas_image_t *image, int cmptno, jas_image_cmptparm_t *cmptparm) { jas_image_cmpt_t *newcmpt; if (cmptno < 0) { cmptno = image->numcmpts_; } assert(cmptno >= 0 && cmptno <= image->numcmpts_); if (image->numcmpts_ >= image->maxcmpts_) { if (jas_image_growcmpts(image, image->maxcmpts_ + 128)) { return -1; } } if (!(newcmpt = jas_image_cmpt_create(cmptparm->tlx, cmptparm->tly, cmptparm->hstep, cmptparm->vstep, cmptparm->width, cmptparm->height, cmptparm->prec, cmptparm->sgnd, 1))) { return -1; } if (cmptno < image->numcmpts_) { memmove(&image->cmpts_[cmptno + 1], &image->cmpts_[cmptno], (image->numcmpts_ - cmptno) * sizeof(jas_image_cmpt_t *)); } image->cmpts_[cmptno] = newcmpt; ++image->numcmpts_; jas_image_setbbox(image); return 0; } jas_image_fmtinfo_t *jas_image_lookupfmtbyid(int id) { int i; jas_image_fmtinfo_t *fmtinfo; for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { if (fmtinfo->id == id) { return fmtinfo; } } return 0; } jas_image_fmtinfo_t *jas_image_lookupfmtbyname(const char *name) { int i; jas_image_fmtinfo_t *fmtinfo; for (i = 0, fmtinfo = jas_image_fmtinfos; i < jas_image_numfmts; ++i, ++fmtinfo) { if (!strcmp(fmtinfo->name, name)) { return fmtinfo; } } return 0; } static uint_fast32_t inttobits(jas_seqent_t v, int prec, bool sgnd) { uint_fast32_t ret; ret = ((sgnd && v < 0) ? ((1 << prec) + v) : v) & JAS_ONES(prec); return ret; } static jas_seqent_t bitstoint(uint_fast32_t v, int prec, bool sgnd) { jas_seqent_t ret; v &= JAS_ONES(prec); ret = (sgnd && (v & (1 << (prec - 1)))) ? (v - (1 << prec)) : v; return ret; } static void jas_image_setbbox(jas_image_t *image) { jas_image_cmpt_t *cmpt; int cmptno; int_fast32_t x; int_fast32_t y; if (image->numcmpts_ > 0) { /* Determine the bounding box for all of the components on the reference grid (i.e., the image area) */ cmpt = image->cmpts_[0]; image->tlx_ = cmpt->tlx_; image->tly_ = cmpt->tly_; image->brx_ = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1; image->bry_ = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1; for (cmptno = 1; cmptno < image->numcmpts_; ++cmptno) { cmpt = image->cmpts_[cmptno]; if (image->tlx_ > cmpt->tlx_) { image->tlx_ = cmpt->tlx_; } if (image->tly_ > cmpt->tly_) { image->tly_ = cmpt->tly_; } x = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1) + 1; if (image->brx_ < x) { image->brx_ = x; } y = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1) + 1; if (image->bry_ < y) { image->bry_ = y; } } } else { image->tlx_ = 0; image->tly_ = 0; image->brx_ = 0; image->bry_ = 0; } } static int jas_image_growcmpts(jas_image_t *image, int maxcmpts) { jas_image_cmpt_t **newcmpts; int cmptno; newcmpts = (!image->cmpts_) ? jas_alloc2(maxcmpts, sizeof(jas_image_cmpt_t *)) : jas_realloc2(image->cmpts_, maxcmpts, sizeof(jas_image_cmpt_t *)); if (!newcmpts) { return -1; } image->cmpts_ = newcmpts; image->maxcmpts_ = maxcmpts; for (cmptno = image->numcmpts_; cmptno < image->maxcmpts_; ++cmptno) { image->cmpts_[cmptno] = 0; } return 0; } int jas_image_copycmpt(jas_image_t *dstimage, int dstcmptno, jas_image_t *srcimage, int srccmptno) { jas_image_cmpt_t *newcmpt; if (dstimage->numcmpts_ >= dstimage->maxcmpts_) { if (jas_image_growcmpts(dstimage, dstimage->maxcmpts_ + 128)) { return -1; } } if (!(newcmpt = jas_image_cmpt_copy(srcimage->cmpts_[srccmptno]))) { return -1; } if (dstcmptno < dstimage->numcmpts_) { memmove(&dstimage->cmpts_[dstcmptno + 1], &dstimage->cmpts_[dstcmptno], (dstimage->numcmpts_ - dstcmptno) * sizeof(jas_image_cmpt_t *)); } dstimage->cmpts_[dstcmptno] = newcmpt; ++dstimage->numcmpts_; jas_image_setbbox(dstimage); return 0; } void jas_image_dump(jas_image_t *image, FILE *out) { long buf[1024]; int cmptno; int n; int i; int width; int height; jas_image_cmpt_t *cmpt; for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { cmpt = image->cmpts_[cmptno]; fprintf(out, "prec=%d, sgnd=%d, cmpttype=%"PRIiFAST32"\n", cmpt->prec_, cmpt->sgnd_, cmpt->type_); width = jas_image_cmptwidth(image, cmptno); height = jas_image_cmptheight(image, cmptno); n = JAS_MIN(16, width); if (jas_image_readcmpt2(image, cmptno, 0, 0, n, 1, buf)) { abort(); } for (i = 0; i < n; ++i) { fprintf(out, " f(%d,%d)=%ld", i, 0, buf[i]); } fprintf(out, "\n"); if (jas_image_readcmpt2(image, cmptno, width - n, height - 1, n, 1, buf)) { abort(); } for (i = 0; i < n; ++i) { fprintf(out, " f(%d,%d)=%ld", width - n + i, height - 1, buf[i]); } fprintf(out, "\n"); } } int jas_image_depalettize(jas_image_t *image, int cmptno, int numlutents, int_fast32_t *lutents, int dtype, int newcmptno) { jas_image_cmptparm_t cmptparms; int_fast32_t v; int i; int j; jas_image_cmpt_t *cmpt; cmpt = image->cmpts_[cmptno]; cmptparms.tlx = cmpt->tlx_; cmptparms.tly = cmpt->tly_; cmptparms.hstep = cmpt->hstep_; cmptparms.vstep = cmpt->vstep_; cmptparms.width = cmpt->width_; cmptparms.height = cmpt->height_; cmptparms.prec = JAS_IMAGE_CDT_GETPREC(dtype); cmptparms.sgnd = JAS_IMAGE_CDT_GETSGND(dtype); if (jas_image_addcmpt(image, newcmptno, &cmptparms)) { return -1; } if (newcmptno <= cmptno) { ++cmptno; cmpt = image->cmpts_[cmptno]; } for (j = 0; j < cmpt->height_; ++j) { for (i = 0; i < cmpt->width_; ++i) { v = jas_image_readcmptsample(image, cmptno, i, j); if (v < 0) { v = 0; } else if (v >= numlutents) { v = numlutents - 1; } jas_image_writecmptsample(image, newcmptno, i, j, lutents[v]); } } return 0; } int jas_image_readcmptsample(jas_image_t *image, int cmptno, int x, int y) { jas_image_cmpt_t *cmpt; uint_fast32_t v; int k; int c; cmpt = image->cmpts_[cmptno]; if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, SEEK_SET) < 0) { return -1; } v = 0; for (k = cmpt->cps_; k > 0; --k) { if ((c = jas_stream_getc(cmpt->stream_)) == EOF) { return -1; } v = (v << 8) | (c & 0xff); } return bitstoint(v, cmpt->prec_, cmpt->sgnd_); } void jas_image_writecmptsample(jas_image_t *image, int cmptno, int x, int y, int_fast32_t v) { jas_image_cmpt_t *cmpt; uint_fast32_t t; int k; int c; cmpt = image->cmpts_[cmptno]; if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * y + x) * cmpt->cps_, SEEK_SET) < 0) { return; } t = inttobits(v, cmpt->prec_, cmpt->sgnd_); for (k = cmpt->cps_; k > 0; --k) { c = (t >> (8 * (cmpt->cps_ - 1))) & 0xff; if (jas_stream_putc(cmpt->stream_, (unsigned char) c) == EOF) { return; } t <<= 8; } } int jas_image_getcmptbytype(jas_image_t *image, int ctype) { int cmptno; for (cmptno = 0; cmptno < image->numcmpts_; ++cmptno) { if (image->cmpts_[cmptno]->type_ == ctype) { return cmptno; } } return -1; } /***********************************************/ /***********************************************/ /***********************************************/ /***********************************************/ int jas_image_readcmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, long *buf) { jas_image_cmpt_t *cmpt; jas_image_coord_t i; jas_image_coord_t j; long v; long *bufptr; if (cmptno < 0 || cmptno >= image->numcmpts_) goto error; cmpt = image->cmpts_[cmptno]; if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ || width < 0 || height < 0 || x + width > cmpt->width_ || y + height > cmpt->height_) goto error; bufptr = buf; for (i = 0; i < height; ++i) { if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) * cmpt->cps_, SEEK_SET) < 0) goto error; for (j = 0; j < width; ++j) { if (getint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, &v)) goto error; *bufptr++ = v; } } return 0; error: return -1; } int jas_image_writecmpt2(jas_image_t *image, int cmptno, jas_image_coord_t x, jas_image_coord_t y, jas_image_coord_t width, jas_image_coord_t height, long *buf) { jas_image_cmpt_t *cmpt; jas_image_coord_t i; jas_image_coord_t j; long v; long *bufptr; if (cmptno < 0 || cmptno >= image->numcmpts_) goto error; cmpt = image->cmpts_[cmptno]; if (x < 0 || x >= cmpt->width_ || y < 0 || y >= cmpt->height_ || width < 0 || height < 0 || x + width > cmpt->width_ || y + height > cmpt->height_) goto error; bufptr = buf; for (i = 0; i < height; ++i) { if (jas_stream_seek(cmpt->stream_, (cmpt->width_ * (y + i) + x) * cmpt->cps_, SEEK_SET) < 0) goto error; for (j = 0; j < width; ++j) { v = *bufptr++; if (putint(cmpt->stream_, cmpt->sgnd_, cmpt->prec_, v)) goto error; } } return 0; error: return -1; } int jas_image_sampcmpt(jas_image_t *image, int cmptno, int newcmptno, jas_image_coord_t ho, jas_image_coord_t vo, jas_image_coord_t hs, jas_image_coord_t vs, int sgnd, int prec) { jas_image_cmpt_t *oldcmpt; jas_image_cmpt_t *newcmpt; int width; int height; jas_image_coord_t tlx; jas_image_coord_t tly; jas_image_coord_t brx; jas_image_coord_t bry; int i; int j; jas_image_cmptparm_t cmptparm; jas_image_coord_t ax; jas_image_coord_t ay; jas_image_coord_t bx; jas_image_coord_t by; jas_image_coord_t d0; jas_image_coord_t d1; jas_image_coord_t d2; jas_image_coord_t d3; jas_image_coord_t oldx; jas_image_coord_t oldy; jas_image_coord_t x; jas_image_coord_t y; long v; jas_image_coord_t cmptbrx; jas_image_coord_t cmptbry; assert(cmptno >= 0 && cmptno < image->numcmpts_); oldcmpt = image->cmpts_[cmptno]; assert(oldcmpt->tlx_ == 0 && oldcmpt->tly_ == 0); jas_image_calcbbox2(image, &tlx, &tly, &brx, &bry); width = FLOORDIV(brx - ho + hs, hs); height = FLOORDIV(bry - vo + vs, vs); cmptparm.tlx = ho; cmptparm.tly = vo; cmptparm.hstep = hs; cmptparm.vstep = vs; cmptparm.width = width; cmptparm.height = height; cmptparm.prec = prec; cmptparm.sgnd = sgnd; if (jas_image_addcmpt(image, newcmptno, &cmptparm)) goto error; cmptbrx = oldcmpt->tlx_ + (oldcmpt->width_ - 1) * oldcmpt->hstep_; cmptbry = oldcmpt->tly_ + (oldcmpt->height_ - 1) * oldcmpt->vstep_; newcmpt = image->cmpts_[newcmptno]; jas_stream_rewind(newcmpt->stream_); for (i = 0; i < height; ++i) { y = newcmpt->tly_ + newcmpt->vstep_ * i; for (j = 0; j < width; ++j) { x = newcmpt->tlx_ + newcmpt->hstep_ * j; ax = downtomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; ay = downtomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; bx = uptomult(x - oldcmpt->tlx_, oldcmpt->hstep_) + oldcmpt->tlx_; if (bx > cmptbrx) bx = cmptbrx; by = uptomult(y - oldcmpt->tly_, oldcmpt->vstep_) + oldcmpt->tly_; if (by > cmptbry) by = cmptbry; d0 = (ax - x) * (ax - x) + (ay - y) * (ay - y); d1 = (bx - x) * (bx - x) + (ay - y) * (ay - y); d2 = (bx - x) * (bx - x) + (by - y) * (by - y); d3 = (ax - x) * (ax - x) + (by - y) * (by - y); if (d0 <= d1 && d0 <= d2 && d0 <= d3) { oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; } else if (d1 <= d0 && d1 <= d2 && d1 <= d3) { oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; oldy = (ay - oldcmpt->tly_) / oldcmpt->vstep_; } else if (d2 <= d0 && d2 <= d1 && d1 <= d3) { oldx = (bx - oldcmpt->tlx_) / oldcmpt->hstep_; oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; } else { oldx = (ax - oldcmpt->tlx_) / oldcmpt->hstep_; oldy = (by - oldcmpt->tly_) / oldcmpt->vstep_; } assert(oldx >= 0 && oldx < oldcmpt->width_ && oldy >= 0 && oldy < oldcmpt->height_); if (jas_stream_seek(oldcmpt->stream_, oldcmpt->cps_ * (oldy * oldcmpt->width_ + oldx), SEEK_SET) < 0) goto error; if (getint(oldcmpt->stream_, oldcmpt->sgnd_, oldcmpt->prec_, &v)) goto error; if (newcmpt->prec_ != oldcmpt->prec_ || newcmpt->sgnd_ != oldcmpt->sgnd_) { v = convert(v, oldcmpt->sgnd_, oldcmpt->prec_, newcmpt->sgnd_, newcmpt->prec_); } if (putint(newcmpt->stream_, newcmpt->sgnd_, newcmpt->prec_, v)) goto error; } } return 0; error: return -1; } int jas_image_ishomosamp(jas_image_t *image) { jas_image_coord_t hstep; jas_image_coord_t vstep; int result; int i; hstep = jas_image_cmpthstep(image, 0); vstep = jas_image_cmptvstep(image, 0); result = 1; for (i = 0; i < image->numcmpts_; ++i) { if (jas_image_cmpthstep(image, i) != hstep || jas_image_cmptvstep(image, i) != vstep) { result = 0; break; } } return result; } /* Note: This function defines a bounding box differently. */ static void jas_image_calcbbox2(jas_image_t *image, jas_image_coord_t *tlx, jas_image_coord_t *tly, jas_image_coord_t *brx, jas_image_coord_t *bry) { jas_image_cmpt_t *cmpt; jas_image_coord_t tmptlx; jas_image_coord_t tmptly; jas_image_coord_t tmpbrx; jas_image_coord_t tmpbry; jas_image_coord_t t; int i; if (image->numcmpts_ > 0) { cmpt = image->cmpts_[0]; tmptlx = cmpt->tlx_; tmptly = cmpt->tly_; tmpbrx = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1); tmpbry = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1); for (i = 0; i < image->numcmpts_; ++i) { cmpt = image->cmpts_[i]; if (cmpt->tlx_ < tmptlx) tmptlx = cmpt->tlx_; if (cmpt->tly_ < tmptly) tmptly = cmpt->tly_; t = cmpt->tlx_ + cmpt->hstep_ * (cmpt->width_ - 1); if (t > tmpbrx) tmpbrx = t; t = cmpt->tly_ + cmpt->vstep_ * (cmpt->height_ - 1); if (t > tmpbry) tmpbry = t; } } else { tmptlx = 0; tmptly = 0; tmpbrx = -1; tmpbry = -1; } *tlx = tmptlx; *tly = tmptly; *brx = tmpbrx; *bry = tmpbry; } static inline long decode_twos_comp(ulong c, int prec) { long result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); // NOTE: Is this correct? result = (c & ((1 << (prec - 1)) - 1)) - (c & (1 << (prec - 1))); return result; } static inline ulong encode_twos_comp(long n, int prec) { ulong result; assert(prec >= 2); jas_eprintf("warning: support for signed data is untested\n"); // NOTE: Is this correct? if (n < 0) { result = -n; result = (result ^ 0xffffffffUL) + 1; result &= (1 << prec) - 1; } else { result = n; } return result; } static int getint(jas_stream_t *in, int sgnd, int prec, long *val) { long v; int n; int c; assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); n = (prec + 7) / 8; v = 0; while (--n >= 0) { if ((c = jas_stream_getc(in)) == EOF) return -1; v = (v << 8) | c; } v &= ((1 << prec) - 1); if (sgnd) { *val = decode_twos_comp(v, prec); } else { *val = v; } return 0; } static int putint(jas_stream_t *out, int sgnd, int prec, long val) { int n; int c; bool s; ulong tmp; assert((!sgnd && prec >= 1) || (sgnd && prec >= 2)); if (sgnd) { val = encode_twos_comp(val, prec); } assert(val >= 0); val &= (1 << prec) - 1; n = (prec + 7) / 8; while (--n >= 0) { c = (val >> (n * 8)) & 0xff; if (jas_stream_putc(out, c) != c) return -1; } return 0; } static long convert(long val, int oldsgnd, int oldprec, int newsgnd, int newprec) { if (newsgnd != oldsgnd) { } if (newprec != oldprec) { if (newprec > oldprec) { val <<= newprec - oldprec; } else if (oldprec > newprec) { val >>= oldprec - newprec; } } return val; } static long downtomult(long x, long y) { assert(x >= 0); return (x / y) * y; } static long uptomult(long x, long y) { assert(x >= 0); return ((x + y - 1) / y) * y; } jas_image_t *jas_image_chclrspc(jas_image_t *image, jas_cmprof_t *outprof, int intent) { jas_image_t *inimage; int minhstep; int minvstep; int i; int j; int k; int n; int hstep; int vstep; int numinauxchans; int numoutauxchans; int numinclrchans; int numoutclrchans; int prec; jas_image_t *outimage; int cmpttype; int numoutchans; jas_cmprof_t *inprof; jas_cmprof_t *tmpprof; jas_image_cmptparm_t cmptparm; int width; int height; jas_cmxform_t *xform; jas_cmpixmap_t inpixmap; jas_cmpixmap_t outpixmap; jas_cmcmptfmt_t *incmptfmts; jas_cmcmptfmt_t *outcmptfmts; #if 0 jas_eprintf("IMAGE\n"); jas_image_dump(image, stderr); #endif outimage = 0; xform = 0; if (!(inimage = jas_image_copy(image))) goto error; image = 0; if (!jas_image_ishomosamp(inimage)) { minhstep = jas_image_cmpthstep(inimage, 0); minvstep = jas_image_cmptvstep(inimage, 0); for (i = 1; i < jas_image_numcmpts(inimage); ++i) { hstep = jas_image_cmpthstep(inimage, i); vstep = jas_image_cmptvstep(inimage, i); if (hstep < minhstep) { minhstep = hstep; } if (vstep < minvstep) { minvstep = vstep; } } n = jas_image_numcmpts(inimage); for (i = 0; i < n; ++i) { cmpttype = jas_image_cmpttype(inimage, i); if (jas_image_sampcmpt(inimage, i, i + 1, 0, 0, minhstep, minvstep, jas_image_cmptsgnd(inimage, i), jas_image_cmptprec(inimage, i))) { goto error; } jas_image_setcmpttype(inimage, i + 1, cmpttype); jas_image_delcmpt(inimage, i); } } width = jas_image_cmptwidth(inimage, 0); height = jas_image_cmptheight(inimage, 0); hstep = jas_image_cmpthstep(inimage, 0); vstep = jas_image_cmptvstep(inimage, 0); if (!(inprof = jas_image_cmprof(inimage))) { abort(); } numinclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(inprof)); numinauxchans = jas_image_numcmpts(inimage) - numinclrchans; numoutclrchans = jas_clrspc_numchans(jas_cmprof_clrspc(outprof)); numoutauxchans = 0; numoutchans = numoutclrchans + numoutauxchans; prec = 8; if (!(outimage = jas_image_create0())) { goto error; } /* Create a component for each of the colorants. */ for (i = 0; i < numoutclrchans; ++i) { cmptparm.tlx = 0; cmptparm.tly = 0; cmptparm.hstep = hstep; cmptparm.vstep = vstep; cmptparm.width = width; cmptparm.height = height; cmptparm.prec = prec; cmptparm.sgnd = 0; if (jas_image_addcmpt(outimage, -1, &cmptparm)) goto error; jas_image_setcmpttype(outimage, i, JAS_IMAGE_CT_COLOR(i)); } #if 0 /* Copy the auxiliary components without modification. */ for (i = 0; i < jas_image_numcmpts(inimage); ++i) { if (!ISCOLOR(jas_image_cmpttype(inimage, i))) { jas_image_copycmpt(outimage, -1, inimage, i); /* XXX - need to specify laydown of component on ref. grid */ } } #endif if (!(tmpprof = jas_cmprof_copy(outprof))) goto error; assert(!jas_image_cmprof(outimage)); jas_image_setcmprof(outimage, tmpprof); tmpprof = 0; jas_image_setclrspc(outimage, jas_cmprof_clrspc(outprof)); if (!(xform = jas_cmxform_create(inprof, outprof, 0, JAS_CMXFORM_OP_FWD, intent, 0))) { goto error; } inpixmap.numcmpts = numinclrchans; if (!(incmptfmts = jas_alloc2(numinclrchans, sizeof(jas_cmcmptfmt_t)))) { abort(); } inpixmap.cmptfmts = incmptfmts; for (i = 0; i < numinclrchans; ++i) { j = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(i)); assert(j >= 0); if (!(incmptfmts[i].buf = jas_alloc2(width, sizeof(long)))) { goto error; } incmptfmts[i].prec = jas_image_cmptprec(inimage, j); incmptfmts[i].sgnd = jas_image_cmptsgnd(inimage, j); incmptfmts[i].width = width; incmptfmts[i].height = 1; } outpixmap.numcmpts = numoutclrchans; if (!(outcmptfmts = jas_alloc2(numoutclrchans, sizeof(jas_cmcmptfmt_t)))) { abort(); } outpixmap.cmptfmts = outcmptfmts; for (i = 0; i < numoutclrchans; ++i) { j = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(i)); assert(j >= 0); if (!(outcmptfmts[i].buf = jas_alloc2(width, sizeof(long)))) goto error; outcmptfmts[i].prec = jas_image_cmptprec(outimage, j); outcmptfmts[i].sgnd = jas_image_cmptsgnd(outimage, j); outcmptfmts[i].width = width; outcmptfmts[i].height = 1; } for (i = 0; i < height; ++i) { for (j = 0; j < numinclrchans; ++j) { k = jas_image_getcmptbytype(inimage, JAS_IMAGE_CT_COLOR(j)); if (jas_image_readcmpt2(inimage, k, 0, i, width, 1, incmptfmts[j].buf)) goto error; } jas_cmxform_apply(xform, &inpixmap, &outpixmap); for (j = 0; j < numoutclrchans; ++j) { k = jas_image_getcmptbytype(outimage, JAS_IMAGE_CT_COLOR(j)); if (jas_image_writecmpt2(outimage, k, 0, i, width, 1, outcmptfmts[j].buf)) goto error; } } for (i = 0; i < numoutclrchans; ++i) { jas_free(outcmptfmts[i].buf); } jas_free(outcmptfmts); for (i = 0; i < numinclrchans; ++i) { jas_free(incmptfmts[i].buf); } jas_free(incmptfmts); jas_cmxform_destroy(xform); jas_image_destroy(inimage); #if 0 jas_eprintf("INIMAGE\n"); jas_image_dump(inimage, stderr); jas_eprintf("OUTIMAGE\n"); jas_image_dump(outimage, stderr); #endif return outimage; error: if (xform) jas_cmxform_destroy(xform); if (inimage) jas_image_destroy(inimage); if (outimage) jas_image_destroy(outimage); return 0; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_5400_1
crossvul-cpp_data_good_3027_0
/* * Performance events core code: * * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de> * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com> * * For licensing details see kernel-base/COPYING */ #include <linux/fs.h> #include <linux/mm.h> #include <linux/cpu.h> #include <linux/smp.h> #include <linux/idr.h> #include <linux/file.h> #include <linux/poll.h> #include <linux/slab.h> #include <linux/hash.h> #include <linux/tick.h> #include <linux/sysfs.h> #include <linux/dcache.h> #include <linux/percpu.h> #include <linux/ptrace.h> #include <linux/reboot.h> #include <linux/vmstat.h> #include <linux/device.h> #include <linux/export.h> #include <linux/vmalloc.h> #include <linux/hardirq.h> #include <linux/rculist.h> #include <linux/uaccess.h> #include <linux/syscalls.h> #include <linux/anon_inodes.h> #include <linux/kernel_stat.h> #include <linux/cgroup.h> #include <linux/perf_event.h> #include <linux/trace_events.h> #include <linux/hw_breakpoint.h> #include <linux/mm_types.h> #include <linux/module.h> #include <linux/mman.h> #include <linux/compat.h> #include <linux/bpf.h> #include <linux/filter.h> #include <linux/namei.h> #include <linux/parser.h> #include "internal.h" #include <asm/irq_regs.h> typedef int (*remote_function_f)(void *); struct remote_function_call { struct task_struct *p; remote_function_f func; void *info; int ret; }; static void remote_function(void *data) { struct remote_function_call *tfc = data; struct task_struct *p = tfc->p; if (p) { /* -EAGAIN */ if (task_cpu(p) != smp_processor_id()) return; /* * Now that we're on right CPU with IRQs disabled, we can test * if we hit the right task without races. */ tfc->ret = -ESRCH; /* No such (running) process */ if (p != current) return; } tfc->ret = tfc->func(tfc->info); } /** * task_function_call - call a function on the cpu on which a task runs * @p: the task to evaluate * @func: the function to be called * @info: the function call argument * * Calls the function @func when the task is currently running. This might * be on the current CPU, which just calls the function directly * * returns: @func return value, or * -ESRCH - when the process isn't running * -EAGAIN - when the process moved away */ static int task_function_call(struct task_struct *p, remote_function_f func, void *info) { struct remote_function_call data = { .p = p, .func = func, .info = info, .ret = -EAGAIN, }; int ret; do { ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1); if (!ret) ret = data.ret; } while (ret == -EAGAIN); return ret; } /** * cpu_function_call - call a function on the cpu * @func: the function to be called * @info: the function call argument * * Calls the function @func on the remote cpu. * * returns: @func return value or -ENXIO when the cpu is offline */ static int cpu_function_call(int cpu, remote_function_f func, void *info) { struct remote_function_call data = { .p = NULL, .func = func, .info = info, .ret = -ENXIO, /* No such CPU */ }; smp_call_function_single(cpu, remote_function, &data, 1); return data.ret; } static inline struct perf_cpu_context * __get_cpu_context(struct perf_event_context *ctx) { return this_cpu_ptr(ctx->pmu->pmu_cpu_context); } static void perf_ctx_lock(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { raw_spin_lock(&cpuctx->ctx.lock); if (ctx) raw_spin_lock(&ctx->lock); } static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { if (ctx) raw_spin_unlock(&ctx->lock); raw_spin_unlock(&cpuctx->ctx.lock); } #define TASK_TOMBSTONE ((void *)-1L) static bool is_kernel_event(struct perf_event *event) { return READ_ONCE(event->owner) == TASK_TOMBSTONE; } /* * On task ctx scheduling... * * When !ctx->nr_events a task context will not be scheduled. This means * we can disable the scheduler hooks (for performance) without leaving * pending task ctx state. * * This however results in two special cases: * * - removing the last event from a task ctx; this is relatively straight * forward and is done in __perf_remove_from_context. * * - adding the first event to a task ctx; this is tricky because we cannot * rely on ctx->is_active and therefore cannot use event_function_call(). * See perf_install_in_context(). * * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set. */ typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *, struct perf_event_context *, void *); struct event_function_struct { struct perf_event *event; event_f func; void *data; }; static int event_function(void *info) { struct event_function_struct *efs = info; struct perf_event *event = efs->event; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct perf_event_context *task_ctx = cpuctx->task_ctx; int ret = 0; WARN_ON_ONCE(!irqs_disabled()); perf_ctx_lock(cpuctx, task_ctx); /* * Since we do the IPI call without holding ctx->lock things can have * changed, double check we hit the task we set out to hit. */ if (ctx->task) { if (ctx->task != current) { ret = -ESRCH; goto unlock; } /* * We only use event_function_call() on established contexts, * and event_function() is only ever called when active (or * rather, we'll have bailed in task_function_call() or the * above ctx->task != current test), therefore we must have * ctx->is_active here. */ WARN_ON_ONCE(!ctx->is_active); /* * And since we have ctx->is_active, cpuctx->task_ctx must * match. */ WARN_ON_ONCE(task_ctx != ctx); } else { WARN_ON_ONCE(&cpuctx->ctx != ctx); } efs->func(event, cpuctx, ctx, efs->data); unlock: perf_ctx_unlock(cpuctx, task_ctx); return ret; } static void event_function_call(struct perf_event *event, event_f func, void *data) { struct perf_event_context *ctx = event->ctx; struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */ struct event_function_struct efs = { .event = event, .func = func, .data = data, }; if (!event->parent) { /* * If this is a !child event, we must hold ctx::mutex to * stabilize the the event->ctx relation. See * perf_event_ctx_lock(). */ lockdep_assert_held(&ctx->mutex); } if (!task) { cpu_function_call(event->cpu, event_function, &efs); return; } if (task == TASK_TOMBSTONE) return; again: if (!task_function_call(task, event_function, &efs)) return; raw_spin_lock_irq(&ctx->lock); /* * Reload the task pointer, it might have been changed by * a concurrent perf_event_context_sched_out(). */ task = ctx->task; if (task == TASK_TOMBSTONE) { raw_spin_unlock_irq(&ctx->lock); return; } if (ctx->is_active) { raw_spin_unlock_irq(&ctx->lock); goto again; } func(event, NULL, ctx, data); raw_spin_unlock_irq(&ctx->lock); } /* * Similar to event_function_call() + event_function(), but hard assumes IRQs * are already disabled and we're on the right CPU. */ static void event_function_local(struct perf_event *event, event_f func, void *data) { struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct task_struct *task = READ_ONCE(ctx->task); struct perf_event_context *task_ctx = NULL; WARN_ON_ONCE(!irqs_disabled()); if (task) { if (task == TASK_TOMBSTONE) return; task_ctx = ctx; } perf_ctx_lock(cpuctx, task_ctx); task = ctx->task; if (task == TASK_TOMBSTONE) goto unlock; if (task) { /* * We must be either inactive or active and the right task, * otherwise we're screwed, since we cannot IPI to somewhere * else. */ if (ctx->is_active) { if (WARN_ON_ONCE(task != current)) goto unlock; if (WARN_ON_ONCE(cpuctx->task_ctx != ctx)) goto unlock; } } else { WARN_ON_ONCE(&cpuctx->ctx != ctx); } func(event, cpuctx, ctx, data); unlock: perf_ctx_unlock(cpuctx, task_ctx); } #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ PERF_FLAG_FD_OUTPUT |\ PERF_FLAG_PID_CGROUP |\ PERF_FLAG_FD_CLOEXEC) /* * branch priv levels that need permission checks */ #define PERF_SAMPLE_BRANCH_PERM_PLM \ (PERF_SAMPLE_BRANCH_KERNEL |\ PERF_SAMPLE_BRANCH_HV) enum event_type_t { EVENT_FLEXIBLE = 0x1, EVENT_PINNED = 0x2, EVENT_TIME = 0x4, /* see ctx_resched() for details */ EVENT_CPU = 0x8, EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, }; /* * perf_sched_events : >0 events exist * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu */ static void perf_sched_delayed(struct work_struct *work); DEFINE_STATIC_KEY_FALSE(perf_sched_events); static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed); static DEFINE_MUTEX(perf_sched_mutex); static atomic_t perf_sched_count; static DEFINE_PER_CPU(atomic_t, perf_cgroup_events); static DEFINE_PER_CPU(int, perf_sched_cb_usages); static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events); static atomic_t nr_mmap_events __read_mostly; static atomic_t nr_comm_events __read_mostly; static atomic_t nr_task_events __read_mostly; static atomic_t nr_freq_events __read_mostly; static atomic_t nr_switch_events __read_mostly; static LIST_HEAD(pmus); static DEFINE_MUTEX(pmus_lock); static struct srcu_struct pmus_srcu; /* * perf event paranoia level: * -1 - not paranoid at all * 0 - disallow raw tracepoint access for unpriv * 1 - disallow cpu events for unpriv * 2 - disallow kernel profiling for unpriv */ int sysctl_perf_event_paranoid __read_mostly = 2; /* Minimum for 512 kiB + 1 user control page */ int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */ /* * max perf event sample rate */ #define DEFAULT_MAX_SAMPLE_RATE 100000 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) #define DEFAULT_CPU_TIME_MAX_PERCENT 25 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; static int perf_sample_allowed_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; static void update_perf_cpu_limits(void) { u64 tmp = perf_sample_period_ns; tmp *= sysctl_perf_cpu_time_max_percent; tmp = div_u64(tmp, 100); if (!tmp) tmp = 1; WRITE_ONCE(perf_sample_allowed_ns, tmp); } static int perf_rotate_context(struct perf_cpu_context *cpuctx); int perf_proc_update_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret || !write) return ret; /* * If throttling is disabled don't allow the write: */ if (sysctl_perf_cpu_time_max_percent == 100 || sysctl_perf_cpu_time_max_percent == 0) return -EINVAL; max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; update_perf_cpu_limits(); return 0; } int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (ret || !write) return ret; if (sysctl_perf_cpu_time_max_percent == 100 || sysctl_perf_cpu_time_max_percent == 0) { printk(KERN_WARNING "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); WRITE_ONCE(perf_sample_allowed_ns, 0); } else { update_perf_cpu_limits(); } return 0; } /* * perf samples are done in some very critical code paths (NMIs). * If they take too much CPU time, the system can lock up and not * get any real work done. This will drop the sample rate when * we detect that events are taking too long. */ #define NR_ACCUMULATED_SAMPLES 128 static DEFINE_PER_CPU(u64, running_sample_length); static u64 __report_avg; static u64 __report_allowed; static void perf_duration_warn(struct irq_work *w) { printk_ratelimited(KERN_INFO "perf: interrupt took too long (%lld > %lld), lowering " "kernel.perf_event_max_sample_rate to %d\n", __report_avg, __report_allowed, sysctl_perf_event_sample_rate); } static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); void perf_sample_event_took(u64 sample_len_ns) { u64 max_len = READ_ONCE(perf_sample_allowed_ns); u64 running_len; u64 avg_len; u32 max; if (max_len == 0) return; /* Decay the counter by 1 average sample. */ running_len = __this_cpu_read(running_sample_length); running_len -= running_len/NR_ACCUMULATED_SAMPLES; running_len += sample_len_ns; __this_cpu_write(running_sample_length, running_len); /* * Note: this will be biased artifically low until we have * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us * from having to maintain a count. */ avg_len = running_len/NR_ACCUMULATED_SAMPLES; if (avg_len <= max_len) return; __report_avg = avg_len; __report_allowed = max_len; /* * Compute a throttle threshold 25% below the current duration. */ avg_len += avg_len / 4; max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent; if (avg_len < max) max /= (u32)avg_len; else max = 1; WRITE_ONCE(perf_sample_allowed_ns, avg_len); WRITE_ONCE(max_samples_per_tick, max); sysctl_perf_event_sample_rate = max * HZ; perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; if (!irq_work_queue(&perf_duration_work)) { early_printk("perf: interrupt took too long (%lld > %lld), lowering " "kernel.perf_event_max_sample_rate to %d\n", __report_avg, __report_allowed, sysctl_perf_event_sample_rate); } } static atomic64_t perf_event_id; static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, enum event_type_t event_type); static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task); static void update_context_time(struct perf_event_context *ctx); static u64 perf_event_time(struct perf_event *event); void __weak perf_event_print_debug(void) { } extern __weak const char *perf_pmu_name(void) { return "pmu"; } static inline u64 perf_clock(void) { return local_clock(); } static inline u64 perf_event_clock(struct perf_event *event) { return event->clock(); } #ifdef CONFIG_CGROUP_PERF static inline bool perf_cgroup_match(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); /* @event doesn't care about cgroup */ if (!event->cgrp) return true; /* wants specific cgroup scope but @cpuctx isn't associated with any */ if (!cpuctx->cgrp) return false; /* * Cgroup scoping is recursive. An event enabled for a cgroup is * also enabled for all its descendant cgroups. If @cpuctx's * cgroup is a descendant of @event's (the test covers identity * case), it's a match. */ return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, event->cgrp->css.cgroup); } static inline void perf_detach_cgroup(struct perf_event *event) { css_put(&event->cgrp->css); event->cgrp = NULL; } static inline int is_cgroup_event(struct perf_event *event) { return event->cgrp != NULL; } static inline u64 perf_cgroup_event_time(struct perf_event *event) { struct perf_cgroup_info *t; t = per_cpu_ptr(event->cgrp->info, event->cpu); return t->time; } static inline void __update_cgrp_time(struct perf_cgroup *cgrp) { struct perf_cgroup_info *info; u64 now; now = perf_clock(); info = this_cpu_ptr(cgrp->info); info->time += now - info->timestamp; info->timestamp = now; } static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) { struct perf_cgroup *cgrp_out = cpuctx->cgrp; if (cgrp_out) __update_cgrp_time(cgrp_out); } static inline void update_cgrp_time_from_event(struct perf_event *event) { struct perf_cgroup *cgrp; /* * ensure we access cgroup data only when needed and * when we know the cgroup is pinned (css_get) */ if (!is_cgroup_event(event)) return; cgrp = perf_cgroup_from_task(current, event->ctx); /* * Do not update time when cgroup is not active */ if (cgrp == event->cgrp) __update_cgrp_time(event->cgrp); } static inline void perf_cgroup_set_timestamp(struct task_struct *task, struct perf_event_context *ctx) { struct perf_cgroup *cgrp; struct perf_cgroup_info *info; /* * ctx->lock held by caller * ensure we do not access cgroup data * unless we have the cgroup pinned (css_get) */ if (!task || !ctx->nr_cgroups) return; cgrp = perf_cgroup_from_task(task, ctx); info = this_cpu_ptr(cgrp->info); info->timestamp = ctx->timestamp; } static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list); #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */ #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */ /* * reschedule events based on the cgroup constraint of task. * * mode SWOUT : schedule out everything * mode SWIN : schedule in based on cgroup for next */ static void perf_cgroup_switch(struct task_struct *task, int mode) { struct perf_cpu_context *cpuctx; struct list_head *list; unsigned long flags; /* * Disable interrupts and preemption to avoid this CPU's * cgrp_cpuctx_entry to change under us. */ local_irq_save(flags); list = this_cpu_ptr(&cgrp_cpuctx_list); list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) { WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0); perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(cpuctx->ctx.pmu); if (mode & PERF_CGROUP_SWOUT) { cpu_ctx_sched_out(cpuctx, EVENT_ALL); /* * must not be done before ctxswout due * to event_filter_match() in event_sched_out() */ cpuctx->cgrp = NULL; } if (mode & PERF_CGROUP_SWIN) { WARN_ON_ONCE(cpuctx->cgrp); /* * set cgrp before ctxsw in to allow * event_filter_match() to not have to pass * task around * we pass the cpuctx->ctx to perf_cgroup_from_task() * because cgorup events are only per-cpu */ cpuctx->cgrp = perf_cgroup_from_task(task, &cpuctx->ctx); cpu_ctx_sched_in(cpuctx, EVENT_ALL, task); } perf_pmu_enable(cpuctx->ctx.pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); } local_irq_restore(flags); } static inline void perf_cgroup_sched_out(struct task_struct *task, struct task_struct *next) { struct perf_cgroup *cgrp1; struct perf_cgroup *cgrp2 = NULL; rcu_read_lock(); /* * we come here when we know perf_cgroup_events > 0 * we do not need to pass the ctx here because we know * we are holding the rcu lock */ cgrp1 = perf_cgroup_from_task(task, NULL); cgrp2 = perf_cgroup_from_task(next, NULL); /* * only schedule out current cgroup events if we know * that we are switching to a different cgroup. Otherwise, * do no touch the cgroup events. */ if (cgrp1 != cgrp2) perf_cgroup_switch(task, PERF_CGROUP_SWOUT); rcu_read_unlock(); } static inline void perf_cgroup_sched_in(struct task_struct *prev, struct task_struct *task) { struct perf_cgroup *cgrp1; struct perf_cgroup *cgrp2 = NULL; rcu_read_lock(); /* * we come here when we know perf_cgroup_events > 0 * we do not need to pass the ctx here because we know * we are holding the rcu lock */ cgrp1 = perf_cgroup_from_task(task, NULL); cgrp2 = perf_cgroup_from_task(prev, NULL); /* * only need to schedule in cgroup events if we are changing * cgroup during ctxsw. Cgroup events were not scheduled * out of ctxsw out if that was not the case. */ if (cgrp1 != cgrp2) perf_cgroup_switch(task, PERF_CGROUP_SWIN); rcu_read_unlock(); } static inline int perf_cgroup_connect(int fd, struct perf_event *event, struct perf_event_attr *attr, struct perf_event *group_leader) { struct perf_cgroup *cgrp; struct cgroup_subsys_state *css; struct fd f = fdget(fd); int ret = 0; if (!f.file) return -EBADF; css = css_tryget_online_from_dir(f.file->f_path.dentry, &perf_event_cgrp_subsys); if (IS_ERR(css)) { ret = PTR_ERR(css); goto out; } cgrp = container_of(css, struct perf_cgroup, css); event->cgrp = cgrp; /* * all events in a group must monitor * the same cgroup because a task belongs * to only one perf cgroup at a time */ if (group_leader && group_leader->cgrp != cgrp) { perf_detach_cgroup(event); ret = -EINVAL; } out: fdput(f); return ret; } static inline void perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) { struct perf_cgroup_info *t; t = per_cpu_ptr(event->cgrp->info, event->cpu); event->shadow_ctx_time = now - t->timestamp; } static inline void perf_cgroup_defer_enabled(struct perf_event *event) { /* * when the current task's perf cgroup does not match * the event's, we need to remember to call the * perf_mark_enable() function the first time a task with * a matching perf cgroup is scheduled in. */ if (is_cgroup_event(event) && !perf_cgroup_match(event)) event->cgrp_defer_enabled = 1; } static inline void perf_cgroup_mark_enabled(struct perf_event *event, struct perf_event_context *ctx) { struct perf_event *sub; u64 tstamp = perf_event_time(event); if (!event->cgrp_defer_enabled) return; event->cgrp_defer_enabled = 0; event->tstamp_enabled = tstamp - event->total_time_enabled; list_for_each_entry(sub, &event->sibling_list, group_entry) { if (sub->state >= PERF_EVENT_STATE_INACTIVE) { sub->tstamp_enabled = tstamp - sub->total_time_enabled; sub->cgrp_defer_enabled = 0; } } } /* * Update cpuctx->cgrp so that it is set when first cgroup event is added and * cleared when last cgroup event is removed. */ static inline void list_update_cgroup_event(struct perf_event *event, struct perf_event_context *ctx, bool add) { struct perf_cpu_context *cpuctx; struct list_head *cpuctx_entry; if (!is_cgroup_event(event)) return; if (add && ctx->nr_cgroups++) return; else if (!add && --ctx->nr_cgroups) return; /* * Because cgroup events are always per-cpu events, * this will always be called from the right CPU. */ cpuctx = __get_cpu_context(ctx); cpuctx_entry = &cpuctx->cgrp_cpuctx_entry; /* cpuctx->cgrp is NULL unless a cgroup event is active in this CPU .*/ if (add) { list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list)); if (perf_cgroup_from_task(current, ctx) == event->cgrp) cpuctx->cgrp = event->cgrp; } else { list_del(cpuctx_entry); cpuctx->cgrp = NULL; } } #else /* !CONFIG_CGROUP_PERF */ static inline bool perf_cgroup_match(struct perf_event *event) { return true; } static inline void perf_detach_cgroup(struct perf_event *event) {} static inline int is_cgroup_event(struct perf_event *event) { return 0; } static inline u64 perf_cgroup_event_cgrp_time(struct perf_event *event) { return 0; } static inline void update_cgrp_time_from_event(struct perf_event *event) { } static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) { } static inline void perf_cgroup_sched_out(struct task_struct *task, struct task_struct *next) { } static inline void perf_cgroup_sched_in(struct task_struct *prev, struct task_struct *task) { } static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, struct perf_event_attr *attr, struct perf_event *group_leader) { return -EINVAL; } static inline void perf_cgroup_set_timestamp(struct task_struct *task, struct perf_event_context *ctx) { } void perf_cgroup_switch(struct task_struct *task, struct task_struct *next) { } static inline void perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) { } static inline u64 perf_cgroup_event_time(struct perf_event *event) { return 0; } static inline void perf_cgroup_defer_enabled(struct perf_event *event) { } static inline void perf_cgroup_mark_enabled(struct perf_event *event, struct perf_event_context *ctx) { } static inline void list_update_cgroup_event(struct perf_event *event, struct perf_event_context *ctx, bool add) { } #endif /* * set default to be dependent on timer tick just * like original code */ #define PERF_CPU_HRTIMER (1000 / HZ) /* * function must be called with interrupts disbled */ static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr) { struct perf_cpu_context *cpuctx; int rotations = 0; WARN_ON(!irqs_disabled()); cpuctx = container_of(hr, struct perf_cpu_context, hrtimer); rotations = perf_rotate_context(cpuctx); raw_spin_lock(&cpuctx->hrtimer_lock); if (rotations) hrtimer_forward_now(hr, cpuctx->hrtimer_interval); else cpuctx->hrtimer_active = 0; raw_spin_unlock(&cpuctx->hrtimer_lock); return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART; } static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu) { struct hrtimer *timer = &cpuctx->hrtimer; struct pmu *pmu = cpuctx->ctx.pmu; u64 interval; /* no multiplexing needed for SW PMU */ if (pmu->task_ctx_nr == perf_sw_context) return; /* * check default is sane, if not set then force to * default interval (1/tick) */ interval = pmu->hrtimer_interval_ms; if (interval < 1) interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval); raw_spin_lock_init(&cpuctx->hrtimer_lock); hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED); timer->function = perf_mux_hrtimer_handler; } static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx) { struct hrtimer *timer = &cpuctx->hrtimer; struct pmu *pmu = cpuctx->ctx.pmu; unsigned long flags; /* not for SW PMU */ if (pmu->task_ctx_nr == perf_sw_context) return 0; raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags); if (!cpuctx->hrtimer_active) { cpuctx->hrtimer_active = 1; hrtimer_forward_now(timer, cpuctx->hrtimer_interval); hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED); } raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags); return 0; } void perf_pmu_disable(struct pmu *pmu) { int *count = this_cpu_ptr(pmu->pmu_disable_count); if (!(*count)++) pmu->pmu_disable(pmu); } void perf_pmu_enable(struct pmu *pmu) { int *count = this_cpu_ptr(pmu->pmu_disable_count); if (!--(*count)) pmu->pmu_enable(pmu); } static DEFINE_PER_CPU(struct list_head, active_ctx_list); /* * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and * perf_event_task_tick() are fully serialized because they're strictly cpu * affine and perf_event_ctx{activate,deactivate} are called with IRQs * disabled, while perf_event_task_tick is called from IRQ context. */ static void perf_event_ctx_activate(struct perf_event_context *ctx) { struct list_head *head = this_cpu_ptr(&active_ctx_list); WARN_ON(!irqs_disabled()); WARN_ON(!list_empty(&ctx->active_ctx_list)); list_add(&ctx->active_ctx_list, head); } static void perf_event_ctx_deactivate(struct perf_event_context *ctx) { WARN_ON(!irqs_disabled()); WARN_ON(list_empty(&ctx->active_ctx_list)); list_del_init(&ctx->active_ctx_list); } static void get_ctx(struct perf_event_context *ctx) { WARN_ON(!atomic_inc_not_zero(&ctx->refcount)); } static void free_ctx(struct rcu_head *head) { struct perf_event_context *ctx; ctx = container_of(head, struct perf_event_context, rcu_head); kfree(ctx->task_ctx_data); kfree(ctx); } static void put_ctx(struct perf_event_context *ctx) { if (atomic_dec_and_test(&ctx->refcount)) { if (ctx->parent_ctx) put_ctx(ctx->parent_ctx); if (ctx->task && ctx->task != TASK_TOMBSTONE) put_task_struct(ctx->task); call_rcu(&ctx->rcu_head, free_ctx); } } /* * Because of perf_event::ctx migration in sys_perf_event_open::move_group and * perf_pmu_migrate_context() we need some magic. * * Those places that change perf_event::ctx will hold both * perf_event_ctx::mutex of the 'old' and 'new' ctx value. * * Lock ordering is by mutex address. There are two other sites where * perf_event_context::mutex nests and those are: * * - perf_event_exit_task_context() [ child , 0 ] * perf_event_exit_event() * put_event() [ parent, 1 ] * * - perf_event_init_context() [ parent, 0 ] * inherit_task_group() * inherit_group() * inherit_event() * perf_event_alloc() * perf_init_event() * perf_try_init_event() [ child , 1 ] * * While it appears there is an obvious deadlock here -- the parent and child * nesting levels are inverted between the two. This is in fact safe because * life-time rules separate them. That is an exiting task cannot fork, and a * spawning task cannot (yet) exit. * * But remember that that these are parent<->child context relations, and * migration does not affect children, therefore these two orderings should not * interact. * * The change in perf_event::ctx does not affect children (as claimed above) * because the sys_perf_event_open() case will install a new event and break * the ctx parent<->child relation, and perf_pmu_migrate_context() is only * concerned with cpuctx and that doesn't have children. * * The places that change perf_event::ctx will issue: * * perf_remove_from_context(); * synchronize_rcu(); * perf_install_in_context(); * * to affect the change. The remove_from_context() + synchronize_rcu() should * quiesce the event, after which we can install it in the new location. This * means that only external vectors (perf_fops, prctl) can perturb the event * while in transit. Therefore all such accessors should also acquire * perf_event_context::mutex to serialize against this. * * However; because event->ctx can change while we're waiting to acquire * ctx->mutex we must be careful and use the below perf_event_ctx_lock() * function. * * Lock order: * cred_guard_mutex * task_struct::perf_event_mutex * perf_event_context::mutex * perf_event::child_mutex; * perf_event_context::lock * perf_event::mmap_mutex * mmap_sem */ static struct perf_event_context * perf_event_ctx_lock_nested(struct perf_event *event, int nesting) { struct perf_event_context *ctx; again: rcu_read_lock(); ctx = ACCESS_ONCE(event->ctx); if (!atomic_inc_not_zero(&ctx->refcount)) { rcu_read_unlock(); goto again; } rcu_read_unlock(); mutex_lock_nested(&ctx->mutex, nesting); if (event->ctx != ctx) { mutex_unlock(&ctx->mutex); put_ctx(ctx); goto again; } return ctx; } static inline struct perf_event_context * perf_event_ctx_lock(struct perf_event *event) { return perf_event_ctx_lock_nested(event, 0); } static void perf_event_ctx_unlock(struct perf_event *event, struct perf_event_context *ctx) { mutex_unlock(&ctx->mutex); put_ctx(ctx); } /* * This must be done under the ctx->lock, such as to serialize against * context_equiv(), therefore we cannot call put_ctx() since that might end up * calling scheduler related locks and ctx->lock nests inside those. */ static __must_check struct perf_event_context * unclone_ctx(struct perf_event_context *ctx) { struct perf_event_context *parent_ctx = ctx->parent_ctx; lockdep_assert_held(&ctx->lock); if (parent_ctx) ctx->parent_ctx = NULL; ctx->generation++; return parent_ctx; } static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) { /* * only top level events have the pid namespace they were created in */ if (event->parent) event = event->parent; return task_tgid_nr_ns(p, event->ns); } static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) { /* * only top level events have the pid namespace they were created in */ if (event->parent) event = event->parent; return task_pid_nr_ns(p, event->ns); } /* * If we inherit events we want to return the parent event id * to userspace. */ static u64 primary_event_id(struct perf_event *event) { u64 id = event->id; if (event->parent) id = event->parent->id; return id; } /* * Get the perf_event_context for a task and lock it. * * This has to cope with with the fact that until it is locked, * the context could get moved to another task. */ static struct perf_event_context * perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags) { struct perf_event_context *ctx; retry: /* * One of the few rules of preemptible RCU is that one cannot do * rcu_read_unlock() while holding a scheduler (or nested) lock when * part of the read side critical section was irqs-enabled -- see * rcu_read_unlock_special(). * * Since ctx->lock nests under rq->lock we must ensure the entire read * side critical section has interrupts disabled. */ local_irq_save(*flags); rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[ctxn]); if (ctx) { /* * If this context is a clone of another, it might * get swapped for another underneath us by * perf_event_task_sched_out, though the * rcu_read_lock() protects us from any context * getting freed. Lock the context and check if it * got swapped before we could get the lock, and retry * if so. If we locked the right context, then it * can't get swapped on us any more. */ raw_spin_lock(&ctx->lock); if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) { raw_spin_unlock(&ctx->lock); rcu_read_unlock(); local_irq_restore(*flags); goto retry; } if (ctx->task == TASK_TOMBSTONE || !atomic_inc_not_zero(&ctx->refcount)) { raw_spin_unlock(&ctx->lock); ctx = NULL; } else { WARN_ON_ONCE(ctx->task != task); } } rcu_read_unlock(); if (!ctx) local_irq_restore(*flags); return ctx; } /* * Get the context for a task and increment its pin_count so it * can't get swapped to another task. This also increments its * reference count so that the context can't get freed. */ static struct perf_event_context * perf_pin_task_context(struct task_struct *task, int ctxn) { struct perf_event_context *ctx; unsigned long flags; ctx = perf_lock_task_context(task, ctxn, &flags); if (ctx) { ++ctx->pin_count; raw_spin_unlock_irqrestore(&ctx->lock, flags); } return ctx; } static void perf_unpin_context(struct perf_event_context *ctx) { unsigned long flags; raw_spin_lock_irqsave(&ctx->lock, flags); --ctx->pin_count; raw_spin_unlock_irqrestore(&ctx->lock, flags); } /* * Update the record of the current time in a context. */ static void update_context_time(struct perf_event_context *ctx) { u64 now = perf_clock(); ctx->time += now - ctx->timestamp; ctx->timestamp = now; } static u64 perf_event_time(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; if (is_cgroup_event(event)) return perf_cgroup_event_time(event); return ctx ? ctx->time : 0; } /* * Update the total_time_enabled and total_time_running fields for a event. */ static void update_event_times(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; u64 run_end; lockdep_assert_held(&ctx->lock); if (event->state < PERF_EVENT_STATE_INACTIVE || event->group_leader->state < PERF_EVENT_STATE_INACTIVE) return; /* * in cgroup mode, time_enabled represents * the time the event was enabled AND active * tasks were in the monitored cgroup. This is * independent of the activity of the context as * there may be a mix of cgroup and non-cgroup events. * * That is why we treat cgroup events differently * here. */ if (is_cgroup_event(event)) run_end = perf_cgroup_event_time(event); else if (ctx->is_active) run_end = ctx->time; else run_end = event->tstamp_stopped; event->total_time_enabled = run_end - event->tstamp_enabled; if (event->state == PERF_EVENT_STATE_INACTIVE) run_end = event->tstamp_stopped; else run_end = perf_event_time(event); event->total_time_running = run_end - event->tstamp_running; } /* * Update total_time_enabled and total_time_running for all events in a group. */ static void update_group_times(struct perf_event *leader) { struct perf_event *event; update_event_times(leader); list_for_each_entry(event, &leader->sibling_list, group_entry) update_event_times(event); } static enum event_type_t get_event_type(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; enum event_type_t event_type; lockdep_assert_held(&ctx->lock); event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE; if (!ctx->task) event_type |= EVENT_CPU; return event_type; } static struct list_head * ctx_group_list(struct perf_event *event, struct perf_event_context *ctx) { if (event->attr.pinned) return &ctx->pinned_groups; else return &ctx->flexible_groups; } /* * Add a event from the lists for its context. * Must be called with ctx->mutex and ctx->lock held. */ static void list_add_event(struct perf_event *event, struct perf_event_context *ctx) { lockdep_assert_held(&ctx->lock); WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); event->attach_state |= PERF_ATTACH_CONTEXT; /* * If we're a stand alone event or group leader, we go to the context * list, group events are kept attached to the group so that * perf_group_detach can, at all times, locate all siblings. */ if (event->group_leader == event) { struct list_head *list; event->group_caps = event->event_caps; list = ctx_group_list(event, ctx); list_add_tail(&event->group_entry, list); } list_update_cgroup_event(event, ctx, true); list_add_rcu(&event->event_entry, &ctx->event_list); ctx->nr_events++; if (event->attr.inherit_stat) ctx->nr_stat++; ctx->generation++; } /* * Initialize event state based on the perf_event_attr::disabled. */ static inline void perf_event__state_init(struct perf_event *event) { event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : PERF_EVENT_STATE_INACTIVE; } static void __perf_event_read_size(struct perf_event *event, int nr_siblings) { int entry = sizeof(u64); /* value */ int size = 0; int nr = 1; if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) size += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) size += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_ID) entry += sizeof(u64); if (event->attr.read_format & PERF_FORMAT_GROUP) { nr += nr_siblings; size += sizeof(u64); } size += entry * nr; event->read_size = size; } static void __perf_event_header_size(struct perf_event *event, u64 sample_type) { struct perf_sample_data *data; u16 size = 0; if (sample_type & PERF_SAMPLE_IP) size += sizeof(data->ip); if (sample_type & PERF_SAMPLE_ADDR) size += sizeof(data->addr); if (sample_type & PERF_SAMPLE_PERIOD) size += sizeof(data->period); if (sample_type & PERF_SAMPLE_WEIGHT) size += sizeof(data->weight); if (sample_type & PERF_SAMPLE_READ) size += event->read_size; if (sample_type & PERF_SAMPLE_DATA_SRC) size += sizeof(data->data_src.val); if (sample_type & PERF_SAMPLE_TRANSACTION) size += sizeof(data->txn); event->header_size = size; } /* * Called at perf_event creation and when events are attached/detached from a * group. */ static void perf_event__header_size(struct perf_event *event) { __perf_event_read_size(event, event->group_leader->nr_siblings); __perf_event_header_size(event, event->attr.sample_type); } static void perf_event__id_header_size(struct perf_event *event) { struct perf_sample_data *data; u64 sample_type = event->attr.sample_type; u16 size = 0; if (sample_type & PERF_SAMPLE_TID) size += sizeof(data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) size += sizeof(data->time); if (sample_type & PERF_SAMPLE_IDENTIFIER) size += sizeof(data->id); if (sample_type & PERF_SAMPLE_ID) size += sizeof(data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) size += sizeof(data->stream_id); if (sample_type & PERF_SAMPLE_CPU) size += sizeof(data->cpu_entry); event->id_header_size = size; } static bool perf_event_validate_size(struct perf_event *event) { /* * The values computed here will be over-written when we actually * attach the event. */ __perf_event_read_size(event, event->group_leader->nr_siblings + 1); __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ); perf_event__id_header_size(event); /* * Sum the lot; should not exceed the 64k limit we have on records. * Conservative limit to allow for callchains and other variable fields. */ if (event->read_size + event->header_size + event->id_header_size + sizeof(struct perf_event_header) >= 16*1024) return false; return true; } static void perf_group_attach(struct perf_event *event) { struct perf_event *group_leader = event->group_leader, *pos; lockdep_assert_held(&event->ctx->lock); /* * We can have double attach due to group movement in perf_event_open. */ if (event->attach_state & PERF_ATTACH_GROUP) return; event->attach_state |= PERF_ATTACH_GROUP; if (group_leader == event) return; WARN_ON_ONCE(group_leader->ctx != event->ctx); group_leader->group_caps &= event->event_caps; list_add_tail(&event->group_entry, &group_leader->sibling_list); group_leader->nr_siblings++; perf_event__header_size(group_leader); list_for_each_entry(pos, &group_leader->sibling_list, group_entry) perf_event__header_size(pos); } /* * Remove a event from the lists for its context. * Must be called with ctx->mutex and ctx->lock held. */ static void list_del_event(struct perf_event *event, struct perf_event_context *ctx) { WARN_ON_ONCE(event->ctx != ctx); lockdep_assert_held(&ctx->lock); /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_CONTEXT)) return; event->attach_state &= ~PERF_ATTACH_CONTEXT; list_update_cgroup_event(event, ctx, false); ctx->nr_events--; if (event->attr.inherit_stat) ctx->nr_stat--; list_del_rcu(&event->event_entry); if (event->group_leader == event) list_del_init(&event->group_entry); update_group_times(event); /* * If event was in error state, then keep it * that way, otherwise bogus counts will be * returned on read(). The only way to get out * of error state is by explicit re-enabling * of the event */ if (event->state > PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_OFF; ctx->generation++; } static void perf_group_detach(struct perf_event *event) { struct perf_event *sibling, *tmp; struct list_head *list = NULL; lockdep_assert_held(&event->ctx->lock); /* * We can have double detach due to exit/hot-unplug + close. */ if (!(event->attach_state & PERF_ATTACH_GROUP)) return; event->attach_state &= ~PERF_ATTACH_GROUP; /* * If this is a sibling, remove it from its group. */ if (event->group_leader != event) { list_del_init(&event->group_entry); event->group_leader->nr_siblings--; goto out; } if (!list_empty(&event->group_entry)) list = &event->group_entry; /* * If this was a group event with sibling events then * upgrade the siblings to singleton events by adding them * to whatever list we are on. */ list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) { if (list) list_move_tail(&sibling->group_entry, list); sibling->group_leader = sibling; /* Inherit group flags from the previous leader */ sibling->group_caps = event->group_caps; WARN_ON_ONCE(sibling->ctx != event->ctx); } out: perf_event__header_size(event->group_leader); list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry) perf_event__header_size(tmp); } static bool is_orphaned_event(struct perf_event *event) { return event->state == PERF_EVENT_STATE_DEAD; } static inline int __pmu_filter_match(struct perf_event *event) { struct pmu *pmu = event->pmu; return pmu->filter_match ? pmu->filter_match(event) : 1; } /* * Check whether we should attempt to schedule an event group based on * PMU-specific filtering. An event group can consist of HW and SW events, * potentially with a SW leader, so we must check all the filters, to * determine whether a group is schedulable: */ static inline int pmu_filter_match(struct perf_event *event) { struct perf_event *child; if (!__pmu_filter_match(event)) return 0; list_for_each_entry(child, &event->sibling_list, group_entry) { if (!__pmu_filter_match(child)) return 0; } return 1; } static inline int event_filter_match(struct perf_event *event) { return (event->cpu == -1 || event->cpu == smp_processor_id()) && perf_cgroup_match(event) && pmu_filter_match(event); } static void event_sched_out(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); u64 delta; WARN_ON_ONCE(event->ctx != ctx); lockdep_assert_held(&ctx->lock); /* * An event which could not be activated because of * filter mismatch still needs to have its timings * maintained, otherwise bogus information is return * via read() for time_enabled, time_running: */ if (event->state == PERF_EVENT_STATE_INACTIVE && !event_filter_match(event)) { delta = tstamp - event->tstamp_stopped; event->tstamp_running += delta; event->tstamp_stopped = tstamp; } if (event->state != PERF_EVENT_STATE_ACTIVE) return; perf_pmu_disable(event->pmu); event->tstamp_stopped = tstamp; event->pmu->del(event, 0); event->oncpu = -1; event->state = PERF_EVENT_STATE_INACTIVE; if (event->pending_disable) { event->pending_disable = 0; event->state = PERF_EVENT_STATE_OFF; } if (!is_software_event(event)) cpuctx->active_oncpu--; if (!--ctx->nr_active) perf_event_ctx_deactivate(ctx); if (event->attr.freq && event->attr.sample_freq) ctx->nr_freq--; if (event->attr.exclusive || !cpuctx->active_oncpu) cpuctx->exclusive = 0; perf_pmu_enable(event->pmu); } static void group_sched_out(struct perf_event *group_event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { struct perf_event *event; int state = group_event->state; perf_pmu_disable(ctx->pmu); event_sched_out(group_event, cpuctx, ctx); /* * Schedule out siblings (if any): */ list_for_each_entry(event, &group_event->sibling_list, group_entry) event_sched_out(event, cpuctx, ctx); perf_pmu_enable(ctx->pmu); if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive) cpuctx->exclusive = 0; } #define DETACH_GROUP 0x01UL /* * Cross CPU call to remove a performance event * * We disable the event on the hardware level first. After that we * remove it from the context list. */ static void __perf_remove_from_context(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, void *info) { unsigned long flags = (unsigned long)info; event_sched_out(event, cpuctx, ctx); if (flags & DETACH_GROUP) perf_group_detach(event); list_del_event(event, ctx); if (!ctx->nr_events && ctx->is_active) { ctx->is_active = 0; if (ctx->task) { WARN_ON_ONCE(cpuctx->task_ctx != ctx); cpuctx->task_ctx = NULL; } } } /* * Remove the event from a task's (or a CPU's) list of events. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This is OK when called from perf_release since * that only calls us on the top-level context, which can't be a clone. * When called from perf_event_exit_task, it's OK because the * context has been detached from its task. */ static void perf_remove_from_context(struct perf_event *event, unsigned long flags) { struct perf_event_context *ctx = event->ctx; lockdep_assert_held(&ctx->mutex); event_function_call(event, __perf_remove_from_context, (void *)flags); /* * The above event_function_call() can NO-OP when it hits * TASK_TOMBSTONE. In that case we must already have been detached * from the context (by perf_event_exit_event()) but the grouping * might still be in-tact. */ WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); if ((flags & DETACH_GROUP) && (event->attach_state & PERF_ATTACH_GROUP)) { /* * Since in that case we cannot possibly be scheduled, simply * detach now. */ raw_spin_lock_irq(&ctx->lock); perf_group_detach(event); raw_spin_unlock_irq(&ctx->lock); } } /* * Cross CPU call to disable a performance event */ static void __perf_event_disable(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, void *info) { if (event->state < PERF_EVENT_STATE_INACTIVE) return; update_context_time(ctx); update_cgrp_time_from_event(event); update_group_times(event); if (event == event->group_leader) group_sched_out(event, cpuctx, ctx); else event_sched_out(event, cpuctx, ctx); event->state = PERF_EVENT_STATE_OFF; } /* * Disable a event. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This condition is satisifed when called through * perf_event_for_each_child or perf_event_for_each because they * hold the top-level event's child_mutex, so any descendant that * goes to exit will block in perf_event_exit_event(). * * When called from perf_pending_event it's OK because event->ctx * is the current context on this CPU and preemption is disabled, * hence we can't get into perf_event_task_sched_out for this context. */ static void _perf_event_disable(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; raw_spin_lock_irq(&ctx->lock); if (event->state <= PERF_EVENT_STATE_OFF) { raw_spin_unlock_irq(&ctx->lock); return; } raw_spin_unlock_irq(&ctx->lock); event_function_call(event, __perf_event_disable, NULL); } void perf_event_disable_local(struct perf_event *event) { event_function_local(event, __perf_event_disable, NULL); } /* * Strictly speaking kernel users cannot create groups and therefore this * interface does not need the perf_event_ctx_lock() magic. */ void perf_event_disable(struct perf_event *event) { struct perf_event_context *ctx; ctx = perf_event_ctx_lock(event); _perf_event_disable(event); perf_event_ctx_unlock(event, ctx); } EXPORT_SYMBOL_GPL(perf_event_disable); void perf_event_disable_inatomic(struct perf_event *event) { event->pending_disable = 1; irq_work_queue(&event->pending); } static void perf_set_shadow_time(struct perf_event *event, struct perf_event_context *ctx, u64 tstamp) { /* * use the correct time source for the time snapshot * * We could get by without this by leveraging the * fact that to get to this function, the caller * has most likely already called update_context_time() * and update_cgrp_time_xx() and thus both timestamp * are identical (or very close). Given that tstamp is, * already adjusted for cgroup, we could say that: * tstamp - ctx->timestamp * is equivalent to * tstamp - cgrp->timestamp. * * Then, in perf_output_read(), the calculation would * work with no changes because: * - event is guaranteed scheduled in * - no scheduled out in between * - thus the timestamp would be the same * * But this is a bit hairy. * * So instead, we have an explicit cgroup call to remain * within the time time source all along. We believe it * is cleaner and simpler to understand. */ if (is_cgroup_event(event)) perf_cgroup_set_shadow_time(event, tstamp); else event->shadow_ctx_time = tstamp - ctx->timestamp; } #define MAX_INTERRUPTS (~0ULL) static void perf_log_throttle(struct perf_event *event, int enable); static void perf_log_itrace_start(struct perf_event *event); static int event_sched_in(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); int ret = 0; lockdep_assert_held(&ctx->lock); if (event->state <= PERF_EVENT_STATE_OFF) return 0; WRITE_ONCE(event->oncpu, smp_processor_id()); /* * Order event::oncpu write to happen before the ACTIVE state * is visible. */ smp_wmb(); WRITE_ONCE(event->state, PERF_EVENT_STATE_ACTIVE); /* * Unthrottle events, since we scheduled we might have missed several * ticks already, also for a heavily scheduling task there is little * guarantee it'll get a tick in a timely manner. */ if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) { perf_log_throttle(event, 1); event->hw.interrupts = 0; } /* * The new state must be visible before we turn it on in the hardware: */ smp_wmb(); perf_pmu_disable(event->pmu); perf_set_shadow_time(event, ctx, tstamp); perf_log_itrace_start(event); if (event->pmu->add(event, PERF_EF_START)) { event->state = PERF_EVENT_STATE_INACTIVE; event->oncpu = -1; ret = -EAGAIN; goto out; } event->tstamp_running += tstamp - event->tstamp_stopped; if (!is_software_event(event)) cpuctx->active_oncpu++; if (!ctx->nr_active++) perf_event_ctx_activate(ctx); if (event->attr.freq && event->attr.sample_freq) ctx->nr_freq++; if (event->attr.exclusive) cpuctx->exclusive = 1; out: perf_pmu_enable(event->pmu); return ret; } static int group_sched_in(struct perf_event *group_event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) { struct perf_event *event, *partial_group = NULL; struct pmu *pmu = ctx->pmu; u64 now = ctx->time; bool simulate = false; if (group_event->state == PERF_EVENT_STATE_OFF) return 0; pmu->start_txn(pmu, PERF_PMU_TXN_ADD); if (event_sched_in(group_event, cpuctx, ctx)) { pmu->cancel_txn(pmu); perf_mux_hrtimer_restart(cpuctx); return -EAGAIN; } /* * Schedule in siblings as one group (if any): */ list_for_each_entry(event, &group_event->sibling_list, group_entry) { if (event_sched_in(event, cpuctx, ctx)) { partial_group = event; goto group_error; } } if (!pmu->commit_txn(pmu)) return 0; group_error: /* * Groups can be scheduled in as one unit only, so undo any * partial group before returning: * The events up to the failed event are scheduled out normally, * tstamp_stopped will be updated. * * The failed events and the remaining siblings need to have * their timings updated as if they had gone thru event_sched_in() * and event_sched_out(). This is required to get consistent timings * across the group. This also takes care of the case where the group * could never be scheduled by ensuring tstamp_stopped is set to mark * the time the event was actually stopped, such that time delta * calculation in update_event_times() is correct. */ list_for_each_entry(event, &group_event->sibling_list, group_entry) { if (event == partial_group) simulate = true; if (simulate) { event->tstamp_running += now - event->tstamp_stopped; event->tstamp_stopped = now; } else { event_sched_out(event, cpuctx, ctx); } } event_sched_out(group_event, cpuctx, ctx); pmu->cancel_txn(pmu); perf_mux_hrtimer_restart(cpuctx); return -EAGAIN; } /* * Work out whether we can put this event group on the CPU now. */ static int group_can_go_on(struct perf_event *event, struct perf_cpu_context *cpuctx, int can_add_hw) { /* * Groups consisting entirely of software events can always go on. */ if (event->group_caps & PERF_EV_CAP_SOFTWARE) return 1; /* * If an exclusive group is already on, no other hardware * events can go on. */ if (cpuctx->exclusive) return 0; /* * If this group is exclusive and there are already * events on the CPU, it can't go on. */ if (event->attr.exclusive && cpuctx->active_oncpu) return 0; /* * Otherwise, try to add it if all previous groups were able * to go on. */ return can_add_hw; } static void add_event_to_ctx(struct perf_event *event, struct perf_event_context *ctx) { u64 tstamp = perf_event_time(event); list_add_event(event, ctx); perf_group_attach(event); event->tstamp_enabled = tstamp; event->tstamp_running = tstamp; event->tstamp_stopped = tstamp; } static void ctx_sched_out(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type); static void ctx_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task); static void task_ctx_sched_out(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, enum event_type_t event_type) { if (!cpuctx->task_ctx) return; if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) return; ctx_sched_out(ctx, cpuctx, event_type); } static void perf_event_sched_in(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, struct task_struct *task) { cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task); if (ctx) ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task); cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task); if (ctx) ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task); } /* * We want to maintain the following priority of scheduling: * - CPU pinned (EVENT_CPU | EVENT_PINNED) * - task pinned (EVENT_PINNED) * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE) * - task flexible (EVENT_FLEXIBLE). * * In order to avoid unscheduling and scheduling back in everything every * time an event is added, only do it for the groups of equal priority and * below. * * This can be called after a batch operation on task events, in which case * event_type is a bit mask of the types of events involved. For CPU events, * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE. */ static void ctx_resched(struct perf_cpu_context *cpuctx, struct perf_event_context *task_ctx, enum event_type_t event_type) { enum event_type_t ctx_event_type = event_type & EVENT_ALL; bool cpu_event = !!(event_type & EVENT_CPU); /* * If pinned groups are involved, flexible groups also need to be * scheduled out. */ if (event_type & EVENT_PINNED) event_type |= EVENT_FLEXIBLE; perf_pmu_disable(cpuctx->ctx.pmu); if (task_ctx) task_ctx_sched_out(cpuctx, task_ctx, event_type); /* * Decide which cpu ctx groups to schedule out based on the types * of events that caused rescheduling: * - EVENT_CPU: schedule out corresponding groups; * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups; * - otherwise, do nothing more. */ if (cpu_event) cpu_ctx_sched_out(cpuctx, ctx_event_type); else if (ctx_event_type & EVENT_PINNED) cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); perf_event_sched_in(cpuctx, task_ctx, current); perf_pmu_enable(cpuctx->ctx.pmu); } /* * Cross CPU call to install and enable a performance event * * Very similar to remote_function() + event_function() but cannot assume that * things like ctx->is_active and cpuctx->task_ctx are set. */ static int __perf_install_in_context(void *info) { struct perf_event *event = info; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct perf_event_context *task_ctx = cpuctx->task_ctx; bool reprogram = true; int ret = 0; raw_spin_lock(&cpuctx->ctx.lock); if (ctx->task) { raw_spin_lock(&ctx->lock); task_ctx = ctx; reprogram = (ctx->task == current); /* * If the task is running, it must be running on this CPU, * otherwise we cannot reprogram things. * * If its not running, we don't care, ctx->lock will * serialize against it becoming runnable. */ if (task_curr(ctx->task) && !reprogram) { ret = -ESRCH; goto unlock; } WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx); } else if (task_ctx) { raw_spin_lock(&task_ctx->lock); } if (reprogram) { ctx_sched_out(ctx, cpuctx, EVENT_TIME); add_event_to_ctx(event, ctx); ctx_resched(cpuctx, task_ctx, get_event_type(event)); } else { add_event_to_ctx(event, ctx); } unlock: perf_ctx_unlock(cpuctx, task_ctx); return ret; } /* * Attach a performance event to a context. * * Very similar to event_function_call, see comment there. */ static void perf_install_in_context(struct perf_event_context *ctx, struct perf_event *event, int cpu) { struct task_struct *task = READ_ONCE(ctx->task); lockdep_assert_held(&ctx->mutex); if (event->cpu != -1) event->cpu = cpu; /* * Ensures that if we can observe event->ctx, both the event and ctx * will be 'complete'. See perf_iterate_sb_cpu(). */ smp_store_release(&event->ctx, ctx); if (!task) { cpu_function_call(cpu, __perf_install_in_context, event); return; } /* * Should not happen, we validate the ctx is still alive before calling. */ if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) return; /* * Installing events is tricky because we cannot rely on ctx->is_active * to be set in case this is the nr_events 0 -> 1 transition. * * Instead we use task_curr(), which tells us if the task is running. * However, since we use task_curr() outside of rq::lock, we can race * against the actual state. This means the result can be wrong. * * If we get a false positive, we retry, this is harmless. * * If we get a false negative, things are complicated. If we are after * perf_event_context_sched_in() ctx::lock will serialize us, and the * value must be correct. If we're before, it doesn't matter since * perf_event_context_sched_in() will program the counter. * * However, this hinges on the remote context switch having observed * our task->perf_event_ctxp[] store, such that it will in fact take * ctx::lock in perf_event_context_sched_in(). * * We do this by task_function_call(), if the IPI fails to hit the task * we know any future context switch of task must see the * perf_event_ctpx[] store. */ /* * This smp_mb() orders the task->perf_event_ctxp[] store with the * task_cpu() load, such that if the IPI then does not find the task * running, a future context switch of that task must observe the * store. */ smp_mb(); again: if (!task_function_call(task, __perf_install_in_context, event)) return; raw_spin_lock_irq(&ctx->lock); task = ctx->task; if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) { /* * Cannot happen because we already checked above (which also * cannot happen), and we hold ctx->mutex, which serializes us * against perf_event_exit_task_context(). */ raw_spin_unlock_irq(&ctx->lock); return; } /* * If the task is not running, ctx->lock will avoid it becoming so, * thus we can safely install the event. */ if (task_curr(task)) { raw_spin_unlock_irq(&ctx->lock); goto again; } add_event_to_ctx(event, ctx); raw_spin_unlock_irq(&ctx->lock); } /* * Put a event into inactive state and update time fields. * Enabling the leader of a group effectively enables all * the group members that aren't explicitly disabled, so we * have to update their ->tstamp_enabled also. * Note: this works for group members as well as group leaders * since the non-leader members' sibling_lists will be empty. */ static void __perf_event_mark_enabled(struct perf_event *event) { struct perf_event *sub; u64 tstamp = perf_event_time(event); event->state = PERF_EVENT_STATE_INACTIVE; event->tstamp_enabled = tstamp - event->total_time_enabled; list_for_each_entry(sub, &event->sibling_list, group_entry) { if (sub->state >= PERF_EVENT_STATE_INACTIVE) sub->tstamp_enabled = tstamp - sub->total_time_enabled; } } /* * Cross CPU call to enable a performance event */ static void __perf_event_enable(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, void *info) { struct perf_event *leader = event->group_leader; struct perf_event_context *task_ctx; if (event->state >= PERF_EVENT_STATE_INACTIVE || event->state <= PERF_EVENT_STATE_ERROR) return; if (ctx->is_active) ctx_sched_out(ctx, cpuctx, EVENT_TIME); __perf_event_mark_enabled(event); if (!ctx->is_active) return; if (!event_filter_match(event)) { if (is_cgroup_event(event)) perf_cgroup_defer_enabled(event); ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); return; } /* * If the event is in a group and isn't the group leader, * then don't put it on unless the group is on. */ if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) { ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); return; } task_ctx = cpuctx->task_ctx; if (ctx->task) WARN_ON_ONCE(task_ctx != ctx); ctx_resched(cpuctx, task_ctx, get_event_type(event)); } /* * Enable a event. * * If event->ctx is a cloned context, callers must make sure that * every task struct that event->ctx->task could possibly point to * remains valid. This condition is satisfied when called through * perf_event_for_each_child or perf_event_for_each as described * for perf_event_disable. */ static void _perf_event_enable(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; raw_spin_lock_irq(&ctx->lock); if (event->state >= PERF_EVENT_STATE_INACTIVE || event->state < PERF_EVENT_STATE_ERROR) { raw_spin_unlock_irq(&ctx->lock); return; } /* * If the event is in error state, clear that first. * * That way, if we see the event in error state below, we know that it * has gone back into error state, as distinct from the task having * been scheduled away before the cross-call arrived. */ if (event->state == PERF_EVENT_STATE_ERROR) event->state = PERF_EVENT_STATE_OFF; raw_spin_unlock_irq(&ctx->lock); event_function_call(event, __perf_event_enable, NULL); } /* * See perf_event_disable(); */ void perf_event_enable(struct perf_event *event) { struct perf_event_context *ctx; ctx = perf_event_ctx_lock(event); _perf_event_enable(event); perf_event_ctx_unlock(event, ctx); } EXPORT_SYMBOL_GPL(perf_event_enable); struct stop_event_data { struct perf_event *event; unsigned int restart; }; static int __perf_event_stop(void *info) { struct stop_event_data *sd = info; struct perf_event *event = sd->event; /* if it's already INACTIVE, do nothing */ if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) return 0; /* matches smp_wmb() in event_sched_in() */ smp_rmb(); /* * There is a window with interrupts enabled before we get here, * so we need to check again lest we try to stop another CPU's event. */ if (READ_ONCE(event->oncpu) != smp_processor_id()) return -EAGAIN; event->pmu->stop(event, PERF_EF_UPDATE); /* * May race with the actual stop (through perf_pmu_output_stop()), * but it is only used for events with AUX ring buffer, and such * events will refuse to restart because of rb::aux_mmap_count==0, * see comments in perf_aux_output_begin(). * * Since this is happening on a event-local CPU, no trace is lost * while restarting. */ if (sd->restart) event->pmu->start(event, 0); return 0; } static int perf_event_stop(struct perf_event *event, int restart) { struct stop_event_data sd = { .event = event, .restart = restart, }; int ret = 0; do { if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) return 0; /* matches smp_wmb() in event_sched_in() */ smp_rmb(); /* * We only want to restart ACTIVE events, so if the event goes * inactive here (event->oncpu==-1), there's nothing more to do; * fall through with ret==-ENXIO. */ ret = cpu_function_call(READ_ONCE(event->oncpu), __perf_event_stop, &sd); } while (ret == -EAGAIN); return ret; } /* * In order to contain the amount of racy and tricky in the address filter * configuration management, it is a two part process: * * (p1) when userspace mappings change as a result of (1) or (2) or (3) below, * we update the addresses of corresponding vmas in * event::addr_filters_offs array and bump the event::addr_filters_gen; * (p2) when an event is scheduled in (pmu::add), it calls * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync() * if the generation has changed since the previous call. * * If (p1) happens while the event is active, we restart it to force (p2). * * (1) perf_addr_filters_apply(): adjusting filters' offsets based on * pre-existing mappings, called once when new filters arrive via SET_FILTER * ioctl; * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly * registered mapping, called for every new mmap(), with mm::mmap_sem down * for reading; * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process * of exec. */ void perf_event_addr_filters_sync(struct perf_event *event) { struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); if (!has_addr_filter(event)) return; raw_spin_lock(&ifh->lock); if (event->addr_filters_gen != event->hw.addr_filters_gen) { event->pmu->addr_filters_sync(event); event->hw.addr_filters_gen = event->addr_filters_gen; } raw_spin_unlock(&ifh->lock); } EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync); static int _perf_event_refresh(struct perf_event *event, int refresh) { /* * not supported on inherited events */ if (event->attr.inherit || !is_sampling_event(event)) return -EINVAL; atomic_add(refresh, &event->event_limit); _perf_event_enable(event); return 0; } /* * See perf_event_disable() */ int perf_event_refresh(struct perf_event *event, int refresh) { struct perf_event_context *ctx; int ret; ctx = perf_event_ctx_lock(event); ret = _perf_event_refresh(event, refresh); perf_event_ctx_unlock(event, ctx); return ret; } EXPORT_SYMBOL_GPL(perf_event_refresh); static void ctx_sched_out(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type) { int is_active = ctx->is_active; struct perf_event *event; lockdep_assert_held(&ctx->lock); if (likely(!ctx->nr_events)) { /* * See __perf_remove_from_context(). */ WARN_ON_ONCE(ctx->is_active); if (ctx->task) WARN_ON_ONCE(cpuctx->task_ctx); return; } ctx->is_active &= ~event_type; if (!(ctx->is_active & EVENT_ALL)) ctx->is_active = 0; if (ctx->task) { WARN_ON_ONCE(cpuctx->task_ctx != ctx); if (!ctx->is_active) cpuctx->task_ctx = NULL; } /* * Always update time if it was set; not only when it changes. * Otherwise we can 'forget' to update time for any but the last * context we sched out. For example: * * ctx_sched_out(.event_type = EVENT_FLEXIBLE) * ctx_sched_out(.event_type = EVENT_PINNED) * * would only update time for the pinned events. */ if (is_active & EVENT_TIME) { /* update (and stop) ctx time */ update_context_time(ctx); update_cgrp_time_from_cpuctx(cpuctx); } is_active ^= ctx->is_active; /* changed bits */ if (!ctx->nr_active || !(is_active & EVENT_ALL)) return; perf_pmu_disable(ctx->pmu); if (is_active & EVENT_PINNED) { list_for_each_entry(event, &ctx->pinned_groups, group_entry) group_sched_out(event, cpuctx, ctx); } if (is_active & EVENT_FLEXIBLE) { list_for_each_entry(event, &ctx->flexible_groups, group_entry) group_sched_out(event, cpuctx, ctx); } perf_pmu_enable(ctx->pmu); } /* * Test whether two contexts are equivalent, i.e. whether they have both been * cloned from the same version of the same context. * * Equivalence is measured using a generation number in the context that is * incremented on each modification to it; see unclone_ctx(), list_add_event() * and list_del_event(). */ static int context_equiv(struct perf_event_context *ctx1, struct perf_event_context *ctx2) { lockdep_assert_held(&ctx1->lock); lockdep_assert_held(&ctx2->lock); /* Pinning disables the swap optimization */ if (ctx1->pin_count || ctx2->pin_count) return 0; /* If ctx1 is the parent of ctx2 */ if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) return 1; /* If ctx2 is the parent of ctx1 */ if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) return 1; /* * If ctx1 and ctx2 have the same parent; we flatten the parent * hierarchy, see perf_event_init_context(). */ if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && ctx1->parent_gen == ctx2->parent_gen) return 1; /* Unmatched */ return 0; } static void __perf_event_sync_stat(struct perf_event *event, struct perf_event *next_event) { u64 value; if (!event->attr.inherit_stat) return; /* * Update the event value, we cannot use perf_event_read() * because we're in the middle of a context switch and have IRQs * disabled, which upsets smp_call_function_single(), however * we know the event must be on the current CPU, therefore we * don't need to use it. */ switch (event->state) { case PERF_EVENT_STATE_ACTIVE: event->pmu->read(event); /* fall-through */ case PERF_EVENT_STATE_INACTIVE: update_event_times(event); break; default: break; } /* * In order to keep per-task stats reliable we need to flip the event * values when we flip the contexts. */ value = local64_read(&next_event->count); value = local64_xchg(&event->count, value); local64_set(&next_event->count, value); swap(event->total_time_enabled, next_event->total_time_enabled); swap(event->total_time_running, next_event->total_time_running); /* * Since we swizzled the values, update the user visible data too. */ perf_event_update_userpage(event); perf_event_update_userpage(next_event); } static void perf_event_sync_stat(struct perf_event_context *ctx, struct perf_event_context *next_ctx) { struct perf_event *event, *next_event; if (!ctx->nr_stat) return; update_context_time(ctx); event = list_first_entry(&ctx->event_list, struct perf_event, event_entry); next_event = list_first_entry(&next_ctx->event_list, struct perf_event, event_entry); while (&event->event_entry != &ctx->event_list && &next_event->event_entry != &next_ctx->event_list) { __perf_event_sync_stat(event, next_event); event = list_next_entry(event, event_entry); next_event = list_next_entry(next_event, event_entry); } } static void perf_event_context_sched_out(struct task_struct *task, int ctxn, struct task_struct *next) { struct perf_event_context *ctx = task->perf_event_ctxp[ctxn]; struct perf_event_context *next_ctx; struct perf_event_context *parent, *next_parent; struct perf_cpu_context *cpuctx; int do_switch = 1; if (likely(!ctx)) return; cpuctx = __get_cpu_context(ctx); if (!cpuctx->task_ctx) return; rcu_read_lock(); next_ctx = next->perf_event_ctxp[ctxn]; if (!next_ctx) goto unlock; parent = rcu_dereference(ctx->parent_ctx); next_parent = rcu_dereference(next_ctx->parent_ctx); /* If neither context have a parent context; they cannot be clones. */ if (!parent && !next_parent) goto unlock; if (next_parent == ctx || next_ctx == parent || next_parent == parent) { /* * Looks like the two contexts are clones, so we might be * able to optimize the context switch. We lock both * contexts and check that they are clones under the * lock (including re-checking that neither has been * uncloned in the meantime). It doesn't matter which * order we take the locks because no other cpu could * be trying to lock both of these tasks. */ raw_spin_lock(&ctx->lock); raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); if (context_equiv(ctx, next_ctx)) { WRITE_ONCE(ctx->task, next); WRITE_ONCE(next_ctx->task, task); swap(ctx->task_ctx_data, next_ctx->task_ctx_data); /* * RCU_INIT_POINTER here is safe because we've not * modified the ctx and the above modification of * ctx->task and ctx->task_ctx_data are immaterial * since those values are always verified under * ctx->lock which we're now holding. */ RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx); RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx); do_switch = 0; perf_event_sync_stat(ctx, next_ctx); } raw_spin_unlock(&next_ctx->lock); raw_spin_unlock(&ctx->lock); } unlock: rcu_read_unlock(); if (do_switch) { raw_spin_lock(&ctx->lock); task_ctx_sched_out(cpuctx, ctx, EVENT_ALL); raw_spin_unlock(&ctx->lock); } } static DEFINE_PER_CPU(struct list_head, sched_cb_list); void perf_sched_cb_dec(struct pmu *pmu) { struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); this_cpu_dec(perf_sched_cb_usages); if (!--cpuctx->sched_cb_usage) list_del(&cpuctx->sched_cb_entry); } void perf_sched_cb_inc(struct pmu *pmu) { struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); if (!cpuctx->sched_cb_usage++) list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list)); this_cpu_inc(perf_sched_cb_usages); } /* * This function provides the context switch callback to the lower code * layer. It is invoked ONLY when the context switch callback is enabled. * * This callback is relevant even to per-cpu events; for example multi event * PEBS requires this to provide PID/TID information. This requires we flush * all queued PEBS records before we context switch to a new task. */ static void perf_pmu_sched_task(struct task_struct *prev, struct task_struct *next, bool sched_in) { struct perf_cpu_context *cpuctx; struct pmu *pmu; if (prev == next) return; list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) { pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */ if (WARN_ON_ONCE(!pmu->sched_task)) continue; perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(pmu); pmu->sched_task(cpuctx->task_ctx, sched_in); perf_pmu_enable(pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); } } static void perf_event_switch(struct task_struct *task, struct task_struct *next_prev, bool sched_in); #define for_each_task_context_nr(ctxn) \ for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++) /* * Called from scheduler to remove the events of the current task, * with interrupts disabled. * * We stop each event and update the event value in event->count. * * This does not protect us against NMI, but disable() * sets the disabled bit in the control field of event _before_ * accessing the event control register. If a NMI hits, then it will * not restart the event. */ void __perf_event_task_sched_out(struct task_struct *task, struct task_struct *next) { int ctxn; if (__this_cpu_read(perf_sched_cb_usages)) perf_pmu_sched_task(task, next, false); if (atomic_read(&nr_switch_events)) perf_event_switch(task, next, false); for_each_task_context_nr(ctxn) perf_event_context_sched_out(task, ctxn, next); /* * if cgroup events exist on this CPU, then we need * to check if we have to switch out PMU state. * cgroup event are system-wide mode only */ if (atomic_read(this_cpu_ptr(&perf_cgroup_events))) perf_cgroup_sched_out(task, next); } /* * Called with IRQs disabled */ static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, enum event_type_t event_type) { ctx_sched_out(&cpuctx->ctx, cpuctx, event_type); } static void ctx_pinned_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx) { struct perf_event *event; list_for_each_entry(event, &ctx->pinned_groups, group_entry) { if (event->state <= PERF_EVENT_STATE_OFF) continue; if (!event_filter_match(event)) continue; /* may need to reset tstamp_enabled */ if (is_cgroup_event(event)) perf_cgroup_mark_enabled(event, ctx); if (group_can_go_on(event, cpuctx, 1)) group_sched_in(event, cpuctx, ctx); /* * If this pinned group hasn't been scheduled, * put it in error state. */ if (event->state == PERF_EVENT_STATE_INACTIVE) { update_group_times(event); event->state = PERF_EVENT_STATE_ERROR; } } } static void ctx_flexible_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx) { struct perf_event *event; int can_add_hw = 1; list_for_each_entry(event, &ctx->flexible_groups, group_entry) { /* Ignore events in OFF or ERROR state */ if (event->state <= PERF_EVENT_STATE_OFF) continue; /* * Listen to the 'cpu' scheduling filter constraint * of events: */ if (!event_filter_match(event)) continue; /* may need to reset tstamp_enabled */ if (is_cgroup_event(event)) perf_cgroup_mark_enabled(event, ctx); if (group_can_go_on(event, cpuctx, can_add_hw)) { if (group_sched_in(event, cpuctx, ctx)) can_add_hw = 0; } } } static void ctx_sched_in(struct perf_event_context *ctx, struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task) { int is_active = ctx->is_active; u64 now; lockdep_assert_held(&ctx->lock); if (likely(!ctx->nr_events)) return; ctx->is_active |= (event_type | EVENT_TIME); if (ctx->task) { if (!is_active) cpuctx->task_ctx = ctx; else WARN_ON_ONCE(cpuctx->task_ctx != ctx); } is_active ^= ctx->is_active; /* changed bits */ if (is_active & EVENT_TIME) { /* start ctx time */ now = perf_clock(); ctx->timestamp = now; perf_cgroup_set_timestamp(task, ctx); } /* * First go through the list and put on any pinned groups * in order to give them the best chance of going on. */ if (is_active & EVENT_PINNED) ctx_pinned_sched_in(ctx, cpuctx); /* Then walk through the lower prio flexible groups */ if (is_active & EVENT_FLEXIBLE) ctx_flexible_sched_in(ctx, cpuctx); } static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, enum event_type_t event_type, struct task_struct *task) { struct perf_event_context *ctx = &cpuctx->ctx; ctx_sched_in(ctx, cpuctx, event_type, task); } static void perf_event_context_sched_in(struct perf_event_context *ctx, struct task_struct *task) { struct perf_cpu_context *cpuctx; cpuctx = __get_cpu_context(ctx); if (cpuctx->task_ctx == ctx) return; perf_ctx_lock(cpuctx, ctx); perf_pmu_disable(ctx->pmu); /* * We want to keep the following priority order: * cpu pinned (that don't need to move), task pinned, * cpu flexible, task flexible. * * However, if task's ctx is not carrying any pinned * events, no need to flip the cpuctx's events around. */ if (!list_empty(&ctx->pinned_groups)) cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); perf_event_sched_in(cpuctx, ctx, task); perf_pmu_enable(ctx->pmu); perf_ctx_unlock(cpuctx, ctx); } /* * Called from scheduler to add the events of the current task * with interrupts disabled. * * We restore the event value and then enable it. * * This does not protect us against NMI, but enable() * sets the enabled bit in the control field of event _before_ * accessing the event control register. If a NMI hits, then it will * keep the event running. */ void __perf_event_task_sched_in(struct task_struct *prev, struct task_struct *task) { struct perf_event_context *ctx; int ctxn; /* * If cgroup events exist on this CPU, then we need to check if we have * to switch in PMU state; cgroup event are system-wide mode only. * * Since cgroup events are CPU events, we must schedule these in before * we schedule in the task events. */ if (atomic_read(this_cpu_ptr(&perf_cgroup_events))) perf_cgroup_sched_in(prev, task); for_each_task_context_nr(ctxn) { ctx = task->perf_event_ctxp[ctxn]; if (likely(!ctx)) continue; perf_event_context_sched_in(ctx, task); } if (atomic_read(&nr_switch_events)) perf_event_switch(task, prev, true); if (__this_cpu_read(perf_sched_cb_usages)) perf_pmu_sched_task(prev, task, true); } static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) { u64 frequency = event->attr.sample_freq; u64 sec = NSEC_PER_SEC; u64 divisor, dividend; int count_fls, nsec_fls, frequency_fls, sec_fls; count_fls = fls64(count); nsec_fls = fls64(nsec); frequency_fls = fls64(frequency); sec_fls = 30; /* * We got @count in @nsec, with a target of sample_freq HZ * the target period becomes: * * @count * 10^9 * period = ------------------- * @nsec * sample_freq * */ /* * Reduce accuracy by one bit such that @a and @b converge * to a similar magnitude. */ #define REDUCE_FLS(a, b) \ do { \ if (a##_fls > b##_fls) { \ a >>= 1; \ a##_fls--; \ } else { \ b >>= 1; \ b##_fls--; \ } \ } while (0) /* * Reduce accuracy until either term fits in a u64, then proceed with * the other, so that finally we can do a u64/u64 division. */ while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { REDUCE_FLS(nsec, frequency); REDUCE_FLS(sec, count); } if (count_fls + sec_fls > 64) { divisor = nsec * frequency; while (count_fls + sec_fls > 64) { REDUCE_FLS(count, sec); divisor >>= 1; } dividend = count * sec; } else { dividend = count * sec; while (nsec_fls + frequency_fls > 64) { REDUCE_FLS(nsec, frequency); dividend >>= 1; } divisor = nsec * frequency; } if (!divisor) return dividend; return div64_u64(dividend, divisor); } static DEFINE_PER_CPU(int, perf_throttled_count); static DEFINE_PER_CPU(u64, perf_throttled_seq); static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) { struct hw_perf_event *hwc = &event->hw; s64 period, sample_period; s64 delta; period = perf_calculate_period(event, nsec, count); delta = (s64)(period - hwc->sample_period); delta = (delta + 7) / 8; /* low pass filter */ sample_period = hwc->sample_period + delta; if (!sample_period) sample_period = 1; hwc->sample_period = sample_period; if (local64_read(&hwc->period_left) > 8*sample_period) { if (disable) event->pmu->stop(event, PERF_EF_UPDATE); local64_set(&hwc->period_left, 0); if (disable) event->pmu->start(event, PERF_EF_RELOAD); } } /* * combine freq adjustment with unthrottling to avoid two passes over the * events. At the same time, make sure, having freq events does not change * the rate of unthrottling as that would introduce bias. */ static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx, int needs_unthr) { struct perf_event *event; struct hw_perf_event *hwc; u64 now, period = TICK_NSEC; s64 delta; /* * only need to iterate over all events iff: * - context have events in frequency mode (needs freq adjust) * - there are events to unthrottle on this cpu */ if (!(ctx->nr_freq || needs_unthr)) return; raw_spin_lock(&ctx->lock); perf_pmu_disable(ctx->pmu); list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->state != PERF_EVENT_STATE_ACTIVE) continue; if (!event_filter_match(event)) continue; perf_pmu_disable(event->pmu); hwc = &event->hw; if (hwc->interrupts == MAX_INTERRUPTS) { hwc->interrupts = 0; perf_log_throttle(event, 1); event->pmu->start(event, 0); } if (!event->attr.freq || !event->attr.sample_freq) goto next; /* * stop the event and update event->count */ event->pmu->stop(event, PERF_EF_UPDATE); now = local64_read(&event->count); delta = now - hwc->freq_count_stamp; hwc->freq_count_stamp = now; /* * restart the event * reload only if value has changed * we have stopped the event so tell that * to perf_adjust_period() to avoid stopping it * twice. */ if (delta > 0) perf_adjust_period(event, period, delta, false); event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); next: perf_pmu_enable(event->pmu); } perf_pmu_enable(ctx->pmu); raw_spin_unlock(&ctx->lock); } /* * Round-robin a context's events: */ static void rotate_ctx(struct perf_event_context *ctx) { /* * Rotate the first entry last of non-pinned groups. Rotation might be * disabled by the inheritance code. */ if (!ctx->rotate_disable) list_rotate_left(&ctx->flexible_groups); } static int perf_rotate_context(struct perf_cpu_context *cpuctx) { struct perf_event_context *ctx = NULL; int rotate = 0; if (cpuctx->ctx.nr_events) { if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active) rotate = 1; } ctx = cpuctx->task_ctx; if (ctx && ctx->nr_events) { if (ctx->nr_events != ctx->nr_active) rotate = 1; } if (!rotate) goto done; perf_ctx_lock(cpuctx, cpuctx->task_ctx); perf_pmu_disable(cpuctx->ctx.pmu); cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); if (ctx) ctx_sched_out(ctx, cpuctx, EVENT_FLEXIBLE); rotate_ctx(&cpuctx->ctx); if (ctx) rotate_ctx(ctx); perf_event_sched_in(cpuctx, ctx, current); perf_pmu_enable(cpuctx->ctx.pmu); perf_ctx_unlock(cpuctx, cpuctx->task_ctx); done: return rotate; } void perf_event_task_tick(void) { struct list_head *head = this_cpu_ptr(&active_ctx_list); struct perf_event_context *ctx, *tmp; int throttled; WARN_ON(!irqs_disabled()); __this_cpu_inc(perf_throttled_seq); throttled = __this_cpu_xchg(perf_throttled_count, 0); tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); list_for_each_entry_safe(ctx, tmp, head, active_ctx_list) perf_adjust_freq_unthr_context(ctx, throttled); } static int event_enable_on_exec(struct perf_event *event, struct perf_event_context *ctx) { if (!event->attr.enable_on_exec) return 0; event->attr.enable_on_exec = 0; if (event->state >= PERF_EVENT_STATE_INACTIVE) return 0; __perf_event_mark_enabled(event); return 1; } /* * Enable all of a task's events that have been marked enable-on-exec. * This expects task == current. */ static void perf_event_enable_on_exec(int ctxn) { struct perf_event_context *ctx, *clone_ctx = NULL; enum event_type_t event_type = 0; struct perf_cpu_context *cpuctx; struct perf_event *event; unsigned long flags; int enabled = 0; local_irq_save(flags); ctx = current->perf_event_ctxp[ctxn]; if (!ctx || !ctx->nr_events) goto out; cpuctx = __get_cpu_context(ctx); perf_ctx_lock(cpuctx, ctx); ctx_sched_out(ctx, cpuctx, EVENT_TIME); list_for_each_entry(event, &ctx->event_list, event_entry) { enabled |= event_enable_on_exec(event, ctx); event_type |= get_event_type(event); } /* * Unclone and reschedule this context if we enabled any event. */ if (enabled) { clone_ctx = unclone_ctx(ctx); ctx_resched(cpuctx, ctx, event_type); } else { ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); } perf_ctx_unlock(cpuctx, ctx); out: local_irq_restore(flags); if (clone_ctx) put_ctx(clone_ctx); } struct perf_read_data { struct perf_event *event; bool group; int ret; }; static int __perf_event_read_cpu(struct perf_event *event, int event_cpu) { u16 local_pkg, event_pkg; if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) { int local_cpu = smp_processor_id(); event_pkg = topology_physical_package_id(event_cpu); local_pkg = topology_physical_package_id(local_cpu); if (event_pkg == local_pkg) return local_cpu; } return event_cpu; } /* * Cross CPU call to read the hardware event */ static void __perf_event_read(void *info) { struct perf_read_data *data = info; struct perf_event *sub, *event = data->event; struct perf_event_context *ctx = event->ctx; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct pmu *pmu = event->pmu; /* * If this is a task context, we need to check whether it is * the current task context of this cpu. If not it has been * scheduled out before the smp call arrived. In that case * event->count would have been updated to a recent sample * when the event was scheduled out. */ if (ctx->task && cpuctx->task_ctx != ctx) return; raw_spin_lock(&ctx->lock); if (ctx->is_active) { update_context_time(ctx); update_cgrp_time_from_event(event); } update_event_times(event); if (event->state != PERF_EVENT_STATE_ACTIVE) goto unlock; if (!data->group) { pmu->read(event); data->ret = 0; goto unlock; } pmu->start_txn(pmu, PERF_PMU_TXN_READ); pmu->read(event); list_for_each_entry(sub, &event->sibling_list, group_entry) { update_event_times(sub); if (sub->state == PERF_EVENT_STATE_ACTIVE) { /* * Use sibling's PMU rather than @event's since * sibling could be on different (eg: software) PMU. */ sub->pmu->read(sub); } } data->ret = pmu->commit_txn(pmu); unlock: raw_spin_unlock(&ctx->lock); } static inline u64 perf_event_count(struct perf_event *event) { if (event->pmu->count) return event->pmu->count(event); return __perf_event_count(event); } /* * NMI-safe method to read a local event, that is an event that * is: * - either for the current task, or for this CPU * - does not have inherit set, for inherited task events * will not be local and we cannot read them atomically * - must not have a pmu::count method */ u64 perf_event_read_local(struct perf_event *event) { unsigned long flags; u64 val; /* * Disabling interrupts avoids all counter scheduling (context * switches, timer based rotation and IPIs). */ local_irq_save(flags); /* If this is a per-task event, it must be for current */ WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) && event->hw.target != current); /* If this is a per-CPU event, it must be for this CPU */ WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) && event->cpu != smp_processor_id()); /* * It must not be an event with inherit set, we cannot read * all child counters from atomic context. */ WARN_ON_ONCE(event->attr.inherit); /* * It must not have a pmu::count method, those are not * NMI safe. */ WARN_ON_ONCE(event->pmu->count); /* * If the event is currently on this CPU, its either a per-task event, * or local to this CPU. Furthermore it means its ACTIVE (otherwise * oncpu == -1). */ if (event->oncpu == smp_processor_id()) event->pmu->read(event); val = local64_read(&event->count); local_irq_restore(flags); return val; } static int perf_event_read(struct perf_event *event, bool group) { int event_cpu, ret = 0; /* * If event is enabled and currently active on a CPU, update the * value in the event structure: */ if (event->state == PERF_EVENT_STATE_ACTIVE) { struct perf_read_data data = { .event = event, .group = group, .ret = 0, }; event_cpu = READ_ONCE(event->oncpu); if ((unsigned)event_cpu >= nr_cpu_ids) return 0; preempt_disable(); event_cpu = __perf_event_read_cpu(event, event_cpu); /* * Purposely ignore the smp_call_function_single() return * value. * * If event_cpu isn't a valid CPU it means the event got * scheduled out and that will have updated the event count. * * Therefore, either way, we'll have an up-to-date event count * after this. */ (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1); preempt_enable(); ret = data.ret; } else if (event->state == PERF_EVENT_STATE_INACTIVE) { struct perf_event_context *ctx = event->ctx; unsigned long flags; raw_spin_lock_irqsave(&ctx->lock, flags); /* * may read while context is not active * (e.g., thread is blocked), in that case * we cannot update context time */ if (ctx->is_active) { update_context_time(ctx); update_cgrp_time_from_event(event); } if (group) update_group_times(event); else update_event_times(event); raw_spin_unlock_irqrestore(&ctx->lock, flags); } return ret; } /* * Initialize the perf_event context in a task_struct: */ static void __perf_event_init_context(struct perf_event_context *ctx) { raw_spin_lock_init(&ctx->lock); mutex_init(&ctx->mutex); INIT_LIST_HEAD(&ctx->active_ctx_list); INIT_LIST_HEAD(&ctx->pinned_groups); INIT_LIST_HEAD(&ctx->flexible_groups); INIT_LIST_HEAD(&ctx->event_list); atomic_set(&ctx->refcount, 1); } static struct perf_event_context * alloc_perf_context(struct pmu *pmu, struct task_struct *task) { struct perf_event_context *ctx; ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL); if (!ctx) return NULL; __perf_event_init_context(ctx); if (task) { ctx->task = task; get_task_struct(task); } ctx->pmu = pmu; return ctx; } static struct task_struct * find_lively_task_by_vpid(pid_t vpid) { struct task_struct *task; rcu_read_lock(); if (!vpid) task = current; else task = find_task_by_vpid(vpid); if (task) get_task_struct(task); rcu_read_unlock(); if (!task) return ERR_PTR(-ESRCH); return task; } /* * Returns a matching context with refcount and pincount. */ static struct perf_event_context * find_get_context(struct pmu *pmu, struct task_struct *task, struct perf_event *event) { struct perf_event_context *ctx, *clone_ctx = NULL; struct perf_cpu_context *cpuctx; void *task_ctx_data = NULL; unsigned long flags; int ctxn, err; int cpu = event->cpu; if (!task) { /* Must be root to operate on a CPU event: */ if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN)) return ERR_PTR(-EACCES); /* * We could be clever and allow to attach a event to an * offline CPU and activate it when the CPU comes up, but * that's for later. */ if (!cpu_online(cpu)) return ERR_PTR(-ENODEV); cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); ctx = &cpuctx->ctx; get_ctx(ctx); ++ctx->pin_count; return ctx; } err = -EINVAL; ctxn = pmu->task_ctx_nr; if (ctxn < 0) goto errout; if (event->attach_state & PERF_ATTACH_TASK_DATA) { task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL); if (!task_ctx_data) { err = -ENOMEM; goto errout; } } retry: ctx = perf_lock_task_context(task, ctxn, &flags); if (ctx) { clone_ctx = unclone_ctx(ctx); ++ctx->pin_count; if (task_ctx_data && !ctx->task_ctx_data) { ctx->task_ctx_data = task_ctx_data; task_ctx_data = NULL; } raw_spin_unlock_irqrestore(&ctx->lock, flags); if (clone_ctx) put_ctx(clone_ctx); } else { ctx = alloc_perf_context(pmu, task); err = -ENOMEM; if (!ctx) goto errout; if (task_ctx_data) { ctx->task_ctx_data = task_ctx_data; task_ctx_data = NULL; } err = 0; mutex_lock(&task->perf_event_mutex); /* * If it has already passed perf_event_exit_task(). * we must see PF_EXITING, it takes this mutex too. */ if (task->flags & PF_EXITING) err = -ESRCH; else if (task->perf_event_ctxp[ctxn]) err = -EAGAIN; else { get_ctx(ctx); ++ctx->pin_count; rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx); } mutex_unlock(&task->perf_event_mutex); if (unlikely(err)) { put_ctx(ctx); if (err == -EAGAIN) goto retry; goto errout; } } kfree(task_ctx_data); return ctx; errout: kfree(task_ctx_data); return ERR_PTR(err); } static void perf_event_free_filter(struct perf_event *event); static void perf_event_free_bpf_prog(struct perf_event *event); static void free_event_rcu(struct rcu_head *head) { struct perf_event *event; event = container_of(head, struct perf_event, rcu_head); if (event->ns) put_pid_ns(event->ns); perf_event_free_filter(event); kfree(event); } static void ring_buffer_attach(struct perf_event *event, struct ring_buffer *rb); static void detach_sb_event(struct perf_event *event) { struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); raw_spin_lock(&pel->lock); list_del_rcu(&event->sb_list); raw_spin_unlock(&pel->lock); } static bool is_sb_event(struct perf_event *event) { struct perf_event_attr *attr = &event->attr; if (event->parent) return false; if (event->attach_state & PERF_ATTACH_TASK) return false; if (attr->mmap || attr->mmap_data || attr->mmap2 || attr->comm || attr->comm_exec || attr->task || attr->context_switch) return true; return false; } static void unaccount_pmu_sb_event(struct perf_event *event) { if (is_sb_event(event)) detach_sb_event(event); } static void unaccount_event_cpu(struct perf_event *event, int cpu) { if (event->parent) return; if (is_cgroup_event(event)) atomic_dec(&per_cpu(perf_cgroup_events, cpu)); } #ifdef CONFIG_NO_HZ_FULL static DEFINE_SPINLOCK(nr_freq_lock); #endif static void unaccount_freq_event_nohz(void) { #ifdef CONFIG_NO_HZ_FULL spin_lock(&nr_freq_lock); if (atomic_dec_and_test(&nr_freq_events)) tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); spin_unlock(&nr_freq_lock); #endif } static void unaccount_freq_event(void) { if (tick_nohz_full_enabled()) unaccount_freq_event_nohz(); else atomic_dec(&nr_freq_events); } static void unaccount_event(struct perf_event *event) { bool dec = false; if (event->parent) return; if (event->attach_state & PERF_ATTACH_TASK) dec = true; if (event->attr.mmap || event->attr.mmap_data) atomic_dec(&nr_mmap_events); if (event->attr.comm) atomic_dec(&nr_comm_events); if (event->attr.task) atomic_dec(&nr_task_events); if (event->attr.freq) unaccount_freq_event(); if (event->attr.context_switch) { dec = true; atomic_dec(&nr_switch_events); } if (is_cgroup_event(event)) dec = true; if (has_branch_stack(event)) dec = true; if (dec) { if (!atomic_add_unless(&perf_sched_count, -1, 1)) schedule_delayed_work(&perf_sched_work, HZ); } unaccount_event_cpu(event, event->cpu); unaccount_pmu_sb_event(event); } static void perf_sched_delayed(struct work_struct *work) { mutex_lock(&perf_sched_mutex); if (atomic_dec_and_test(&perf_sched_count)) static_branch_disable(&perf_sched_events); mutex_unlock(&perf_sched_mutex); } /* * The following implement mutual exclusion of events on "exclusive" pmus * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled * at a time, so we disallow creating events that might conflict, namely: * * 1) cpu-wide events in the presence of per-task events, * 2) per-task events in the presence of cpu-wide events, * 3) two matching events on the same context. * * The former two cases are handled in the allocation path (perf_event_alloc(), * _free_event()), the latter -- before the first perf_install_in_context(). */ static int exclusive_event_init(struct perf_event *event) { struct pmu *pmu = event->pmu; if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE)) return 0; /* * Prevent co-existence of per-task and cpu-wide events on the * same exclusive pmu. * * Negative pmu::exclusive_cnt means there are cpu-wide * events on this "exclusive" pmu, positive means there are * per-task events. * * Since this is called in perf_event_alloc() path, event::ctx * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK * to mean "per-task event", because unlike other attach states it * never gets cleared. */ if (event->attach_state & PERF_ATTACH_TASK) { if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) return -EBUSY; } else { if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) return -EBUSY; } return 0; } static void exclusive_event_destroy(struct perf_event *event) { struct pmu *pmu = event->pmu; if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE)) return; /* see comment in exclusive_event_init() */ if (event->attach_state & PERF_ATTACH_TASK) atomic_dec(&pmu->exclusive_cnt); else atomic_inc(&pmu->exclusive_cnt); } static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) { if ((e1->pmu == e2->pmu) && (e1->cpu == e2->cpu || e1->cpu == -1 || e2->cpu == -1)) return true; return false; } /* Called under the same ctx::mutex as perf_install_in_context() */ static bool exclusive_event_installable(struct perf_event *event, struct perf_event_context *ctx) { struct perf_event *iter_event; struct pmu *pmu = event->pmu; if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE)) return true; list_for_each_entry(iter_event, &ctx->event_list, event_entry) { if (exclusive_event_match(iter_event, event)) return false; } return true; } static void perf_addr_filters_splice(struct perf_event *event, struct list_head *head); static void _free_event(struct perf_event *event) { irq_work_sync(&event->pending); unaccount_event(event); if (event->rb) { /* * Can happen when we close an event with re-directed output. * * Since we have a 0 refcount, perf_mmap_close() will skip * over us; possibly making our ring_buffer_put() the last. */ mutex_lock(&event->mmap_mutex); ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); } if (is_cgroup_event(event)) perf_detach_cgroup(event); if (!event->parent) { if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) put_callchain_buffers(); } perf_event_free_bpf_prog(event); perf_addr_filters_splice(event, NULL); kfree(event->addr_filters_offs); if (event->destroy) event->destroy(event); if (event->ctx) put_ctx(event->ctx); exclusive_event_destroy(event); module_put(event->pmu->module); call_rcu(&event->rcu_head, free_event_rcu); } /* * Used to free events which have a known refcount of 1, such as in error paths * where the event isn't exposed yet and inherited events. */ static void free_event(struct perf_event *event) { if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, "unexpected event refcount: %ld; ptr=%p\n", atomic_long_read(&event->refcount), event)) { /* leak to avoid use-after-free */ return; } _free_event(event); } /* * Remove user event from the owner task. */ static void perf_remove_from_owner(struct perf_event *event) { struct task_struct *owner; rcu_read_lock(); /* * Matches the smp_store_release() in perf_event_exit_task(). If we * observe !owner it means the list deletion is complete and we can * indeed free this event, otherwise we need to serialize on * owner->perf_event_mutex. */ owner = lockless_dereference(event->owner); if (owner) { /* * Since delayed_put_task_struct() also drops the last * task reference we can safely take a new reference * while holding the rcu_read_lock(). */ get_task_struct(owner); } rcu_read_unlock(); if (owner) { /* * If we're here through perf_event_exit_task() we're already * holding ctx->mutex which would be an inversion wrt. the * normal lock order. * * However we can safely take this lock because its the child * ctx->mutex. */ mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); /* * We have to re-check the event->owner field, if it is cleared * we raced with perf_event_exit_task(), acquiring the mutex * ensured they're done, and we can proceed with freeing the * event. */ if (event->owner) { list_del_init(&event->owner_entry); smp_store_release(&event->owner, NULL); } mutex_unlock(&owner->perf_event_mutex); put_task_struct(owner); } } static void put_event(struct perf_event *event) { if (!atomic_long_dec_and_test(&event->refcount)) return; _free_event(event); } /* * Kill an event dead; while event:refcount will preserve the event * object, it will not preserve its functionality. Once the last 'user' * gives up the object, we'll destroy the thing. */ int perf_event_release_kernel(struct perf_event *event) { struct perf_event_context *ctx = event->ctx; struct perf_event *child, *tmp; /* * If we got here through err_file: fput(event_file); we will not have * attached to a context yet. */ if (!ctx) { WARN_ON_ONCE(event->attach_state & (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); goto no_ctx; } if (!is_kernel_event(event)) perf_remove_from_owner(event); ctx = perf_event_ctx_lock(event); WARN_ON_ONCE(ctx->parent_ctx); perf_remove_from_context(event, DETACH_GROUP); raw_spin_lock_irq(&ctx->lock); /* * Mark this even as STATE_DEAD, there is no external reference to it * anymore. * * Anybody acquiring event->child_mutex after the below loop _must_ * also see this, most importantly inherit_event() which will avoid * placing more children on the list. * * Thus this guarantees that we will in fact observe and kill _ALL_ * child events. */ event->state = PERF_EVENT_STATE_DEAD; raw_spin_unlock_irq(&ctx->lock); perf_event_ctx_unlock(event, ctx); again: mutex_lock(&event->child_mutex); list_for_each_entry(child, &event->child_list, child_list) { /* * Cannot change, child events are not migrated, see the * comment with perf_event_ctx_lock_nested(). */ ctx = lockless_dereference(child->ctx); /* * Since child_mutex nests inside ctx::mutex, we must jump * through hoops. We start by grabbing a reference on the ctx. * * Since the event cannot get freed while we hold the * child_mutex, the context must also exist and have a !0 * reference count. */ get_ctx(ctx); /* * Now that we have a ctx ref, we can drop child_mutex, and * acquire ctx::mutex without fear of it going away. Then we * can re-acquire child_mutex. */ mutex_unlock(&event->child_mutex); mutex_lock(&ctx->mutex); mutex_lock(&event->child_mutex); /* * Now that we hold ctx::mutex and child_mutex, revalidate our * state, if child is still the first entry, it didn't get freed * and we can continue doing so. */ tmp = list_first_entry_or_null(&event->child_list, struct perf_event, child_list); if (tmp == child) { perf_remove_from_context(child, DETACH_GROUP); list_del(&child->child_list); free_event(child); /* * This matches the refcount bump in inherit_event(); * this can't be the last reference. */ put_event(event); } mutex_unlock(&event->child_mutex); mutex_unlock(&ctx->mutex); put_ctx(ctx); goto again; } mutex_unlock(&event->child_mutex); no_ctx: put_event(event); /* Must be the 'last' reference */ return 0; } EXPORT_SYMBOL_GPL(perf_event_release_kernel); /* * Called when the last reference to the file is gone. */ static int perf_release(struct inode *inode, struct file *file) { perf_event_release_kernel(file->private_data); return 0; } u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) { struct perf_event *child; u64 total = 0; *enabled = 0; *running = 0; mutex_lock(&event->child_mutex); (void)perf_event_read(event, false); total += perf_event_count(event); *enabled += event->total_time_enabled + atomic64_read(&event->child_total_time_enabled); *running += event->total_time_running + atomic64_read(&event->child_total_time_running); list_for_each_entry(child, &event->child_list, child_list) { (void)perf_event_read(child, false); total += perf_event_count(child); *enabled += child->total_time_enabled; *running += child->total_time_running; } mutex_unlock(&event->child_mutex); return total; } EXPORT_SYMBOL_GPL(perf_event_read_value); static int __perf_read_group_add(struct perf_event *leader, u64 read_format, u64 *values) { struct perf_event *sub; int n = 1; /* skip @nr */ int ret; ret = perf_event_read(leader, true); if (ret) return ret; /* * Since we co-schedule groups, {enabled,running} times of siblings * will be identical to those of the leader, so we only publish one * set. */ if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { values[n++] += leader->total_time_enabled + atomic64_read(&leader->child_total_time_enabled); } if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { values[n++] += leader->total_time_running + atomic64_read(&leader->child_total_time_running); } /* * Write {count,id} tuples for every sibling. */ values[n++] += perf_event_count(leader); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(leader); list_for_each_entry(sub, &leader->sibling_list, group_entry) { values[n++] += perf_event_count(sub); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(sub); } return 0; } static int perf_read_group(struct perf_event *event, u64 read_format, char __user *buf) { struct perf_event *leader = event->group_leader, *child; struct perf_event_context *ctx = leader->ctx; int ret; u64 *values; lockdep_assert_held(&ctx->mutex); values = kzalloc(event->read_size, GFP_KERNEL); if (!values) return -ENOMEM; values[0] = 1 + leader->nr_siblings; /* * By locking the child_mutex of the leader we effectively * lock the child list of all siblings.. XXX explain how. */ mutex_lock(&leader->child_mutex); ret = __perf_read_group_add(leader, read_format, values); if (ret) goto unlock; list_for_each_entry(child, &leader->child_list, child_list) { ret = __perf_read_group_add(child, read_format, values); if (ret) goto unlock; } mutex_unlock(&leader->child_mutex); ret = event->read_size; if (copy_to_user(buf, values, event->read_size)) ret = -EFAULT; goto out; unlock: mutex_unlock(&leader->child_mutex); out: kfree(values); return ret; } static int perf_read_one(struct perf_event *event, u64 read_format, char __user *buf) { u64 enabled, running; u64 values[4]; int n = 0; values[n++] = perf_event_read_value(event, &enabled, &running); if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(event); if (copy_to_user(buf, values, n * sizeof(u64))) return -EFAULT; return n * sizeof(u64); } static bool is_event_hup(struct perf_event *event) { bool no_children; if (event->state > PERF_EVENT_STATE_EXIT) return false; mutex_lock(&event->child_mutex); no_children = list_empty(&event->child_list); mutex_unlock(&event->child_mutex); return no_children; } /* * Read the performance event - simple non blocking version for now */ static ssize_t __perf_read(struct perf_event *event, char __user *buf, size_t count) { u64 read_format = event->attr.read_format; int ret; /* * Return end-of-file for a read on a event that is in * error state (i.e. because it was pinned but it couldn't be * scheduled on to the CPU at some point). */ if (event->state == PERF_EVENT_STATE_ERROR) return 0; if (count < event->read_size) return -ENOSPC; WARN_ON_ONCE(event->ctx->parent_ctx); if (read_format & PERF_FORMAT_GROUP) ret = perf_read_group(event, read_format, buf); else ret = perf_read_one(event, read_format, buf); return ret; } static ssize_t perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct perf_event *event = file->private_data; struct perf_event_context *ctx; int ret; ctx = perf_event_ctx_lock(event); ret = __perf_read(event, buf, count); perf_event_ctx_unlock(event, ctx); return ret; } static unsigned int perf_poll(struct file *file, poll_table *wait) { struct perf_event *event = file->private_data; struct ring_buffer *rb; unsigned int events = POLLHUP; poll_wait(file, &event->waitq, wait); if (is_event_hup(event)) return events; /* * Pin the event->rb by taking event->mmap_mutex; otherwise * perf_event_set_output() can swizzle our rb and make us miss wakeups. */ mutex_lock(&event->mmap_mutex); rb = event->rb; if (rb) events = atomic_xchg(&rb->poll, 0); mutex_unlock(&event->mmap_mutex); return events; } static void _perf_event_reset(struct perf_event *event) { (void)perf_event_read(event, false); local64_set(&event->count, 0); perf_event_update_userpage(event); } /* * Holding the top-level event's child_mutex means that any * descendant process that has inherited this event will block * in perf_event_exit_event() if it goes to exit, thus satisfying the * task existence requirements of perf_event_enable/disable. */ static void perf_event_for_each_child(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event *child; WARN_ON_ONCE(event->ctx->parent_ctx); mutex_lock(&event->child_mutex); func(event); list_for_each_entry(child, &event->child_list, child_list) func(child); mutex_unlock(&event->child_mutex); } static void perf_event_for_each(struct perf_event *event, void (*func)(struct perf_event *)) { struct perf_event_context *ctx = event->ctx; struct perf_event *sibling; lockdep_assert_held(&ctx->mutex); event = event->group_leader; perf_event_for_each_child(event, func); list_for_each_entry(sibling, &event->sibling_list, group_entry) perf_event_for_each_child(sibling, func); } static void __perf_event_period(struct perf_event *event, struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, void *info) { u64 value = *((u64 *)info); bool active; if (event->attr.freq) { event->attr.sample_freq = value; } else { event->attr.sample_period = value; event->hw.sample_period = value; } active = (event->state == PERF_EVENT_STATE_ACTIVE); if (active) { perf_pmu_disable(ctx->pmu); /* * We could be throttled; unthrottle now to avoid the tick * trying to unthrottle while we already re-started the event. */ if (event->hw.interrupts == MAX_INTERRUPTS) { event->hw.interrupts = 0; perf_log_throttle(event, 1); } event->pmu->stop(event, PERF_EF_UPDATE); } local64_set(&event->hw.period_left, 0); if (active) { event->pmu->start(event, PERF_EF_RELOAD); perf_pmu_enable(ctx->pmu); } } static int perf_event_period(struct perf_event *event, u64 __user *arg) { u64 value; if (!is_sampling_event(event)) return -EINVAL; if (copy_from_user(&value, arg, sizeof(value))) return -EFAULT; if (!value) return -EINVAL; if (event->attr.freq && value > sysctl_perf_event_sample_rate) return -EINVAL; event_function_call(event, __perf_event_period, &value); return 0; } static const struct file_operations perf_fops; static inline int perf_fget_light(int fd, struct fd *p) { struct fd f = fdget(fd); if (!f.file) return -EBADF; if (f.file->f_op != &perf_fops) { fdput(f); return -EBADF; } *p = f; return 0; } static int perf_event_set_output(struct perf_event *event, struct perf_event *output_event); static int perf_event_set_filter(struct perf_event *event, void __user *arg); static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd); static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) { void (*func)(struct perf_event *); u32 flags = arg; switch (cmd) { case PERF_EVENT_IOC_ENABLE: func = _perf_event_enable; break; case PERF_EVENT_IOC_DISABLE: func = _perf_event_disable; break; case PERF_EVENT_IOC_RESET: func = _perf_event_reset; break; case PERF_EVENT_IOC_REFRESH: return _perf_event_refresh(event, arg); case PERF_EVENT_IOC_PERIOD: return perf_event_period(event, (u64 __user *)arg); case PERF_EVENT_IOC_ID: { u64 id = primary_event_id(event); if (copy_to_user((void __user *)arg, &id, sizeof(id))) return -EFAULT; return 0; } case PERF_EVENT_IOC_SET_OUTPUT: { int ret; if (arg != -1) { struct perf_event *output_event; struct fd output; ret = perf_fget_light(arg, &output); if (ret) return ret; output_event = output.file->private_data; ret = perf_event_set_output(event, output_event); fdput(output); } else { ret = perf_event_set_output(event, NULL); } return ret; } case PERF_EVENT_IOC_SET_FILTER: return perf_event_set_filter(event, (void __user *)arg); case PERF_EVENT_IOC_SET_BPF: return perf_event_set_bpf_prog(event, arg); case PERF_EVENT_IOC_PAUSE_OUTPUT: { struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb || !rb->nr_pages) { rcu_read_unlock(); return -EINVAL; } rb_toggle_paused(rb, !!arg); rcu_read_unlock(); return 0; } default: return -ENOTTY; } if (flags & PERF_IOC_FLAG_GROUP) perf_event_for_each(event, func); else perf_event_for_each_child(event, func); return 0; } static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct perf_event *event = file->private_data; struct perf_event_context *ctx; long ret; ctx = perf_event_ctx_lock(event); ret = _perf_ioctl(event, cmd, arg); perf_event_ctx_unlock(event, ctx); return ret; } #ifdef CONFIG_COMPAT static long perf_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (_IOC_NR(cmd)) { case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): case _IOC_NR(PERF_EVENT_IOC_ID): /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { cmd &= ~IOCSIZE_MASK; cmd |= sizeof(void *) << IOCSIZE_SHIFT; } break; } return perf_ioctl(file, cmd, arg); } #else # define perf_compat_ioctl NULL #endif int perf_event_task_enable(void) { struct perf_event_context *ctx; struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) { ctx = perf_event_ctx_lock(event); perf_event_for_each_child(event, _perf_event_enable); perf_event_ctx_unlock(event, ctx); } mutex_unlock(&current->perf_event_mutex); return 0; } int perf_event_task_disable(void) { struct perf_event_context *ctx; struct perf_event *event; mutex_lock(&current->perf_event_mutex); list_for_each_entry(event, &current->perf_event_list, owner_entry) { ctx = perf_event_ctx_lock(event); perf_event_for_each_child(event, _perf_event_disable); perf_event_ctx_unlock(event, ctx); } mutex_unlock(&current->perf_event_mutex); return 0; } static int perf_event_index(struct perf_event *event) { if (event->hw.state & PERF_HES_STOPPED) return 0; if (event->state != PERF_EVENT_STATE_ACTIVE) return 0; return event->pmu->event_idx(event); } static void calc_timer_values(struct perf_event *event, u64 *now, u64 *enabled, u64 *running) { u64 ctx_time; *now = perf_clock(); ctx_time = event->shadow_ctx_time + *now; *enabled = ctx_time - event->tstamp_enabled; *running = ctx_time - event->tstamp_running; } static void perf_event_init_userpage(struct perf_event *event) { struct perf_event_mmap_page *userpg; struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; userpg = rb->user_page; /* Allow new userspace to detect that bit 0 is deprecated */ userpg->cap_bit0_is_deprecated = 1; userpg->size = offsetof(struct perf_event_mmap_page, __reserved); userpg->data_offset = PAGE_SIZE; userpg->data_size = perf_data_size(rb); unlock: rcu_read_unlock(); } void __weak arch_perf_update_userpage( struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) { } /* * Callers need to ensure there can be no nesting of this function, otherwise * the seqlock logic goes bad. We can not serialize this because the arch * code calls this from NMI context. */ void perf_event_update_userpage(struct perf_event *event) { struct perf_event_mmap_page *userpg; struct ring_buffer *rb; u64 enabled, running, now; rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; /* * compute total_time_enabled, total_time_running * based on snapshot values taken when the event * was last scheduled in. * * we cannot simply called update_context_time() * because of locking issue as we can be called in * NMI context */ calc_timer_values(event, &now, &enabled, &running); userpg = rb->user_page; /* * Disable preemption so as to not let the corresponding user-space * spin too long if we get preempted. */ preempt_disable(); ++userpg->lock; barrier(); userpg->index = perf_event_index(event); userpg->offset = perf_event_count(event); if (userpg->index) userpg->offset -= local64_read(&event->hw.prev_count); userpg->time_enabled = enabled + atomic64_read(&event->child_total_time_enabled); userpg->time_running = running + atomic64_read(&event->child_total_time_running); arch_perf_update_userpage(event, userpg, now); barrier(); ++userpg->lock; preempt_enable(); unlock: rcu_read_unlock(); } static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct perf_event *event = vma->vm_file->private_data; struct ring_buffer *rb; int ret = VM_FAULT_SIGBUS; if (vmf->flags & FAULT_FLAG_MKWRITE) { if (vmf->pgoff == 0) ret = 0; return ret; } rcu_read_lock(); rb = rcu_dereference(event->rb); if (!rb) goto unlock; if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE)) goto unlock; vmf->page = perf_mmap_to_page(rb, vmf->pgoff); if (!vmf->page) goto unlock; get_page(vmf->page); vmf->page->mapping = vma->vm_file->f_mapping; vmf->page->index = vmf->pgoff; ret = 0; unlock: rcu_read_unlock(); return ret; } static void ring_buffer_attach(struct perf_event *event, struct ring_buffer *rb) { struct ring_buffer *old_rb = NULL; unsigned long flags; if (event->rb) { /* * Should be impossible, we set this when removing * event->rb_entry and wait/clear when adding event->rb_entry. */ WARN_ON_ONCE(event->rcu_pending); old_rb = event->rb; spin_lock_irqsave(&old_rb->event_lock, flags); list_del_rcu(&event->rb_entry); spin_unlock_irqrestore(&old_rb->event_lock, flags); event->rcu_batches = get_state_synchronize_rcu(); event->rcu_pending = 1; } if (rb) { if (event->rcu_pending) { cond_synchronize_rcu(event->rcu_batches); event->rcu_pending = 0; } spin_lock_irqsave(&rb->event_lock, flags); list_add_rcu(&event->rb_entry, &rb->event_list); spin_unlock_irqrestore(&rb->event_lock, flags); } /* * Avoid racing with perf_mmap_close(AUX): stop the event * before swizzling the event::rb pointer; if it's getting * unmapped, its aux_mmap_count will be 0 and it won't * restart. See the comment in __perf_pmu_output_stop(). * * Data will inevitably be lost when set_output is done in * mid-air, but then again, whoever does it like this is * not in for the data anyway. */ if (has_aux(event)) perf_event_stop(event, 0); rcu_assign_pointer(event->rb, rb); if (old_rb) { ring_buffer_put(old_rb); /* * Since we detached before setting the new rb, so that we * could attach the new rb, we could have missed a wakeup. * Provide it now. */ wake_up_all(&event->waitq); } } static void ring_buffer_wakeup(struct perf_event *event) { struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (rb) { list_for_each_entry_rcu(event, &rb->event_list, rb_entry) wake_up_all(&event->waitq); } rcu_read_unlock(); } struct ring_buffer *ring_buffer_get(struct perf_event *event) { struct ring_buffer *rb; rcu_read_lock(); rb = rcu_dereference(event->rb); if (rb) { if (!atomic_inc_not_zero(&rb->refcount)) rb = NULL; } rcu_read_unlock(); return rb; } void ring_buffer_put(struct ring_buffer *rb) { if (!atomic_dec_and_test(&rb->refcount)) return; WARN_ON_ONCE(!list_empty(&rb->event_list)); call_rcu(&rb->rcu_head, rb_free_rcu); } static void perf_mmap_open(struct vm_area_struct *vma) { struct perf_event *event = vma->vm_file->private_data; atomic_inc(&event->mmap_count); atomic_inc(&event->rb->mmap_count); if (vma->vm_pgoff) atomic_inc(&event->rb->aux_mmap_count); if (event->pmu->event_mapped) event->pmu->event_mapped(event); } static void perf_pmu_output_stop(struct perf_event *event); /* * A buffer can be mmap()ed multiple times; either directly through the same * event, or through other events by use of perf_event_set_output(). * * In order to undo the VM accounting done by perf_mmap() we need to destroy * the buffer here, where we still have a VM context. This means we need * to detach all events redirecting to us. */ static void perf_mmap_close(struct vm_area_struct *vma) { struct perf_event *event = vma->vm_file->private_data; struct ring_buffer *rb = ring_buffer_get(event); struct user_struct *mmap_user = rb->mmap_user; int mmap_locked = rb->mmap_locked; unsigned long size = perf_data_size(rb); if (event->pmu->event_unmapped) event->pmu->event_unmapped(event); /* * rb->aux_mmap_count will always drop before rb->mmap_count and * event->mmap_count, so it is ok to use event->mmap_mutex to * serialize with perf_mmap here. */ if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff && atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) { /* * Stop all AUX events that are writing to this buffer, * so that we can free its AUX pages and corresponding PMU * data. Note that after rb::aux_mmap_count dropped to zero, * they won't start any more (see perf_aux_output_begin()). */ perf_pmu_output_stop(event); /* now it's safe to free the pages */ atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm); vma->vm_mm->pinned_vm -= rb->aux_mmap_locked; /* this has to be the last one */ rb_free_aux(rb); WARN_ON_ONCE(atomic_read(&rb->aux_refcount)); mutex_unlock(&event->mmap_mutex); } atomic_dec(&rb->mmap_count); if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) goto out_put; ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); /* If there's still other mmap()s of this buffer, we're done. */ if (atomic_read(&rb->mmap_count)) goto out_put; /* * No other mmap()s, detach from all other events that might redirect * into the now unreachable buffer. Somewhat complicated by the * fact that rb::event_lock otherwise nests inside mmap_mutex. */ again: rcu_read_lock(); list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { if (!atomic_long_inc_not_zero(&event->refcount)) { /* * This event is en-route to free_event() which will * detach it and remove it from the list. */ continue; } rcu_read_unlock(); mutex_lock(&event->mmap_mutex); /* * Check we didn't race with perf_event_set_output() which can * swizzle the rb from under us while we were waiting to * acquire mmap_mutex. * * If we find a different rb; ignore this event, a next * iteration will no longer find it on the list. We have to * still restart the iteration to make sure we're not now * iterating the wrong list. */ if (event->rb == rb) ring_buffer_attach(event, NULL); mutex_unlock(&event->mmap_mutex); put_event(event); /* * Restart the iteration; either we're on the wrong list or * destroyed its integrity by doing a deletion. */ goto again; } rcu_read_unlock(); /* * It could be there's still a few 0-ref events on the list; they'll * get cleaned up by free_event() -- they'll also still have their * ref on the rb and will free it whenever they are done with it. * * Aside from that, this buffer is 'fully' detached and unmapped, * undo the VM accounting. */ atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm); vma->vm_mm->pinned_vm -= mmap_locked; free_uid(mmap_user); out_put: ring_buffer_put(rb); /* could be last */ } static const struct vm_operations_struct perf_mmap_vmops = { .open = perf_mmap_open, .close = perf_mmap_close, /* non mergable */ .fault = perf_mmap_fault, .page_mkwrite = perf_mmap_fault, }; static int perf_mmap(struct file *file, struct vm_area_struct *vma) { struct perf_event *event = file->private_data; unsigned long user_locked, user_lock_limit; struct user_struct *user = current_user(); unsigned long locked, lock_limit; struct ring_buffer *rb = NULL; unsigned long vma_size; unsigned long nr_pages; long user_extra = 0, extra = 0; int ret = 0, flags = 0; /* * Don't allow mmap() of inherited per-task counters. This would * create a performance issue due to all children writing to the * same rb. */ if (event->cpu == -1 && event->attr.inherit) return -EINVAL; if (!(vma->vm_flags & VM_SHARED)) return -EINVAL; vma_size = vma->vm_end - vma->vm_start; if (vma->vm_pgoff == 0) { nr_pages = (vma_size / PAGE_SIZE) - 1; } else { /* * AUX area mapping: if rb->aux_nr_pages != 0, it's already * mapped, all subsequent mappings should have the same size * and offset. Must be above the normal perf buffer. */ u64 aux_offset, aux_size; if (!event->rb) return -EINVAL; nr_pages = vma_size / PAGE_SIZE; mutex_lock(&event->mmap_mutex); ret = -EINVAL; rb = event->rb; if (!rb) goto aux_unlock; aux_offset = ACCESS_ONCE(rb->user_page->aux_offset); aux_size = ACCESS_ONCE(rb->user_page->aux_size); if (aux_offset < perf_data_size(rb) + PAGE_SIZE) goto aux_unlock; if (aux_offset != vma->vm_pgoff << PAGE_SHIFT) goto aux_unlock; /* already mapped with a different offset */ if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff) goto aux_unlock; if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE) goto aux_unlock; /* already mapped with a different size */ if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) goto aux_unlock; if (!is_power_of_2(nr_pages)) goto aux_unlock; if (!atomic_inc_not_zero(&rb->mmap_count)) goto aux_unlock; if (rb_has_aux(rb)) { atomic_inc(&rb->aux_mmap_count); ret = 0; goto unlock; } atomic_set(&rb->aux_mmap_count, 1); user_extra = nr_pages; goto accounting; } /* * If we have rb pages ensure they're a power-of-two number, so we * can do bitmasks instead of modulo. */ if (nr_pages != 0 && !is_power_of_2(nr_pages)) return -EINVAL; if (vma_size != PAGE_SIZE * (1 + nr_pages)) return -EINVAL; WARN_ON_ONCE(event->ctx->parent_ctx); again: mutex_lock(&event->mmap_mutex); if (event->rb) { if (event->rb->nr_pages != nr_pages) { ret = -EINVAL; goto unlock; } if (!atomic_inc_not_zero(&event->rb->mmap_count)) { /* * Raced against perf_mmap_close() through * perf_event_set_output(). Try again, hope for better * luck. */ mutex_unlock(&event->mmap_mutex); goto again; } goto unlock; } user_extra = nr_pages + 1; accounting: user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); /* * Increase the limit linearly with more CPUs: */ user_lock_limit *= num_online_cpus(); user_locked = atomic_long_read(&user->locked_vm) + user_extra; if (user_locked > user_lock_limit) extra = user_locked - user_lock_limit; lock_limit = rlimit(RLIMIT_MEMLOCK); lock_limit >>= PAGE_SHIFT; locked = vma->vm_mm->pinned_vm + extra; if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() && !capable(CAP_IPC_LOCK)) { ret = -EPERM; goto unlock; } WARN_ON(!rb && event->rb); if (vma->vm_flags & VM_WRITE) flags |= RING_BUFFER_WRITABLE; if (!rb) { rb = rb_alloc(nr_pages, event->attr.watermark ? event->attr.wakeup_watermark : 0, event->cpu, flags); if (!rb) { ret = -ENOMEM; goto unlock; } atomic_set(&rb->mmap_count, 1); rb->mmap_user = get_current_user(); rb->mmap_locked = extra; ring_buffer_attach(event, rb); perf_event_init_userpage(event); perf_event_update_userpage(event); } else { ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages, event->attr.aux_watermark, flags); if (!ret) rb->aux_mmap_locked = extra; } unlock: if (!ret) { atomic_long_add(user_extra, &user->locked_vm); vma->vm_mm->pinned_vm += extra; atomic_inc(&event->mmap_count); } else if (rb) { atomic_dec(&rb->mmap_count); } aux_unlock: mutex_unlock(&event->mmap_mutex); /* * Since pinned accounting is per vm we cannot allow fork() to copy our * vma. */ vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP; vma->vm_ops = &perf_mmap_vmops; if (event->pmu->event_mapped) event->pmu->event_mapped(event); return ret; } static int perf_fasync(int fd, struct file *filp, int on) { struct inode *inode = file_inode(filp); struct perf_event *event = filp->private_data; int retval; inode_lock(inode); retval = fasync_helper(fd, filp, on, &event->fasync); inode_unlock(inode); if (retval < 0) return retval; return 0; } static const struct file_operations perf_fops = { .llseek = no_llseek, .release = perf_release, .read = perf_read, .poll = perf_poll, .unlocked_ioctl = perf_ioctl, .compat_ioctl = perf_compat_ioctl, .mmap = perf_mmap, .fasync = perf_fasync, }; /* * Perf event wakeup * * If there's data, ensure we set the poll() state and publish everything * to user-space before waking everybody up. */ static inline struct fasync_struct **perf_event_fasync(struct perf_event *event) { /* only the parent has fasync state */ if (event->parent) event = event->parent; return &event->fasync; } void perf_event_wakeup(struct perf_event *event) { ring_buffer_wakeup(event); if (event->pending_kill) { kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); event->pending_kill = 0; } } static void perf_pending_event(struct irq_work *entry) { struct perf_event *event = container_of(entry, struct perf_event, pending); int rctx; rctx = perf_swevent_get_recursion_context(); /* * If we 'fail' here, that's OK, it means recursion is already disabled * and we won't recurse 'further'. */ if (event->pending_disable) { event->pending_disable = 0; perf_event_disable_local(event); } if (event->pending_wakeup) { event->pending_wakeup = 0; perf_event_wakeup(event); } if (rctx >= 0) perf_swevent_put_recursion_context(rctx); } /* * We assume there is only KVM supporting the callbacks. * Later on, we might change it to a list if there is * another virtualization implementation supporting the callbacks. */ struct perf_guest_info_callbacks *perf_guest_cbs; int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) { perf_guest_cbs = cbs; return 0; } EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) { perf_guest_cbs = NULL; return 0; } EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); static void perf_output_sample_regs(struct perf_output_handle *handle, struct pt_regs *regs, u64 mask) { int bit; DECLARE_BITMAP(_mask, 64); bitmap_from_u64(_mask, mask); for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { u64 val; val = perf_reg_value(regs, bit); perf_output_put(handle, val); } } static void perf_sample_regs_user(struct perf_regs *regs_user, struct pt_regs *regs, struct pt_regs *regs_user_copy) { if (user_mode(regs)) { regs_user->abi = perf_reg_abi(current); regs_user->regs = regs; } else if (current->mm) { perf_get_regs_user(regs_user, regs, regs_user_copy); } else { regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; regs_user->regs = NULL; } } static void perf_sample_regs_intr(struct perf_regs *regs_intr, struct pt_regs *regs) { regs_intr->regs = regs; regs_intr->abi = perf_reg_abi(current); } /* * Get remaining task size from user stack pointer. * * It'd be better to take stack vma map and limit this more * precisly, but there's no way to get it safely under interrupt, * so using TASK_SIZE as limit. */ static u64 perf_ustack_task_size(struct pt_regs *regs) { unsigned long addr = perf_user_stack_pointer(regs); if (!addr || addr >= TASK_SIZE) return 0; return TASK_SIZE - addr; } static u16 perf_sample_ustack_size(u16 stack_size, u16 header_size, struct pt_regs *regs) { u64 task_size; /* No regs, no stack pointer, no dump. */ if (!regs) return 0; /* * Check if we fit in with the requested stack size into the: * - TASK_SIZE * If we don't, we limit the size to the TASK_SIZE. * * - remaining sample size * If we don't, we customize the stack size to * fit in to the remaining sample size. */ task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); stack_size = min(stack_size, (u16) task_size); /* Current header size plus static size and dynamic size. */ header_size += 2 * sizeof(u64); /* Do we fit in with the current stack dump size? */ if ((u16) (header_size + stack_size) < header_size) { /* * If we overflow the maximum size for the sample, * we customize the stack dump size to fit in. */ stack_size = USHRT_MAX - header_size - sizeof(u64); stack_size = round_up(stack_size, sizeof(u64)); } return stack_size; } static void perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, struct pt_regs *regs) { /* Case of a kernel thread, nothing to dump */ if (!regs) { u64 size = 0; perf_output_put(handle, size); } else { unsigned long sp; unsigned int rem; u64 dyn_size; /* * We dump: * static size * - the size requested by user or the best one we can fit * in to the sample max size * data * - user stack dump data * dynamic size * - the actual dumped size */ /* Static size. */ perf_output_put(handle, dump_size); /* Data. */ sp = perf_user_stack_pointer(regs); rem = __output_copy_user(handle, (void *) sp, dump_size); dyn_size = dump_size - rem; perf_output_skip(handle, rem); /* Dynamic size. */ perf_output_put(handle, dyn_size); } } static void __perf_event_header__init_id(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { u64 sample_type = event->attr.sample_type; data->type = sample_type; header->size += event->id_header_size; if (sample_type & PERF_SAMPLE_TID) { /* namespace issues */ data->tid_entry.pid = perf_event_pid(event, current); data->tid_entry.tid = perf_event_tid(event, current); } if (sample_type & PERF_SAMPLE_TIME) data->time = perf_event_clock(event); if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) data->id = primary_event_id(event); if (sample_type & PERF_SAMPLE_STREAM_ID) data->stream_id = event->id; if (sample_type & PERF_SAMPLE_CPU) { data->cpu_entry.cpu = raw_smp_processor_id(); data->cpu_entry.reserved = 0; } } void perf_event_header__init_id(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { if (event->attr.sample_id_all) __perf_event_header__init_id(header, data, event); } static void __perf_event__output_id_sample(struct perf_output_handle *handle, struct perf_sample_data *data) { u64 sample_type = data->type; if (sample_type & PERF_SAMPLE_TID) perf_output_put(handle, data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) perf_output_put(handle, data->time); if (sample_type & PERF_SAMPLE_ID) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) perf_output_put(handle, data->stream_id); if (sample_type & PERF_SAMPLE_CPU) perf_output_put(handle, data->cpu_entry); if (sample_type & PERF_SAMPLE_IDENTIFIER) perf_output_put(handle, data->id); } void perf_event__output_id_sample(struct perf_event *event, struct perf_output_handle *handle, struct perf_sample_data *sample) { if (event->attr.sample_id_all) __perf_event__output_id_sample(handle, sample); } static void perf_output_read_one(struct perf_output_handle *handle, struct perf_event *event, u64 enabled, u64 running) { u64 read_format = event->attr.read_format; u64 values[4]; int n = 0; values[n++] = perf_event_count(event); if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { values[n++] = enabled + atomic64_read(&event->child_total_time_enabled); } if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { values[n++] = running + atomic64_read(&event->child_total_time_running); } if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(event); __output_copy(handle, values, n * sizeof(u64)); } /* * XXX PERF_FORMAT_GROUP vs inherited events seems difficult. */ static void perf_output_read_group(struct perf_output_handle *handle, struct perf_event *event, u64 enabled, u64 running) { struct perf_event *leader = event->group_leader, *sub; u64 read_format = event->attr.read_format; u64 values[5]; int n = 0; values[n++] = 1 + leader->nr_siblings; if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) values[n++] = enabled; if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) values[n++] = running; if (leader != event) leader->pmu->read(leader); values[n++] = perf_event_count(leader); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(leader); __output_copy(handle, values, n * sizeof(u64)); list_for_each_entry(sub, &leader->sibling_list, group_entry) { n = 0; if ((sub != event) && (sub->state == PERF_EVENT_STATE_ACTIVE)) sub->pmu->read(sub); values[n++] = perf_event_count(sub); if (read_format & PERF_FORMAT_ID) values[n++] = primary_event_id(sub); __output_copy(handle, values, n * sizeof(u64)); } } #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ PERF_FORMAT_TOTAL_TIME_RUNNING) static void perf_output_read(struct perf_output_handle *handle, struct perf_event *event) { u64 enabled = 0, running = 0, now; u64 read_format = event->attr.read_format; /* * compute total_time_enabled, total_time_running * based on snapshot values taken when the event * was last scheduled in. * * we cannot simply called update_context_time() * because of locking issue as we are called in * NMI context */ if (read_format & PERF_FORMAT_TOTAL_TIMES) calc_timer_values(event, &now, &enabled, &running); if (event->attr.read_format & PERF_FORMAT_GROUP) perf_output_read_group(handle, event, enabled, running); else perf_output_read_one(handle, event, enabled, running); } void perf_output_sample(struct perf_output_handle *handle, struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event) { u64 sample_type = data->type; perf_output_put(handle, *header); if (sample_type & PERF_SAMPLE_IDENTIFIER) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_IP) perf_output_put(handle, data->ip); if (sample_type & PERF_SAMPLE_TID) perf_output_put(handle, data->tid_entry); if (sample_type & PERF_SAMPLE_TIME) perf_output_put(handle, data->time); if (sample_type & PERF_SAMPLE_ADDR) perf_output_put(handle, data->addr); if (sample_type & PERF_SAMPLE_ID) perf_output_put(handle, data->id); if (sample_type & PERF_SAMPLE_STREAM_ID) perf_output_put(handle, data->stream_id); if (sample_type & PERF_SAMPLE_CPU) perf_output_put(handle, data->cpu_entry); if (sample_type & PERF_SAMPLE_PERIOD) perf_output_put(handle, data->period); if (sample_type & PERF_SAMPLE_READ) perf_output_read(handle, event); if (sample_type & PERF_SAMPLE_CALLCHAIN) { if (data->callchain) { int size = 1; if (data->callchain) size += data->callchain->nr; size *= sizeof(u64); __output_copy(handle, data->callchain, size); } else { u64 nr = 0; perf_output_put(handle, nr); } } if (sample_type & PERF_SAMPLE_RAW) { struct perf_raw_record *raw = data->raw; if (raw) { struct perf_raw_frag *frag = &raw->frag; perf_output_put(handle, raw->size); do { if (frag->copy) { __output_custom(handle, frag->copy, frag->data, frag->size); } else { __output_copy(handle, frag->data, frag->size); } if (perf_raw_frag_last(frag)) break; frag = frag->next; } while (1); if (frag->pad) __output_skip(handle, NULL, frag->pad); } else { struct { u32 size; u32 data; } raw = { .size = sizeof(u32), .data = 0, }; perf_output_put(handle, raw); } } if (sample_type & PERF_SAMPLE_BRANCH_STACK) { if (data->br_stack) { size_t size; size = data->br_stack->nr * sizeof(struct perf_branch_entry); perf_output_put(handle, data->br_stack->nr); perf_output_copy(handle, data->br_stack->entries, size); } else { /* * we always store at least the value of nr */ u64 nr = 0; perf_output_put(handle, nr); } } if (sample_type & PERF_SAMPLE_REGS_USER) { u64 abi = data->regs_user.abi; /* * If there are no regs to dump, notice it through * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). */ perf_output_put(handle, abi); if (abi) { u64 mask = event->attr.sample_regs_user; perf_output_sample_regs(handle, data->regs_user.regs, mask); } } if (sample_type & PERF_SAMPLE_STACK_USER) { perf_output_sample_ustack(handle, data->stack_user_size, data->regs_user.regs); } if (sample_type & PERF_SAMPLE_WEIGHT) perf_output_put(handle, data->weight); if (sample_type & PERF_SAMPLE_DATA_SRC) perf_output_put(handle, data->data_src.val); if (sample_type & PERF_SAMPLE_TRANSACTION) perf_output_put(handle, data->txn); if (sample_type & PERF_SAMPLE_REGS_INTR) { u64 abi = data->regs_intr.abi; /* * If there are no regs to dump, notice it through * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). */ perf_output_put(handle, abi); if (abi) { u64 mask = event->attr.sample_regs_intr; perf_output_sample_regs(handle, data->regs_intr.regs, mask); } } if (!event->attr.watermark) { int wakeup_events = event->attr.wakeup_events; if (wakeup_events) { struct ring_buffer *rb = handle->rb; int events = local_inc_return(&rb->events); if (events >= wakeup_events) { local_sub(wakeup_events, &rb->events); local_inc(&rb->wakeup); } } } } void perf_prepare_sample(struct perf_event_header *header, struct perf_sample_data *data, struct perf_event *event, struct pt_regs *regs) { u64 sample_type = event->attr.sample_type; header->type = PERF_RECORD_SAMPLE; header->size = sizeof(*header) + event->header_size; header->misc = 0; header->misc |= perf_misc_flags(regs); __perf_event_header__init_id(header, data, event); if (sample_type & PERF_SAMPLE_IP) data->ip = perf_instruction_pointer(regs); if (sample_type & PERF_SAMPLE_CALLCHAIN) { int size = 1; data->callchain = perf_callchain(event, regs); if (data->callchain) size += data->callchain->nr; header->size += size * sizeof(u64); } if (sample_type & PERF_SAMPLE_RAW) { struct perf_raw_record *raw = data->raw; int size; if (raw) { struct perf_raw_frag *frag = &raw->frag; u32 sum = 0; do { sum += frag->size; if (perf_raw_frag_last(frag)) break; frag = frag->next; } while (1); size = round_up(sum + sizeof(u32), sizeof(u64)); raw->size = size - sizeof(u32); frag->pad = raw->size - sum; } else { size = sizeof(u64); } header->size += size; } if (sample_type & PERF_SAMPLE_BRANCH_STACK) { int size = sizeof(u64); /* nr */ if (data->br_stack) { size += data->br_stack->nr * sizeof(struct perf_branch_entry); } header->size += size; } if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER)) perf_sample_regs_user(&data->regs_user, regs, &data->regs_user_copy); if (sample_type & PERF_SAMPLE_REGS_USER) { /* regs dump ABI info */ int size = sizeof(u64); if (data->regs_user.regs) { u64 mask = event->attr.sample_regs_user; size += hweight64(mask) * sizeof(u64); } header->size += size; } if (sample_type & PERF_SAMPLE_STACK_USER) { /* * Either we need PERF_SAMPLE_STACK_USER bit to be allways * processed as the last one or have additional check added * in case new sample type is added, because we could eat * up the rest of the sample size. */ u16 stack_size = event->attr.sample_stack_user; u16 size = sizeof(u64); stack_size = perf_sample_ustack_size(stack_size, header->size, data->regs_user.regs); /* * If there is something to dump, add space for the dump * itself and for the field that tells the dynamic size, * which is how many have been actually dumped. */ if (stack_size) size += sizeof(u64) + stack_size; data->stack_user_size = stack_size; header->size += size; } if (sample_type & PERF_SAMPLE_REGS_INTR) { /* regs dump ABI info */ int size = sizeof(u64); perf_sample_regs_intr(&data->regs_intr, regs); if (data->regs_intr.regs) { u64 mask = event->attr.sample_regs_intr; size += hweight64(mask) * sizeof(u64); } header->size += size; } } static void __always_inline __perf_event_output(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs, int (*output_begin)(struct perf_output_handle *, struct perf_event *, unsigned int)) { struct perf_output_handle handle; struct perf_event_header header; /* protect the callchain buffers */ rcu_read_lock(); perf_prepare_sample(&header, data, event, regs); if (output_begin(&handle, event, header.size)) goto exit; perf_output_sample(&handle, &header, data, event); perf_output_end(&handle); exit: rcu_read_unlock(); } void perf_event_output_forward(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { __perf_event_output(event, data, regs, perf_output_begin_forward); } void perf_event_output_backward(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { __perf_event_output(event, data, regs, perf_output_begin_backward); } void perf_event_output(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { __perf_event_output(event, data, regs, perf_output_begin); } /* * read event_id */ struct perf_read_event { struct perf_event_header header; u32 pid; u32 tid; }; static void perf_event_read_event(struct perf_event *event, struct task_struct *task) { struct perf_output_handle handle; struct perf_sample_data sample; struct perf_read_event read_event = { .header = { .type = PERF_RECORD_READ, .misc = 0, .size = sizeof(read_event) + event->read_size, }, .pid = perf_event_pid(event, task), .tid = perf_event_tid(event, task), }; int ret; perf_event_header__init_id(&read_event.header, &sample, event); ret = perf_output_begin(&handle, event, read_event.header.size); if (ret) return; perf_output_put(&handle, read_event); perf_output_read(&handle, event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } typedef void (perf_iterate_f)(struct perf_event *event, void *data); static void perf_iterate_ctx(struct perf_event_context *ctx, perf_iterate_f output, void *data, bool all) { struct perf_event *event; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (!all) { if (event->state < PERF_EVENT_STATE_INACTIVE) continue; if (!event_filter_match(event)) continue; } output(event, data); } } static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) { struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); struct perf_event *event; list_for_each_entry_rcu(event, &pel->list, sb_list) { /* * Skip events that are not fully formed yet; ensure that * if we observe event->ctx, both event and ctx will be * complete enough. See perf_install_in_context(). */ if (!smp_load_acquire(&event->ctx)) continue; if (event->state < PERF_EVENT_STATE_INACTIVE) continue; if (!event_filter_match(event)) continue; output(event, data); } } /* * Iterate all events that need to receive side-band events. * * For new callers; ensure that account_pmu_sb_event() includes * your event, otherwise it might not get delivered. */ static void perf_iterate_sb(perf_iterate_f output, void *data, struct perf_event_context *task_ctx) { struct perf_event_context *ctx; int ctxn; rcu_read_lock(); preempt_disable(); /* * If we have task_ctx != NULL we only notify the task context itself. * The task_ctx is set only for EXIT events before releasing task * context. */ if (task_ctx) { perf_iterate_ctx(task_ctx, output, data, false); goto done; } perf_iterate_sb_cpu(output, data); for_each_task_context_nr(ctxn) { ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); if (ctx) perf_iterate_ctx(ctx, output, data, false); } done: preempt_enable(); rcu_read_unlock(); } /* * Clear all file-based filters at exec, they'll have to be * re-instated when/if these objects are mmapped again. */ static void perf_event_addr_filters_exec(struct perf_event *event, void *data) { struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); struct perf_addr_filter *filter; unsigned int restart = 0, count = 0; unsigned long flags; if (!has_addr_filter(event)) return; raw_spin_lock_irqsave(&ifh->lock, flags); list_for_each_entry(filter, &ifh->list, entry) { if (filter->inode) { event->addr_filters_offs[count] = 0; restart++; } count++; } if (restart) event->addr_filters_gen++; raw_spin_unlock_irqrestore(&ifh->lock, flags); if (restart) perf_event_stop(event, 1); } void perf_event_exec(void) { struct perf_event_context *ctx; int ctxn; rcu_read_lock(); for_each_task_context_nr(ctxn) { ctx = current->perf_event_ctxp[ctxn]; if (!ctx) continue; perf_event_enable_on_exec(ctxn); perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); } rcu_read_unlock(); } struct remote_output { struct ring_buffer *rb; int err; }; static void __perf_event_output_stop(struct perf_event *event, void *data) { struct perf_event *parent = event->parent; struct remote_output *ro = data; struct ring_buffer *rb = ro->rb; struct stop_event_data sd = { .event = event, }; if (!has_aux(event)) return; if (!parent) parent = event; /* * In case of inheritance, it will be the parent that links to the * ring-buffer, but it will be the child that's actually using it. * * We are using event::rb to determine if the event should be stopped, * however this may race with ring_buffer_attach() (through set_output), * which will make us skip the event that actually needs to be stopped. * So ring_buffer_attach() has to stop an aux event before re-assigning * its rb pointer. */ if (rcu_dereference(parent->rb) == rb) ro->err = __perf_event_stop(&sd); } static int __perf_pmu_output_stop(void *info) { struct perf_event *event = info; struct pmu *pmu = event->pmu; struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); struct remote_output ro = { .rb = event->rb, }; rcu_read_lock(); perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); if (cpuctx->task_ctx) perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, &ro, false); rcu_read_unlock(); return ro.err; } static void perf_pmu_output_stop(struct perf_event *event) { struct perf_event *iter; int err, cpu; restart: rcu_read_lock(); list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { /* * For per-CPU events, we need to make sure that neither they * nor their children are running; for cpu==-1 events it's * sufficient to stop the event itself if it's active, since * it can't have children. */ cpu = iter->cpu; if (cpu == -1) cpu = READ_ONCE(iter->oncpu); if (cpu == -1) continue; err = cpu_function_call(cpu, __perf_pmu_output_stop, event); if (err == -EAGAIN) { rcu_read_unlock(); goto restart; } } rcu_read_unlock(); } /* * task tracking -- fork/exit * * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task */ struct perf_task_event { struct task_struct *task; struct perf_event_context *task_ctx; struct { struct perf_event_header header; u32 pid; u32 ppid; u32 tid; u32 ptid; u64 time; } event_id; }; static int perf_event_task_match(struct perf_event *event) { return event->attr.comm || event->attr.mmap || event->attr.mmap2 || event->attr.mmap_data || event->attr.task; } static void perf_event_task_output(struct perf_event *event, void *data) { struct perf_task_event *task_event = data; struct perf_output_handle handle; struct perf_sample_data sample; struct task_struct *task = task_event->task; int ret, size = task_event->event_id.header.size; if (!perf_event_task_match(event)) return; perf_event_header__init_id(&task_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, task_event->event_id.header.size); if (ret) goto out; task_event->event_id.pid = perf_event_pid(event, task); task_event->event_id.ppid = perf_event_pid(event, current); task_event->event_id.tid = perf_event_tid(event, task); task_event->event_id.ptid = perf_event_tid(event, current); task_event->event_id.time = perf_event_clock(event); perf_output_put(&handle, task_event->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: task_event->event_id.header.size = size; } static void perf_event_task(struct task_struct *task, struct perf_event_context *task_ctx, int new) { struct perf_task_event task_event; if (!atomic_read(&nr_comm_events) && !atomic_read(&nr_mmap_events) && !atomic_read(&nr_task_events)) return; task_event = (struct perf_task_event){ .task = task, .task_ctx = task_ctx, .event_id = { .header = { .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, .misc = 0, .size = sizeof(task_event.event_id), }, /* .pid */ /* .ppid */ /* .tid */ /* .ptid */ /* .time */ }, }; perf_iterate_sb(perf_event_task_output, &task_event, task_ctx); } void perf_event_fork(struct task_struct *task) { perf_event_task(task, NULL, 1); } /* * comm tracking */ struct perf_comm_event { struct task_struct *task; char *comm; int comm_size; struct { struct perf_event_header header; u32 pid; u32 tid; } event_id; }; static int perf_event_comm_match(struct perf_event *event) { return event->attr.comm; } static void perf_event_comm_output(struct perf_event *event, void *data) { struct perf_comm_event *comm_event = data; struct perf_output_handle handle; struct perf_sample_data sample; int size = comm_event->event_id.header.size; int ret; if (!perf_event_comm_match(event)) return; perf_event_header__init_id(&comm_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, comm_event->event_id.header.size); if (ret) goto out; comm_event->event_id.pid = perf_event_pid(event, comm_event->task); comm_event->event_id.tid = perf_event_tid(event, comm_event->task); perf_output_put(&handle, comm_event->event_id); __output_copy(&handle, comm_event->comm, comm_event->comm_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: comm_event->event_id.header.size = size; } static void perf_event_comm_event(struct perf_comm_event *comm_event) { char comm[TASK_COMM_LEN]; unsigned int size; memset(comm, 0, sizeof(comm)); strlcpy(comm, comm_event->task->comm, sizeof(comm)); size = ALIGN(strlen(comm)+1, sizeof(u64)); comm_event->comm = comm; comm_event->comm_size = size; comm_event->event_id.header.size = sizeof(comm_event->event_id) + size; perf_iterate_sb(perf_event_comm_output, comm_event, NULL); } void perf_event_comm(struct task_struct *task, bool exec) { struct perf_comm_event comm_event; if (!atomic_read(&nr_comm_events)) return; comm_event = (struct perf_comm_event){ .task = task, /* .comm */ /* .comm_size */ .event_id = { .header = { .type = PERF_RECORD_COMM, .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0, /* .size */ }, /* .pid */ /* .tid */ }, }; perf_event_comm_event(&comm_event); } /* * mmap tracking */ struct perf_mmap_event { struct vm_area_struct *vma; const char *file_name; int file_size; int maj, min; u64 ino; u64 ino_generation; u32 prot, flags; struct { struct perf_event_header header; u32 pid; u32 tid; u64 start; u64 len; u64 pgoff; } event_id; }; static int perf_event_mmap_match(struct perf_event *event, void *data) { struct perf_mmap_event *mmap_event = data; struct vm_area_struct *vma = mmap_event->vma; int executable = vma->vm_flags & VM_EXEC; return (!executable && event->attr.mmap_data) || (executable && (event->attr.mmap || event->attr.mmap2)); } static void perf_event_mmap_output(struct perf_event *event, void *data) { struct perf_mmap_event *mmap_event = data; struct perf_output_handle handle; struct perf_sample_data sample; int size = mmap_event->event_id.header.size; int ret; if (!perf_event_mmap_match(event, data)) return; if (event->attr.mmap2) { mmap_event->event_id.header.type = PERF_RECORD_MMAP2; mmap_event->event_id.header.size += sizeof(mmap_event->maj); mmap_event->event_id.header.size += sizeof(mmap_event->min); mmap_event->event_id.header.size += sizeof(mmap_event->ino); mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation); mmap_event->event_id.header.size += sizeof(mmap_event->prot); mmap_event->event_id.header.size += sizeof(mmap_event->flags); } perf_event_header__init_id(&mmap_event->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, mmap_event->event_id.header.size); if (ret) goto out; mmap_event->event_id.pid = perf_event_pid(event, current); mmap_event->event_id.tid = perf_event_tid(event, current); perf_output_put(&handle, mmap_event->event_id); if (event->attr.mmap2) { perf_output_put(&handle, mmap_event->maj); perf_output_put(&handle, mmap_event->min); perf_output_put(&handle, mmap_event->ino); perf_output_put(&handle, mmap_event->ino_generation); perf_output_put(&handle, mmap_event->prot); perf_output_put(&handle, mmap_event->flags); } __output_copy(&handle, mmap_event->file_name, mmap_event->file_size); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); out: mmap_event->event_id.header.size = size; } static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) { struct vm_area_struct *vma = mmap_event->vma; struct file *file = vma->vm_file; int maj = 0, min = 0; u64 ino = 0, gen = 0; u32 prot = 0, flags = 0; unsigned int size; char tmp[16]; char *buf = NULL; char *name; if (vma->vm_flags & VM_READ) prot |= PROT_READ; if (vma->vm_flags & VM_WRITE) prot |= PROT_WRITE; if (vma->vm_flags & VM_EXEC) prot |= PROT_EXEC; if (vma->vm_flags & VM_MAYSHARE) flags = MAP_SHARED; else flags = MAP_PRIVATE; if (vma->vm_flags & VM_DENYWRITE) flags |= MAP_DENYWRITE; if (vma->vm_flags & VM_MAYEXEC) flags |= MAP_EXECUTABLE; if (vma->vm_flags & VM_LOCKED) flags |= MAP_LOCKED; if (vma->vm_flags & VM_HUGETLB) flags |= MAP_HUGETLB; if (file) { struct inode *inode; dev_t dev; buf = kmalloc(PATH_MAX, GFP_KERNEL); if (!buf) { name = "//enomem"; goto cpy_name; } /* * d_path() works from the end of the rb backwards, so we * need to add enough zero bytes after the string to handle * the 64bit alignment we do later. */ name = file_path(file, buf, PATH_MAX - sizeof(u64)); if (IS_ERR(name)) { name = "//toolong"; goto cpy_name; } inode = file_inode(vma->vm_file); dev = inode->i_sb->s_dev; ino = inode->i_ino; gen = inode->i_generation; maj = MAJOR(dev); min = MINOR(dev); goto got_name; } else { if (vma->vm_ops && vma->vm_ops->name) { name = (char *) vma->vm_ops->name(vma); if (name) goto cpy_name; } name = (char *)arch_vma_name(vma); if (name) goto cpy_name; if (vma->vm_start <= vma->vm_mm->start_brk && vma->vm_end >= vma->vm_mm->brk) { name = "[heap]"; goto cpy_name; } if (vma->vm_start <= vma->vm_mm->start_stack && vma->vm_end >= vma->vm_mm->start_stack) { name = "[stack]"; goto cpy_name; } name = "//anon"; goto cpy_name; } cpy_name: strlcpy(tmp, name, sizeof(tmp)); name = tmp; got_name: /* * Since our buffer works in 8 byte units we need to align our string * size to a multiple of 8. However, we must guarantee the tail end is * zero'd out to avoid leaking random bits to userspace. */ size = strlen(name)+1; while (!IS_ALIGNED(size, sizeof(u64))) name[size++] = '\0'; mmap_event->file_name = name; mmap_event->file_size = size; mmap_event->maj = maj; mmap_event->min = min; mmap_event->ino = ino; mmap_event->ino_generation = gen; mmap_event->prot = prot; mmap_event->flags = flags; if (!(vma->vm_flags & VM_EXEC)) mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA; mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size; perf_iterate_sb(perf_event_mmap_output, mmap_event, NULL); kfree(buf); } /* * Check whether inode and address range match filter criteria. */ static bool perf_addr_filter_match(struct perf_addr_filter *filter, struct file *file, unsigned long offset, unsigned long size) { if (filter->inode != file_inode(file)) return false; if (filter->offset > offset + size) return false; if (filter->offset + filter->size < offset) return false; return true; } static void __perf_addr_filters_adjust(struct perf_event *event, void *data) { struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); struct vm_area_struct *vma = data; unsigned long off = vma->vm_pgoff << PAGE_SHIFT, flags; struct file *file = vma->vm_file; struct perf_addr_filter *filter; unsigned int restart = 0, count = 0; if (!has_addr_filter(event)) return; if (!file) return; raw_spin_lock_irqsave(&ifh->lock, flags); list_for_each_entry(filter, &ifh->list, entry) { if (perf_addr_filter_match(filter, file, off, vma->vm_end - vma->vm_start)) { event->addr_filters_offs[count] = vma->vm_start; restart++; } count++; } if (restart) event->addr_filters_gen++; raw_spin_unlock_irqrestore(&ifh->lock, flags); if (restart) perf_event_stop(event, 1); } /* * Adjust all task's events' filters to the new vma */ static void perf_addr_filters_adjust(struct vm_area_struct *vma) { struct perf_event_context *ctx; int ctxn; /* * Data tracing isn't supported yet and as such there is no need * to keep track of anything that isn't related to executable code: */ if (!(vma->vm_flags & VM_EXEC)) return; rcu_read_lock(); for_each_task_context_nr(ctxn) { ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); if (!ctx) continue; perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); } rcu_read_unlock(); } void perf_event_mmap(struct vm_area_struct *vma) { struct perf_mmap_event mmap_event; if (!atomic_read(&nr_mmap_events)) return; mmap_event = (struct perf_mmap_event){ .vma = vma, /* .file_name */ /* .file_size */ .event_id = { .header = { .type = PERF_RECORD_MMAP, .misc = PERF_RECORD_MISC_USER, /* .size */ }, /* .pid */ /* .tid */ .start = vma->vm_start, .len = vma->vm_end - vma->vm_start, .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT, }, /* .maj (attr_mmap2 only) */ /* .min (attr_mmap2 only) */ /* .ino (attr_mmap2 only) */ /* .ino_generation (attr_mmap2 only) */ /* .prot (attr_mmap2 only) */ /* .flags (attr_mmap2 only) */ }; perf_addr_filters_adjust(vma); perf_event_mmap_event(&mmap_event); } void perf_event_aux_event(struct perf_event *event, unsigned long head, unsigned long size, u64 flags) { struct perf_output_handle handle; struct perf_sample_data sample; struct perf_aux_event { struct perf_event_header header; u64 offset; u64 size; u64 flags; } rec = { .header = { .type = PERF_RECORD_AUX, .misc = 0, .size = sizeof(rec), }, .offset = head, .size = size, .flags = flags, }; int ret; perf_event_header__init_id(&rec.header, &sample, event); ret = perf_output_begin(&handle, event, rec.header.size); if (ret) return; perf_output_put(&handle, rec); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } /* * Lost/dropped samples logging */ void perf_log_lost_samples(struct perf_event *event, u64 lost) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 lost; } lost_samples_event = { .header = { .type = PERF_RECORD_LOST_SAMPLES, .misc = 0, .size = sizeof(lost_samples_event), }, .lost = lost, }; perf_event_header__init_id(&lost_samples_event.header, &sample, event); ret = perf_output_begin(&handle, event, lost_samples_event.header.size); if (ret) return; perf_output_put(&handle, lost_samples_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } /* * context_switch tracking */ struct perf_switch_event { struct task_struct *task; struct task_struct *next_prev; struct { struct perf_event_header header; u32 next_prev_pid; u32 next_prev_tid; } event_id; }; static int perf_event_switch_match(struct perf_event *event) { return event->attr.context_switch; } static void perf_event_switch_output(struct perf_event *event, void *data) { struct perf_switch_event *se = data; struct perf_output_handle handle; struct perf_sample_data sample; int ret; if (!perf_event_switch_match(event)) return; /* Only CPU-wide events are allowed to see next/prev pid/tid */ if (event->ctx->task) { se->event_id.header.type = PERF_RECORD_SWITCH; se->event_id.header.size = sizeof(se->event_id.header); } else { se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE; se->event_id.header.size = sizeof(se->event_id); se->event_id.next_prev_pid = perf_event_pid(event, se->next_prev); se->event_id.next_prev_tid = perf_event_tid(event, se->next_prev); } perf_event_header__init_id(&se->event_id.header, &sample, event); ret = perf_output_begin(&handle, event, se->event_id.header.size); if (ret) return; if (event->ctx->task) perf_output_put(&handle, se->event_id.header); else perf_output_put(&handle, se->event_id); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } static void perf_event_switch(struct task_struct *task, struct task_struct *next_prev, bool sched_in) { struct perf_switch_event switch_event; /* N.B. caller checks nr_switch_events != 0 */ switch_event = (struct perf_switch_event){ .task = task, .next_prev = next_prev, .event_id = { .header = { /* .type */ .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT, /* .size */ }, /* .next_prev_pid */ /* .next_prev_tid */ }, }; perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); } /* * IRQ throttle logging */ static void perf_log_throttle(struct perf_event *event, int enable) { struct perf_output_handle handle; struct perf_sample_data sample; int ret; struct { struct perf_event_header header; u64 time; u64 id; u64 stream_id; } throttle_event = { .header = { .type = PERF_RECORD_THROTTLE, .misc = 0, .size = sizeof(throttle_event), }, .time = perf_event_clock(event), .id = primary_event_id(event), .stream_id = event->id, }; if (enable) throttle_event.header.type = PERF_RECORD_UNTHROTTLE; perf_event_header__init_id(&throttle_event.header, &sample, event); ret = perf_output_begin(&handle, event, throttle_event.header.size); if (ret) return; perf_output_put(&handle, throttle_event); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } static void perf_log_itrace_start(struct perf_event *event) { struct perf_output_handle handle; struct perf_sample_data sample; struct perf_aux_event { struct perf_event_header header; u32 pid; u32 tid; } rec; int ret; if (event->parent) event = event->parent; if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || event->hw.itrace_started) return; rec.header.type = PERF_RECORD_ITRACE_START; rec.header.misc = 0; rec.header.size = sizeof(rec); rec.pid = perf_event_pid(event, current); rec.tid = perf_event_tid(event, current); perf_event_header__init_id(&rec.header, &sample, event); ret = perf_output_begin(&handle, event, rec.header.size); if (ret) return; perf_output_put(&handle, rec); perf_event__output_id_sample(event, &handle, &sample); perf_output_end(&handle); } static int __perf_event_account_interrupt(struct perf_event *event, int throttle) { struct hw_perf_event *hwc = &event->hw; int ret = 0; u64 seq; seq = __this_cpu_read(perf_throttled_seq); if (seq != hwc->interrupts_seq) { hwc->interrupts_seq = seq; hwc->interrupts = 1; } else { hwc->interrupts++; if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { __this_cpu_inc(perf_throttled_count); tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); hwc->interrupts = MAX_INTERRUPTS; perf_log_throttle(event, 0); ret = 1; } } if (event->attr.freq) { u64 now = perf_clock(); s64 delta = now - hwc->freq_time_stamp; hwc->freq_time_stamp = now; if (delta > 0 && delta < 2*TICK_NSEC) perf_adjust_period(event, delta, hwc->last_period, true); } return ret; } int perf_event_account_interrupt(struct perf_event *event) { return __perf_event_account_interrupt(event, 1); } /* * Generic event overflow handling, sampling. */ static int __perf_event_overflow(struct perf_event *event, int throttle, struct perf_sample_data *data, struct pt_regs *regs) { int events = atomic_read(&event->event_limit); int ret = 0; /* * Non-sampling counters might still use the PMI to fold short * hardware counters, ignore those. */ if (unlikely(!is_sampling_event(event))) return 0; ret = __perf_event_account_interrupt(event, throttle); /* * XXX event_limit might not quite work as expected on inherited * events */ event->pending_kill = POLL_IN; if (events && atomic_dec_and_test(&event->event_limit)) { ret = 1; event->pending_kill = POLL_HUP; perf_event_disable_inatomic(event); } READ_ONCE(event->overflow_handler)(event, data, regs); if (*perf_event_fasync(event) && event->pending_kill) { event->pending_wakeup = 1; irq_work_queue(&event->pending); } return ret; } int perf_event_overflow(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { return __perf_event_overflow(event, 1, data, regs); } /* * Generic software event infrastructure */ struct swevent_htable { struct swevent_hlist *swevent_hlist; struct mutex hlist_mutex; int hlist_refcount; /* Recursion avoidance in each contexts */ int recursion[PERF_NR_CONTEXTS]; }; static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); /* * We directly increment event->count and keep a second value in * event->hw.period_left to count intervals. This period event * is kept in the range [-sample_period, 0] so that we can use the * sign as trigger. */ u64 perf_swevent_set_period(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; u64 period = hwc->last_period; u64 nr, offset; s64 old, val; hwc->last_period = hwc->sample_period; again: old = val = local64_read(&hwc->period_left); if (val < 0) return 0; nr = div64_u64(period + val, period); offset = nr * period; val -= offset; if (local64_cmpxchg(&hwc->period_left, old, val) != old) goto again; return nr; } static void perf_swevent_overflow(struct perf_event *event, u64 overflow, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; int throttle = 0; if (!overflow) overflow = perf_swevent_set_period(event); if (hwc->interrupts == MAX_INTERRUPTS) return; for (; overflow; overflow--) { if (__perf_event_overflow(event, throttle, data, regs)) { /* * We inhibit the overflow from happening when * hwc->interrupts == MAX_INTERRUPTS. */ break; } throttle = 1; } } static void perf_swevent_event(struct perf_event *event, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct hw_perf_event *hwc = &event->hw; local64_add(nr, &event->count); if (!regs) return; if (!is_sampling_event(event)) return; if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { data->period = nr; return perf_swevent_overflow(event, 1, data, regs); } else data->period = event->hw.last_period; if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) return perf_swevent_overflow(event, 1, data, regs); if (local64_add_negative(nr, &hwc->period_left)) return; perf_swevent_overflow(event, 0, data, regs); } static int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) { if (event->hw.state & PERF_HES_STOPPED) return 1; if (regs) { if (event->attr.exclude_user && user_mode(regs)) return 1; if (event->attr.exclude_kernel && !user_mode(regs)) return 1; } return 0; } static int perf_swevent_match(struct perf_event *event, enum perf_type_id type, u32 event_id, struct perf_sample_data *data, struct pt_regs *regs) { if (event->attr.type != type) return 0; if (event->attr.config != event_id) return 0; if (perf_exclude_event(event, regs)) return 0; return 1; } static inline u64 swevent_hash(u64 type, u32 event_id) { u64 val = event_id | (type << 32); return hash_64(val, SWEVENT_HLIST_BITS); } static inline struct hlist_head * __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) { u64 hash = swevent_hash(type, event_id); return &hlist->heads[hash]; } /* For the read side: events when they trigger */ static inline struct hlist_head * find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) { struct swevent_hlist *hlist; hlist = rcu_dereference(swhash->swevent_hlist); if (!hlist) return NULL; return __find_swevent_head(hlist, type, event_id); } /* For the event head insertion and removal in the hlist */ static inline struct hlist_head * find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) { struct swevent_hlist *hlist; u32 event_id = event->attr.config; u64 type = event->attr.type; /* * Event scheduling is always serialized against hlist allocation * and release. Which makes the protected version suitable here. * The context lock guarantees that. */ hlist = rcu_dereference_protected(swhash->swevent_hlist, lockdep_is_held(&event->ctx->lock)); if (!hlist) return NULL; return __find_swevent_head(hlist, type, event_id); } static void do_perf_sw_event(enum perf_type_id type, u32 event_id, u64 nr, struct perf_sample_data *data, struct pt_regs *regs) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); struct perf_event *event; struct hlist_head *head; rcu_read_lock(); head = find_swevent_head_rcu(swhash, type, event_id); if (!head) goto end; hlist_for_each_entry_rcu(event, head, hlist_entry) { if (perf_swevent_match(event, type, event_id, data, regs)) perf_swevent_event(event, nr, data, regs); } end: rcu_read_unlock(); } DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); int perf_swevent_get_recursion_context(void) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); return get_recursion_context(swhash->recursion); } EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); void perf_swevent_put_recursion_context(int rctx) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); put_recursion_context(swhash->recursion, rctx); } void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) { struct perf_sample_data data; if (WARN_ON_ONCE(!regs)) return; perf_sample_data_init(&data, addr, 0); do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); } void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) { int rctx; preempt_disable_notrace(); rctx = perf_swevent_get_recursion_context(); if (unlikely(rctx < 0)) goto fail; ___perf_sw_event(event_id, nr, regs, addr); perf_swevent_put_recursion_context(rctx); fail: preempt_enable_notrace(); } static void perf_swevent_read(struct perf_event *event) { } static int perf_swevent_add(struct perf_event *event, int flags) { struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); struct hw_perf_event *hwc = &event->hw; struct hlist_head *head; if (is_sampling_event(event)) { hwc->last_period = hwc->sample_period; perf_swevent_set_period(event); } hwc->state = !(flags & PERF_EF_START); head = find_swevent_head(swhash, event); if (WARN_ON_ONCE(!head)) return -EINVAL; hlist_add_head_rcu(&event->hlist_entry, head); perf_event_update_userpage(event); return 0; } static void perf_swevent_del(struct perf_event *event, int flags) { hlist_del_rcu(&event->hlist_entry); } static void perf_swevent_start(struct perf_event *event, int flags) { event->hw.state = 0; } static void perf_swevent_stop(struct perf_event *event, int flags) { event->hw.state = PERF_HES_STOPPED; } /* Deref the hlist from the update side */ static inline struct swevent_hlist * swevent_hlist_deref(struct swevent_htable *swhash) { return rcu_dereference_protected(swhash->swevent_hlist, lockdep_is_held(&swhash->hlist_mutex)); } static void swevent_hlist_release(struct swevent_htable *swhash) { struct swevent_hlist *hlist = swevent_hlist_deref(swhash); if (!hlist) return; RCU_INIT_POINTER(swhash->swevent_hlist, NULL); kfree_rcu(hlist, rcu_head); } static void swevent_hlist_put_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); if (!--swhash->hlist_refcount) swevent_hlist_release(swhash); mutex_unlock(&swhash->hlist_mutex); } static void swevent_hlist_put(void) { int cpu; for_each_possible_cpu(cpu) swevent_hlist_put_cpu(cpu); } static int swevent_hlist_get_cpu(int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); int err = 0; mutex_lock(&swhash->hlist_mutex); if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) { struct swevent_hlist *hlist; hlist = kzalloc(sizeof(*hlist), GFP_KERNEL); if (!hlist) { err = -ENOMEM; goto exit; } rcu_assign_pointer(swhash->swevent_hlist, hlist); } swhash->hlist_refcount++; exit: mutex_unlock(&swhash->hlist_mutex); return err; } static int swevent_hlist_get(void) { int err, cpu, failed_cpu; get_online_cpus(); for_each_possible_cpu(cpu) { err = swevent_hlist_get_cpu(cpu); if (err) { failed_cpu = cpu; goto fail; } } put_online_cpus(); return 0; fail: for_each_possible_cpu(cpu) { if (cpu == failed_cpu) break; swevent_hlist_put_cpu(cpu); } put_online_cpus(); return err; } struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; static void sw_perf_event_destroy(struct perf_event *event) { u64 event_id = event->attr.config; WARN_ON(event->parent); static_key_slow_dec(&perf_swevent_enabled[event_id]); swevent_hlist_put(); } static int perf_swevent_init(struct perf_event *event) { u64 event_id = event->attr.config; if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; switch (event_id) { case PERF_COUNT_SW_CPU_CLOCK: case PERF_COUNT_SW_TASK_CLOCK: return -ENOENT; default: break; } if (event_id >= PERF_COUNT_SW_MAX) return -ENOENT; if (!event->parent) { int err; err = swevent_hlist_get(); if (err) return err; static_key_slow_inc(&perf_swevent_enabled[event_id]); event->destroy = sw_perf_event_destroy; } return 0; } static struct pmu perf_swevent = { .task_ctx_nr = perf_sw_context, .capabilities = PERF_PMU_CAP_NO_NMI, .event_init = perf_swevent_init, .add = perf_swevent_add, .del = perf_swevent_del, .start = perf_swevent_start, .stop = perf_swevent_stop, .read = perf_swevent_read, }; #ifdef CONFIG_EVENT_TRACING static int perf_tp_filter_match(struct perf_event *event, struct perf_sample_data *data) { void *record = data->raw->frag.data; /* only top level events have filters set */ if (event->parent) event = event->parent; if (likely(!event->filter) || filter_match_preds(event->filter, record)) return 1; return 0; } static int perf_tp_event_match(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { if (event->hw.state & PERF_HES_STOPPED) return 0; /* * All tracepoints are from kernel-space. */ if (event->attr.exclude_kernel) return 0; if (!perf_tp_filter_match(event, data)) return 0; return 1; } void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, struct trace_event_call *call, u64 count, struct pt_regs *regs, struct hlist_head *head, struct task_struct *task) { struct bpf_prog *prog = call->prog; if (prog) { *(struct pt_regs **)raw_data = regs; if (!trace_call_bpf(prog, raw_data) || hlist_empty(head)) { perf_swevent_put_recursion_context(rctx); return; } } perf_tp_event(call->event.type, count, raw_data, size, regs, head, rctx, task); } EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, struct pt_regs *regs, struct hlist_head *head, int rctx, struct task_struct *task) { struct perf_sample_data data; struct perf_event *event; struct perf_raw_record raw = { .frag = { .size = entry_size, .data = record, }, }; perf_sample_data_init(&data, 0, 0); data.raw = &raw; perf_trace_buf_update(record, event_type); hlist_for_each_entry_rcu(event, head, hlist_entry) { if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } /* * If we got specified a target task, also iterate its context and * deliver this event there too. */ if (task && task != current) { struct perf_event_context *ctx; struct trace_entry *entry = record; rcu_read_lock(); ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]); if (!ctx) goto unlock; list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { if (event->attr.type != PERF_TYPE_TRACEPOINT) continue; if (event->attr.config != entry->type) continue; if (perf_tp_event_match(event, &data, regs)) perf_swevent_event(event, count, &data, regs); } unlock: rcu_read_unlock(); } perf_swevent_put_recursion_context(rctx); } EXPORT_SYMBOL_GPL(perf_tp_event); static void tp_perf_event_destroy(struct perf_event *event) { perf_trace_destroy(event); } static int perf_tp_event_init(struct perf_event *event) { int err; if (event->attr.type != PERF_TYPE_TRACEPOINT) return -ENOENT; /* * no branch sampling for tracepoint events */ if (has_branch_stack(event)) return -EOPNOTSUPP; err = perf_trace_init(event); if (err) return err; event->destroy = tp_perf_event_destroy; return 0; } static struct pmu perf_tracepoint = { .task_ctx_nr = perf_sw_context, .event_init = perf_tp_event_init, .add = perf_trace_add, .del = perf_trace_del, .start = perf_swevent_start, .stop = perf_swevent_stop, .read = perf_swevent_read, }; static inline void perf_tp_register(void) { perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); } static void perf_event_free_filter(struct perf_event *event) { ftrace_profile_free_filter(event); } #ifdef CONFIG_BPF_SYSCALL static void bpf_overflow_handler(struct perf_event *event, struct perf_sample_data *data, struct pt_regs *regs) { struct bpf_perf_event_data_kern ctx = { .data = data, .regs = regs, }; int ret = 0; preempt_disable(); if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) goto out; rcu_read_lock(); ret = BPF_PROG_RUN(event->prog, &ctx); rcu_read_unlock(); out: __this_cpu_dec(bpf_prog_active); preempt_enable(); if (!ret) return; event->orig_overflow_handler(event, data, regs); } static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd) { struct bpf_prog *prog; if (event->overflow_handler_context) /* hw breakpoint or kernel counter */ return -EINVAL; if (event->prog) return -EEXIST; prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT); if (IS_ERR(prog)) return PTR_ERR(prog); event->prog = prog; event->orig_overflow_handler = READ_ONCE(event->overflow_handler); WRITE_ONCE(event->overflow_handler, bpf_overflow_handler); return 0; } static void perf_event_free_bpf_handler(struct perf_event *event) { struct bpf_prog *prog = event->prog; if (!prog) return; WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler); event->prog = NULL; bpf_prog_put(prog); } #else static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd) { return -EOPNOTSUPP; } static void perf_event_free_bpf_handler(struct perf_event *event) { } #endif static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd) { bool is_kprobe, is_tracepoint; struct bpf_prog *prog; if (event->attr.type == PERF_TYPE_HARDWARE || event->attr.type == PERF_TYPE_SOFTWARE) return perf_event_set_bpf_handler(event, prog_fd); if (event->attr.type != PERF_TYPE_TRACEPOINT) return -EINVAL; if (event->tp_event->prog) return -EEXIST; is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE; is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; if (!is_kprobe && !is_tracepoint) /* bpf programs can only be attached to u/kprobe or tracepoint */ return -EINVAL; prog = bpf_prog_get(prog_fd); if (IS_ERR(prog)) return PTR_ERR(prog); if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) || (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT)) { /* valid fd, but invalid bpf program type */ bpf_prog_put(prog); return -EINVAL; } if (is_tracepoint) { int off = trace_event_get_offsets(event->tp_event); if (prog->aux->max_ctx_offset > off) { bpf_prog_put(prog); return -EACCES; } } event->tp_event->prog = prog; return 0; } static void perf_event_free_bpf_prog(struct perf_event *event) { struct bpf_prog *prog; perf_event_free_bpf_handler(event); if (!event->tp_event) return; prog = event->tp_event->prog; if (prog) { event->tp_event->prog = NULL; bpf_prog_put(prog); } } #else static inline void perf_tp_register(void) { } static void perf_event_free_filter(struct perf_event *event) { } static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd) { return -ENOENT; } static void perf_event_free_bpf_prog(struct perf_event *event) { } #endif /* CONFIG_EVENT_TRACING */ #ifdef CONFIG_HAVE_HW_BREAKPOINT void perf_bp_event(struct perf_event *bp, void *data) { struct perf_sample_data sample; struct pt_regs *regs = data; perf_sample_data_init(&sample, bp->attr.bp_addr, 0); if (!bp->hw.state && !perf_exclude_event(bp, regs)) perf_swevent_event(bp, 1, &sample, regs); } #endif /* * Allocate a new address filter */ static struct perf_addr_filter * perf_addr_filter_new(struct perf_event *event, struct list_head *filters) { int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); struct perf_addr_filter *filter; filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); if (!filter) return NULL; INIT_LIST_HEAD(&filter->entry); list_add_tail(&filter->entry, filters); return filter; } static void free_filters_list(struct list_head *filters) { struct perf_addr_filter *filter, *iter; list_for_each_entry_safe(filter, iter, filters, entry) { if (filter->inode) iput(filter->inode); list_del(&filter->entry); kfree(filter); } } /* * Free existing address filters and optionally install new ones */ static void perf_addr_filters_splice(struct perf_event *event, struct list_head *head) { unsigned long flags; LIST_HEAD(list); if (!has_addr_filter(event)) return; /* don't bother with children, they don't have their own filters */ if (event->parent) return; raw_spin_lock_irqsave(&event->addr_filters.lock, flags); list_splice_init(&event->addr_filters.list, &list); if (head) list_splice(head, &event->addr_filters.list); raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); free_filters_list(&list); } /* * Scan through mm's vmas and see if one of them matches the * @filter; if so, adjust filter's address range. * Called with mm::mmap_sem down for reading. */ static unsigned long perf_addr_filter_apply(struct perf_addr_filter *filter, struct mm_struct *mm) { struct vm_area_struct *vma; for (vma = mm->mmap; vma; vma = vma->vm_next) { struct file *file = vma->vm_file; unsigned long off = vma->vm_pgoff << PAGE_SHIFT; unsigned long vma_size = vma->vm_end - vma->vm_start; if (!file) continue; if (!perf_addr_filter_match(filter, file, off, vma_size)) continue; return vma->vm_start; } return 0; } /* * Update event's address range filters based on the * task's existing mappings, if any. */ static void perf_event_addr_filters_apply(struct perf_event *event) { struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); struct task_struct *task = READ_ONCE(event->ctx->task); struct perf_addr_filter *filter; struct mm_struct *mm = NULL; unsigned int count = 0; unsigned long flags; /* * We may observe TASK_TOMBSTONE, which means that the event tear-down * will stop on the parent's child_mutex that our caller is also holding */ if (task == TASK_TOMBSTONE) return; if (!ifh->nr_file_filters) return; mm = get_task_mm(event->ctx->task); if (!mm) goto restart; down_read(&mm->mmap_sem); raw_spin_lock_irqsave(&ifh->lock, flags); list_for_each_entry(filter, &ifh->list, entry) { event->addr_filters_offs[count] = 0; /* * Adjust base offset if the filter is associated to a binary * that needs to be mapped: */ if (filter->inode) event->addr_filters_offs[count] = perf_addr_filter_apply(filter, mm); count++; } event->addr_filters_gen++; raw_spin_unlock_irqrestore(&ifh->lock, flags); up_read(&mm->mmap_sem); mmput(mm); restart: perf_event_stop(event, 1); } /* * Address range filtering: limiting the data to certain * instruction address ranges. Filters are ioctl()ed to us from * userspace as ascii strings. * * Filter string format: * * ACTION RANGE_SPEC * where ACTION is one of the * * "filter": limit the trace to this region * * "start": start tracing from this address * * "stop": stop tracing at this address/region; * RANGE_SPEC is * * for kernel addresses: <start address>[/<size>] * * for object files: <start address>[/<size>]@</path/to/object/file> * * if <size> is not specified, the range is treated as a single address. */ enum { IF_ACT_NONE = -1, IF_ACT_FILTER, IF_ACT_START, IF_ACT_STOP, IF_SRC_FILE, IF_SRC_KERNEL, IF_SRC_FILEADDR, IF_SRC_KERNELADDR, }; enum { IF_STATE_ACTION = 0, IF_STATE_SOURCE, IF_STATE_END, }; static const match_table_t if_tokens = { { IF_ACT_FILTER, "filter" }, { IF_ACT_START, "start" }, { IF_ACT_STOP, "stop" }, { IF_SRC_FILE, "%u/%u@%s" }, { IF_SRC_KERNEL, "%u/%u" }, { IF_SRC_FILEADDR, "%u@%s" }, { IF_SRC_KERNELADDR, "%u" }, { IF_ACT_NONE, NULL }, }; /* * Address filter string parser */ static int perf_event_parse_addr_filter(struct perf_event *event, char *fstr, struct list_head *filters) { struct perf_addr_filter *filter = NULL; char *start, *orig, *filename = NULL; struct path path; substring_t args[MAX_OPT_ARGS]; int state = IF_STATE_ACTION, token; unsigned int kernel = 0; int ret = -EINVAL; orig = fstr = kstrdup(fstr, GFP_KERNEL); if (!fstr) return -ENOMEM; while ((start = strsep(&fstr, " ,\n")) != NULL) { ret = -EINVAL; if (!*start) continue; /* filter definition begins */ if (state == IF_STATE_ACTION) { filter = perf_addr_filter_new(event, filters); if (!filter) goto fail; } token = match_token(start, if_tokens, args); switch (token) { case IF_ACT_FILTER: case IF_ACT_START: filter->filter = 1; case IF_ACT_STOP: if (state != IF_STATE_ACTION) goto fail; state = IF_STATE_SOURCE; break; case IF_SRC_KERNELADDR: case IF_SRC_KERNEL: kernel = 1; case IF_SRC_FILEADDR: case IF_SRC_FILE: if (state != IF_STATE_SOURCE) goto fail; if (token == IF_SRC_FILE || token == IF_SRC_KERNEL) filter->range = 1; *args[0].to = 0; ret = kstrtoul(args[0].from, 0, &filter->offset); if (ret) goto fail; if (filter->range) { *args[1].to = 0; ret = kstrtoul(args[1].from, 0, &filter->size); if (ret) goto fail; } if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { int fpos = filter->range ? 2 : 1; filename = match_strdup(&args[fpos]); if (!filename) { ret = -ENOMEM; goto fail; } } state = IF_STATE_END; break; default: goto fail; } /* * Filter definition is fully parsed, validate and install it. * Make sure that it doesn't contradict itself or the event's * attribute. */ if (state == IF_STATE_END) { ret = -EINVAL; if (kernel && event->attr.exclude_kernel) goto fail; if (!kernel) { if (!filename) goto fail; /* * For now, we only support file-based filters * in per-task events; doing so for CPU-wide * events requires additional context switching * trickery, since same object code will be * mapped at different virtual addresses in * different processes. */ ret = -EOPNOTSUPP; if (!event->ctx->task) goto fail_free_name; /* look up the path and grab its inode */ ret = kern_path(filename, LOOKUP_FOLLOW, &path); if (ret) goto fail_free_name; filter->inode = igrab(d_inode(path.dentry)); path_put(&path); kfree(filename); filename = NULL; ret = -EINVAL; if (!filter->inode || !S_ISREG(filter->inode->i_mode)) /* free_filters_list() will iput() */ goto fail; event->addr_filters.nr_file_filters++; } /* ready to consume more filters */ state = IF_STATE_ACTION; filter = NULL; } } if (state != IF_STATE_ACTION) goto fail; kfree(orig); return 0; fail_free_name: kfree(filename); fail: free_filters_list(filters); kfree(orig); return ret; } static int perf_event_set_addr_filter(struct perf_event *event, char *filter_str) { LIST_HEAD(filters); int ret; /* * Since this is called in perf_ioctl() path, we're already holding * ctx::mutex. */ lockdep_assert_held(&event->ctx->mutex); if (WARN_ON_ONCE(event->parent)) return -EINVAL; ret = perf_event_parse_addr_filter(event, filter_str, &filters); if (ret) goto fail_clear_files; ret = event->pmu->addr_filters_validate(&filters); if (ret) goto fail_free_filters; /* remove existing filters, if any */ perf_addr_filters_splice(event, &filters); /* install new filters */ perf_event_for_each_child(event, perf_event_addr_filters_apply); return ret; fail_free_filters: free_filters_list(&filters); fail_clear_files: event->addr_filters.nr_file_filters = 0; return ret; } static int perf_event_set_filter(struct perf_event *event, void __user *arg) { char *filter_str; int ret = -EINVAL; if ((event->attr.type != PERF_TYPE_TRACEPOINT || !IS_ENABLED(CONFIG_EVENT_TRACING)) && !has_addr_filter(event)) return -EINVAL; filter_str = strndup_user(arg, PAGE_SIZE); if (IS_ERR(filter_str)) return PTR_ERR(filter_str); if (IS_ENABLED(CONFIG_EVENT_TRACING) && event->attr.type == PERF_TYPE_TRACEPOINT) ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); else if (has_addr_filter(event)) ret = perf_event_set_addr_filter(event, filter_str); kfree(filter_str); return ret; } /* * hrtimer based swevent callback */ static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) { enum hrtimer_restart ret = HRTIMER_RESTART; struct perf_sample_data data; struct pt_regs *regs; struct perf_event *event; u64 period; event = container_of(hrtimer, struct perf_event, hw.hrtimer); if (event->state != PERF_EVENT_STATE_ACTIVE) return HRTIMER_NORESTART; event->pmu->read(event); perf_sample_data_init(&data, 0, event->hw.last_period); regs = get_irq_regs(); if (regs && !perf_exclude_event(event, regs)) { if (!(event->attr.exclude_idle && is_idle_task(current))) if (__perf_event_overflow(event, 1, &data, regs)) ret = HRTIMER_NORESTART; } period = max_t(u64, 10000, event->hw.sample_period); hrtimer_forward_now(hrtimer, ns_to_ktime(period)); return ret; } static void perf_swevent_start_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; s64 period; if (!is_sampling_event(event)) return; period = local64_read(&hwc->period_left); if (period) { if (period < 0) period = 10000; local64_set(&hwc->period_left, 0); } else { period = max_t(u64, 10000, hwc->sample_period); } hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), HRTIMER_MODE_REL_PINNED); } static void perf_swevent_cancel_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (is_sampling_event(event)) { ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); local64_set(&hwc->period_left, ktime_to_ns(remaining)); hrtimer_cancel(&hwc->hrtimer); } } static void perf_swevent_init_hrtimer(struct perf_event *event) { struct hw_perf_event *hwc = &event->hw; if (!is_sampling_event(event)) return; hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); hwc->hrtimer.function = perf_swevent_hrtimer; /* * Since hrtimers have a fixed rate, we can do a static freq->period * mapping and avoid the whole period adjust feedback stuff. */ if (event->attr.freq) { long freq = event->attr.sample_freq; event->attr.sample_period = NSEC_PER_SEC / freq; hwc->sample_period = event->attr.sample_period; local64_set(&hwc->period_left, hwc->sample_period); hwc->last_period = hwc->sample_period; event->attr.freq = 0; } } /* * Software event: cpu wall time clock */ static void cpu_clock_event_update(struct perf_event *event) { s64 prev; u64 now; now = local_clock(); prev = local64_xchg(&event->hw.prev_count, now); local64_add(now - prev, &event->count); } static void cpu_clock_event_start(struct perf_event *event, int flags) { local64_set(&event->hw.prev_count, local_clock()); perf_swevent_start_hrtimer(event); } static void cpu_clock_event_stop(struct perf_event *event, int flags) { perf_swevent_cancel_hrtimer(event); cpu_clock_event_update(event); } static int cpu_clock_event_add(struct perf_event *event, int flags) { if (flags & PERF_EF_START) cpu_clock_event_start(event, flags); perf_event_update_userpage(event); return 0; } static void cpu_clock_event_del(struct perf_event *event, int flags) { cpu_clock_event_stop(event, flags); } static void cpu_clock_event_read(struct perf_event *event) { cpu_clock_event_update(event); } static int cpu_clock_event_init(struct perf_event *event) { if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; perf_swevent_init_hrtimer(event); return 0; } static struct pmu perf_cpu_clock = { .task_ctx_nr = perf_sw_context, .capabilities = PERF_PMU_CAP_NO_NMI, .event_init = cpu_clock_event_init, .add = cpu_clock_event_add, .del = cpu_clock_event_del, .start = cpu_clock_event_start, .stop = cpu_clock_event_stop, .read = cpu_clock_event_read, }; /* * Software event: task time clock */ static void task_clock_event_update(struct perf_event *event, u64 now) { u64 prev; s64 delta; prev = local64_xchg(&event->hw.prev_count, now); delta = now - prev; local64_add(delta, &event->count); } static void task_clock_event_start(struct perf_event *event, int flags) { local64_set(&event->hw.prev_count, event->ctx->time); perf_swevent_start_hrtimer(event); } static void task_clock_event_stop(struct perf_event *event, int flags) { perf_swevent_cancel_hrtimer(event); task_clock_event_update(event, event->ctx->time); } static int task_clock_event_add(struct perf_event *event, int flags) { if (flags & PERF_EF_START) task_clock_event_start(event, flags); perf_event_update_userpage(event); return 0; } static void task_clock_event_del(struct perf_event *event, int flags) { task_clock_event_stop(event, PERF_EF_UPDATE); } static void task_clock_event_read(struct perf_event *event) { u64 now = perf_clock(); u64 delta = now - event->ctx->timestamp; u64 time = event->ctx->time + delta; task_clock_event_update(event, time); } static int task_clock_event_init(struct perf_event *event) { if (event->attr.type != PERF_TYPE_SOFTWARE) return -ENOENT; if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) return -ENOENT; /* * no branch sampling for software events */ if (has_branch_stack(event)) return -EOPNOTSUPP; perf_swevent_init_hrtimer(event); return 0; } static struct pmu perf_task_clock = { .task_ctx_nr = perf_sw_context, .capabilities = PERF_PMU_CAP_NO_NMI, .event_init = task_clock_event_init, .add = task_clock_event_add, .del = task_clock_event_del, .start = task_clock_event_start, .stop = task_clock_event_stop, .read = task_clock_event_read, }; static void perf_pmu_nop_void(struct pmu *pmu) { } static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) { } static int perf_pmu_nop_int(struct pmu *pmu) { return 0; } static DEFINE_PER_CPU(unsigned int, nop_txn_flags); static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) { __this_cpu_write(nop_txn_flags, flags); if (flags & ~PERF_PMU_TXN_ADD) return; perf_pmu_disable(pmu); } static int perf_pmu_commit_txn(struct pmu *pmu) { unsigned int flags = __this_cpu_read(nop_txn_flags); __this_cpu_write(nop_txn_flags, 0); if (flags & ~PERF_PMU_TXN_ADD) return 0; perf_pmu_enable(pmu); return 0; } static void perf_pmu_cancel_txn(struct pmu *pmu) { unsigned int flags = __this_cpu_read(nop_txn_flags); __this_cpu_write(nop_txn_flags, 0); if (flags & ~PERF_PMU_TXN_ADD) return; perf_pmu_enable(pmu); } static int perf_event_idx_default(struct perf_event *event) { return 0; } /* * Ensures all contexts with the same task_ctx_nr have the same * pmu_cpu_context too. */ static struct perf_cpu_context __percpu *find_pmu_context(int ctxn) { struct pmu *pmu; if (ctxn < 0) return NULL; list_for_each_entry(pmu, &pmus, entry) { if (pmu->task_ctx_nr == ctxn) return pmu->pmu_cpu_context; } return NULL; } static void free_pmu_context(struct pmu *pmu) { mutex_lock(&pmus_lock); free_percpu(pmu->pmu_cpu_context); mutex_unlock(&pmus_lock); } /* * Let userspace know that this PMU supports address range filtering: */ static ssize_t nr_addr_filters_show(struct device *dev, struct device_attribute *attr, char *page) { struct pmu *pmu = dev_get_drvdata(dev); return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters); } DEVICE_ATTR_RO(nr_addr_filters); static struct idr pmu_idr; static ssize_t type_show(struct device *dev, struct device_attribute *attr, char *page) { struct pmu *pmu = dev_get_drvdata(dev); return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type); } static DEVICE_ATTR_RO(type); static ssize_t perf_event_mux_interval_ms_show(struct device *dev, struct device_attribute *attr, char *page) { struct pmu *pmu = dev_get_drvdata(dev); return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms); } static DEFINE_MUTEX(mux_interval_mutex); static ssize_t perf_event_mux_interval_ms_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct pmu *pmu = dev_get_drvdata(dev); int timer, cpu, ret; ret = kstrtoint(buf, 0, &timer); if (ret) return ret; if (timer < 1) return -EINVAL; /* same value, noting to do */ if (timer == pmu->hrtimer_interval_ms) return count; mutex_lock(&mux_interval_mutex); pmu->hrtimer_interval_ms = timer; /* update all cpuctx for this PMU */ get_online_cpus(); for_each_online_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); cpu_function_call(cpu, (remote_function_f)perf_mux_hrtimer_restart, cpuctx); } put_online_cpus(); mutex_unlock(&mux_interval_mutex); return count; } static DEVICE_ATTR_RW(perf_event_mux_interval_ms); static struct attribute *pmu_dev_attrs[] = { &dev_attr_type.attr, &dev_attr_perf_event_mux_interval_ms.attr, NULL, }; ATTRIBUTE_GROUPS(pmu_dev); static int pmu_bus_running; static struct bus_type pmu_bus = { .name = "event_source", .dev_groups = pmu_dev_groups, }; static void pmu_dev_release(struct device *dev) { kfree(dev); } static int pmu_dev_alloc(struct pmu *pmu) { int ret = -ENOMEM; pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL); if (!pmu->dev) goto out; pmu->dev->groups = pmu->attr_groups; device_initialize(pmu->dev); ret = dev_set_name(pmu->dev, "%s", pmu->name); if (ret) goto free_dev; dev_set_drvdata(pmu->dev, pmu); pmu->dev->bus = &pmu_bus; pmu->dev->release = pmu_dev_release; ret = device_add(pmu->dev); if (ret) goto free_dev; /* For PMUs with address filters, throw in an extra attribute: */ if (pmu->nr_addr_filters) ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters); if (ret) goto del_dev; out: return ret; del_dev: device_del(pmu->dev); free_dev: put_device(pmu->dev); goto out; } static struct lock_class_key cpuctx_mutex; static struct lock_class_key cpuctx_lock; int perf_pmu_register(struct pmu *pmu, const char *name, int type) { int cpu, ret; mutex_lock(&pmus_lock); ret = -ENOMEM; pmu->pmu_disable_count = alloc_percpu(int); if (!pmu->pmu_disable_count) goto unlock; pmu->type = -1; if (!name) goto skip_type; pmu->name = name; if (type < 0) { type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL); if (type < 0) { ret = type; goto free_pdc; } } pmu->type = type; if (pmu_bus_running) { ret = pmu_dev_alloc(pmu); if (ret) goto free_idr; } skip_type: if (pmu->task_ctx_nr == perf_hw_context) { static int hw_context_taken = 0; /* * Other than systems with heterogeneous CPUs, it never makes * sense for two PMUs to share perf_hw_context. PMUs which are * uncore must use perf_invalid_context. */ if (WARN_ON_ONCE(hw_context_taken && !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS))) pmu->task_ctx_nr = perf_invalid_context; hw_context_taken = 1; } pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); if (pmu->pmu_cpu_context) goto got_cpu_context; ret = -ENOMEM; pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); if (!pmu->pmu_cpu_context) goto free_dev; for_each_possible_cpu(cpu) { struct perf_cpu_context *cpuctx; cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); __perf_event_init_context(&cpuctx->ctx); lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); cpuctx->ctx.pmu = pmu; __perf_mux_hrtimer_init(cpuctx, cpu); } got_cpu_context: if (!pmu->start_txn) { if (pmu->pmu_enable) { /* * If we have pmu_enable/pmu_disable calls, install * transaction stubs that use that to try and batch * hardware accesses. */ pmu->start_txn = perf_pmu_start_txn; pmu->commit_txn = perf_pmu_commit_txn; pmu->cancel_txn = perf_pmu_cancel_txn; } else { pmu->start_txn = perf_pmu_nop_txn; pmu->commit_txn = perf_pmu_nop_int; pmu->cancel_txn = perf_pmu_nop_void; } } if (!pmu->pmu_enable) { pmu->pmu_enable = perf_pmu_nop_void; pmu->pmu_disable = perf_pmu_nop_void; } if (!pmu->event_idx) pmu->event_idx = perf_event_idx_default; list_add_rcu(&pmu->entry, &pmus); atomic_set(&pmu->exclusive_cnt, 0); ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; free_dev: device_del(pmu->dev); put_device(pmu->dev); free_idr: if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); free_pdc: free_percpu(pmu->pmu_disable_count); goto unlock; } EXPORT_SYMBOL_GPL(perf_pmu_register); void perf_pmu_unregister(struct pmu *pmu) { int remove_device; mutex_lock(&pmus_lock); remove_device = pmu_bus_running; list_del_rcu(&pmu->entry); mutex_unlock(&pmus_lock); /* * We dereference the pmu list under both SRCU and regular RCU, so * synchronize against both of those. */ synchronize_srcu(&pmus_srcu); synchronize_rcu(); free_percpu(pmu->pmu_disable_count); if (pmu->type >= PERF_TYPE_MAX) idr_remove(&pmu_idr, pmu->type); if (remove_device) { if (pmu->nr_addr_filters) device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); device_del(pmu->dev); put_device(pmu->dev); } free_pmu_context(pmu); } EXPORT_SYMBOL_GPL(perf_pmu_unregister); static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) { struct perf_event_context *ctx = NULL; int ret; if (!try_module_get(pmu->module)) return -ENODEV; if (event->group_leader != event) { /* * This ctx->mutex can nest when we're called through * inheritance. See the perf_event_ctx_lock_nested() comment. */ ctx = perf_event_ctx_lock_nested(event->group_leader, SINGLE_DEPTH_NESTING); BUG_ON(!ctx); } event->pmu = pmu; ret = pmu->event_init(event); if (ctx) perf_event_ctx_unlock(event->group_leader, ctx); if (ret) module_put(pmu->module); return ret; } static struct pmu *perf_init_event(struct perf_event *event) { struct pmu *pmu = NULL; int idx; int ret; idx = srcu_read_lock(&pmus_srcu); /* Try parent's PMU first: */ if (event->parent && event->parent->pmu) { pmu = event->parent->pmu; ret = perf_try_init_event(pmu, event); if (!ret) goto unlock; } rcu_read_lock(); pmu = idr_find(&pmu_idr, event->attr.type); rcu_read_unlock(); if (pmu) { ret = perf_try_init_event(pmu, event); if (ret) pmu = ERR_PTR(ret); goto unlock; } list_for_each_entry_rcu(pmu, &pmus, entry) { ret = perf_try_init_event(pmu, event); if (!ret) goto unlock; if (ret != -ENOENT) { pmu = ERR_PTR(ret); goto unlock; } } pmu = ERR_PTR(-ENOENT); unlock: srcu_read_unlock(&pmus_srcu, idx); return pmu; } static void attach_sb_event(struct perf_event *event) { struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); raw_spin_lock(&pel->lock); list_add_rcu(&event->sb_list, &pel->list); raw_spin_unlock(&pel->lock); } /* * We keep a list of all !task (and therefore per-cpu) events * that need to receive side-band records. * * This avoids having to scan all the various PMU per-cpu contexts * looking for them. */ static void account_pmu_sb_event(struct perf_event *event) { if (is_sb_event(event)) attach_sb_event(event); } static void account_event_cpu(struct perf_event *event, int cpu) { if (event->parent) return; if (is_cgroup_event(event)) atomic_inc(&per_cpu(perf_cgroup_events, cpu)); } /* Freq events need the tick to stay alive (see perf_event_task_tick). */ static void account_freq_event_nohz(void) { #ifdef CONFIG_NO_HZ_FULL /* Lock so we don't race with concurrent unaccount */ spin_lock(&nr_freq_lock); if (atomic_inc_return(&nr_freq_events) == 1) tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); spin_unlock(&nr_freq_lock); #endif } static void account_freq_event(void) { if (tick_nohz_full_enabled()) account_freq_event_nohz(); else atomic_inc(&nr_freq_events); } static void account_event(struct perf_event *event) { bool inc = false; if (event->parent) return; if (event->attach_state & PERF_ATTACH_TASK) inc = true; if (event->attr.mmap || event->attr.mmap_data) atomic_inc(&nr_mmap_events); if (event->attr.comm) atomic_inc(&nr_comm_events); if (event->attr.task) atomic_inc(&nr_task_events); if (event->attr.freq) account_freq_event(); if (event->attr.context_switch) { atomic_inc(&nr_switch_events); inc = true; } if (has_branch_stack(event)) inc = true; if (is_cgroup_event(event)) inc = true; if (inc) { if (atomic_inc_not_zero(&perf_sched_count)) goto enabled; mutex_lock(&perf_sched_mutex); if (!atomic_read(&perf_sched_count)) { static_branch_enable(&perf_sched_events); /* * Guarantee that all CPUs observe they key change and * call the perf scheduling hooks before proceeding to * install events that need them. */ synchronize_sched(); } /* * Now that we have waited for the sync_sched(), allow further * increments to by-pass the mutex. */ atomic_inc(&perf_sched_count); mutex_unlock(&perf_sched_mutex); } enabled: account_event_cpu(event, event->cpu); account_pmu_sb_event(event); } /* * Allocate and initialize a event structure */ static struct perf_event * perf_event_alloc(struct perf_event_attr *attr, int cpu, struct task_struct *task, struct perf_event *group_leader, struct perf_event *parent_event, perf_overflow_handler_t overflow_handler, void *context, int cgroup_fd) { struct pmu *pmu; struct perf_event *event; struct hw_perf_event *hwc; long err = -EINVAL; if ((unsigned)cpu >= nr_cpu_ids) { if (!task || cpu != -1) return ERR_PTR(-EINVAL); } event = kzalloc(sizeof(*event), GFP_KERNEL); if (!event) return ERR_PTR(-ENOMEM); /* * Single events are their own group leaders, with an * empty sibling list: */ if (!group_leader) group_leader = event; mutex_init(&event->child_mutex); INIT_LIST_HEAD(&event->child_list); INIT_LIST_HEAD(&event->group_entry); INIT_LIST_HEAD(&event->event_entry); INIT_LIST_HEAD(&event->sibling_list); INIT_LIST_HEAD(&event->rb_entry); INIT_LIST_HEAD(&event->active_entry); INIT_LIST_HEAD(&event->addr_filters.list); INIT_HLIST_NODE(&event->hlist_entry); init_waitqueue_head(&event->waitq); init_irq_work(&event->pending, perf_pending_event); mutex_init(&event->mmap_mutex); raw_spin_lock_init(&event->addr_filters.lock); atomic_long_set(&event->refcount, 1); event->cpu = cpu; event->attr = *attr; event->group_leader = group_leader; event->pmu = NULL; event->oncpu = -1; event->parent = parent_event; event->ns = get_pid_ns(task_active_pid_ns(current)); event->id = atomic64_inc_return(&perf_event_id); event->state = PERF_EVENT_STATE_INACTIVE; if (task) { event->attach_state = PERF_ATTACH_TASK; /* * XXX pmu::event_init needs to know what task to account to * and we cannot use the ctx information because we need the * pmu before we get a ctx. */ event->hw.target = task; } event->clock = &local_clock; if (parent_event) event->clock = parent_event->clock; if (!overflow_handler && parent_event) { overflow_handler = parent_event->overflow_handler; context = parent_event->overflow_handler_context; #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) if (overflow_handler == bpf_overflow_handler) { struct bpf_prog *prog = bpf_prog_inc(parent_event->prog); if (IS_ERR(prog)) { err = PTR_ERR(prog); goto err_ns; } event->prog = prog; event->orig_overflow_handler = parent_event->orig_overflow_handler; } #endif } if (overflow_handler) { event->overflow_handler = overflow_handler; event->overflow_handler_context = context; } else if (is_write_backward(event)){ event->overflow_handler = perf_event_output_backward; event->overflow_handler_context = NULL; } else { event->overflow_handler = perf_event_output_forward; event->overflow_handler_context = NULL; } perf_event__state_init(event); pmu = NULL; hwc = &event->hw; hwc->sample_period = attr->sample_period; if (attr->freq && attr->sample_freq) hwc->sample_period = 1; hwc->last_period = hwc->sample_period; local64_set(&hwc->period_left, hwc->sample_period); /* * we currently do not support PERF_FORMAT_GROUP on inherited events */ if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP)) goto err_ns; if (!has_branch_stack(event)) event->attr.branch_sample_type = 0; if (cgroup_fd != -1) { err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); if (err) goto err_ns; } pmu = perf_init_event(event); if (!pmu) goto err_ns; else if (IS_ERR(pmu)) { err = PTR_ERR(pmu); goto err_ns; } err = exclusive_event_init(event); if (err) goto err_pmu; if (has_addr_filter(event)) { event->addr_filters_offs = kcalloc(pmu->nr_addr_filters, sizeof(unsigned long), GFP_KERNEL); if (!event->addr_filters_offs) goto err_per_task; /* force hw sync on the address filters */ event->addr_filters_gen = 1; } if (!event->parent) { if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { err = get_callchain_buffers(attr->sample_max_stack); if (err) goto err_addr_filters; } } /* symmetric to unaccount_event() in _free_event() */ account_event(event); return event; err_addr_filters: kfree(event->addr_filters_offs); err_per_task: exclusive_event_destroy(event); err_pmu: if (event->destroy) event->destroy(event); module_put(pmu->module); err_ns: if (is_cgroup_event(event)) perf_detach_cgroup(event); if (event->ns) put_pid_ns(event->ns); kfree(event); return ERR_PTR(err); } static int perf_copy_attr(struct perf_event_attr __user *uattr, struct perf_event_attr *attr) { u32 size; int ret; if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0)) return -EFAULT; /* * zero the full structure, so that a short copy will be nice. */ memset(attr, 0, sizeof(*attr)); ret = get_user(size, &uattr->size); if (ret) return ret; if (size > PAGE_SIZE) /* silly large */ goto err_size; if (!size) /* abi compat */ size = PERF_ATTR_SIZE_VER0; if (size < PERF_ATTR_SIZE_VER0) goto err_size; /* * If we're handed a bigger struct than we know of, * ensure all the unknown bits are 0 - i.e. new * user-space does not rely on any kernel feature * extensions we dont know about yet. */ if (size > sizeof(*attr)) { unsigned char __user *addr; unsigned char __user *end; unsigned char val; addr = (void __user *)uattr + sizeof(*attr); end = (void __user *)uattr + size; for (; addr < end; addr++) { ret = get_user(val, addr); if (ret) return ret; if (val) goto err_size; } size = sizeof(*attr); } ret = copy_from_user(attr, uattr, size); if (ret) return -EFAULT; if (attr->__reserved_1) return -EINVAL; if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) return -EINVAL; if (attr->read_format & ~(PERF_FORMAT_MAX-1)) return -EINVAL; if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { u64 mask = attr->branch_sample_type; /* only using defined bits */ if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) return -EINVAL; /* at least one branch bit must be set */ if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) return -EINVAL; /* propagate priv level, when not set for branch */ if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { /* exclude_kernel checked on syscall entry */ if (!attr->exclude_kernel) mask |= PERF_SAMPLE_BRANCH_KERNEL; if (!attr->exclude_user) mask |= PERF_SAMPLE_BRANCH_USER; if (!attr->exclude_hv) mask |= PERF_SAMPLE_BRANCH_HV; /* * adjust user setting (for HW filter setup) */ attr->branch_sample_type = mask; } /* privileged levels capture (kernel, hv): check permissions */ if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM) && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr->sample_type & PERF_SAMPLE_REGS_USER) { ret = perf_reg_validate(attr->sample_regs_user); if (ret) return ret; } if (attr->sample_type & PERF_SAMPLE_STACK_USER) { if (!arch_perf_have_user_stack_dump()) return -ENOSYS; /* * We have __u32 type for the size, but so far * we can only use __u16 as maximum due to the * __u16 sample size limit. */ if (attr->sample_stack_user >= USHRT_MAX) ret = -EINVAL; else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) ret = -EINVAL; } if (attr->sample_type & PERF_SAMPLE_REGS_INTR) ret = perf_reg_validate(attr->sample_regs_intr); out: return ret; err_size: put_user(sizeof(*attr), &uattr->size); ret = -E2BIG; goto out; } static int perf_event_set_output(struct perf_event *event, struct perf_event *output_event) { struct ring_buffer *rb = NULL; int ret = -EINVAL; if (!output_event) goto set; /* don't allow circular references */ if (event == output_event) goto out; /* * Don't allow cross-cpu buffers */ if (output_event->cpu != event->cpu) goto out; /* * If its not a per-cpu rb, it must be the same task. */ if (output_event->cpu == -1 && output_event->ctx != event->ctx) goto out; /* * Mixing clocks in the same buffer is trouble you don't need. */ if (output_event->clock != event->clock) goto out; /* * Either writing ring buffer from beginning or from end. * Mixing is not allowed. */ if (is_write_backward(output_event) != is_write_backward(event)) goto out; /* * If both events generate aux data, they must be on the same PMU */ if (has_aux(event) && has_aux(output_event) && event->pmu != output_event->pmu) goto out; set: mutex_lock(&event->mmap_mutex); /* Can't redirect output if we've got an active mmap() */ if (atomic_read(&event->mmap_count)) goto unlock; if (output_event) { /* get the rb we want to redirect to */ rb = ring_buffer_get(output_event); if (!rb) goto unlock; } ring_buffer_attach(event, rb); ret = 0; unlock: mutex_unlock(&event->mmap_mutex); out: return ret; } static void mutex_lock_double(struct mutex *a, struct mutex *b) { if (b < a) swap(a, b); mutex_lock(a); mutex_lock_nested(b, SINGLE_DEPTH_NESTING); } static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) { bool nmi_safe = false; switch (clk_id) { case CLOCK_MONOTONIC: event->clock = &ktime_get_mono_fast_ns; nmi_safe = true; break; case CLOCK_MONOTONIC_RAW: event->clock = &ktime_get_raw_fast_ns; nmi_safe = true; break; case CLOCK_REALTIME: event->clock = &ktime_get_real_ns; break; case CLOCK_BOOTTIME: event->clock = &ktime_get_boot_ns; break; case CLOCK_TAI: event->clock = &ktime_get_tai_ns; break; default: return -EINVAL; } if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) return -EINVAL; return 0; } /* * Variation on perf_event_ctx_lock_nested(), except we take two context * mutexes. */ static struct perf_event_context * __perf_event_ctx_lock_double(struct perf_event *group_leader, struct perf_event_context *ctx) { struct perf_event_context *gctx; again: rcu_read_lock(); gctx = READ_ONCE(group_leader->ctx); if (!atomic_inc_not_zero(&gctx->refcount)) { rcu_read_unlock(); goto again; } rcu_read_unlock(); mutex_lock_double(&gctx->mutex, &ctx->mutex); if (group_leader->ctx != gctx) { mutex_unlock(&ctx->mutex); mutex_unlock(&gctx->mutex); put_ctx(gctx); goto again; } return gctx; } /** * sys_perf_event_open - open a performance event, associate it to a task/cpu * * @attr_uptr: event_id type attributes for monitoring/sampling * @pid: target pid * @cpu: target cpu * @group_fd: group leader event fd */ SYSCALL_DEFINE5(perf_event_open, struct perf_event_attr __user *, attr_uptr, pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) { struct perf_event *group_leader = NULL, *output_event = NULL; struct perf_event *event, *sibling; struct perf_event_attr attr; struct perf_event_context *ctx, *uninitialized_var(gctx); struct file *event_file = NULL; struct fd group = {NULL, 0}; struct task_struct *task = NULL; struct pmu *pmu; int event_fd; int move_group = 0; int err; int f_flags = O_RDWR; int cgroup_fd = -1; /* for future expandability... */ if (flags & ~PERF_FLAG_ALL) return -EINVAL; err = perf_copy_attr(attr_uptr, &attr); if (err) return err; if (!attr.exclude_kernel) { if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN)) return -EACCES; } if (attr.freq) { if (attr.sample_freq > sysctl_perf_event_sample_rate) return -EINVAL; } else { if (attr.sample_period & (1ULL << 63)) return -EINVAL; } if (!attr.sample_max_stack) attr.sample_max_stack = sysctl_perf_event_max_stack; /* * In cgroup mode, the pid argument is used to pass the fd * opened to the cgroup directory in cgroupfs. The cpu argument * designates the cpu on which to monitor threads from that * cgroup. */ if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) return -EINVAL; if (flags & PERF_FLAG_FD_CLOEXEC) f_flags |= O_CLOEXEC; event_fd = get_unused_fd_flags(f_flags); if (event_fd < 0) return event_fd; if (group_fd != -1) { err = perf_fget_light(group_fd, &group); if (err) goto err_fd; group_leader = group.file->private_data; if (flags & PERF_FLAG_FD_OUTPUT) output_event = group_leader; if (flags & PERF_FLAG_FD_NO_GROUP) group_leader = NULL; } if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { task = find_lively_task_by_vpid(pid); if (IS_ERR(task)) { err = PTR_ERR(task); goto err_group_fd; } } if (task && group_leader && group_leader->attr.inherit != attr.inherit) { err = -EINVAL; goto err_task; } get_online_cpus(); if (task) { err = mutex_lock_interruptible(&task->signal->cred_guard_mutex); if (err) goto err_cpus; /* * Reuse ptrace permission checks for now. * * We must hold cred_guard_mutex across this and any potential * perf_install_in_context() call for this new event to * serialize against exec() altering our credentials (and the * perf_event_exit_task() that could imply). */ err = -EACCES; if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) goto err_cred; } if (flags & PERF_FLAG_PID_CGROUP) cgroup_fd = pid; event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL, NULL, cgroup_fd); if (IS_ERR(event)) { err = PTR_ERR(event); goto err_cred; } if (is_sampling_event(event)) { if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { err = -EOPNOTSUPP; goto err_alloc; } } /* * Special case software events and allow them to be part of * any hardware group. */ pmu = event->pmu; if (attr.use_clockid) { err = perf_event_set_clock(event, attr.clockid); if (err) goto err_alloc; } if (pmu->task_ctx_nr == perf_sw_context) event->event_caps |= PERF_EV_CAP_SOFTWARE; if (group_leader && (is_software_event(event) != is_software_event(group_leader))) { if (is_software_event(event)) { /* * If event and group_leader are not both a software * event, and event is, then group leader is not. * * Allow the addition of software events to !software * groups, this is safe because software events never * fail to schedule. */ pmu = group_leader->pmu; } else if (is_software_event(group_leader) && (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { /* * In case the group is a pure software group, and we * try to add a hardware event, move the whole group to * the hardware context. */ move_group = 1; } } /* * Get the target context (task or percpu): */ ctx = find_get_context(pmu, task, event); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_alloc; } if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) { err = -EBUSY; goto err_context; } /* * Look up the group leader (we will attach this event to it): */ if (group_leader) { err = -EINVAL; /* * Do not allow a recursive hierarchy (this new sibling * becoming part of another group-sibling): */ if (group_leader->group_leader != group_leader) goto err_context; /* All events in a group should have the same clock */ if (group_leader->clock != event->clock) goto err_context; /* * Do not allow to attach to a group in a different * task or CPU context: */ if (move_group) { /* * Make sure we're both on the same task, or both * per-cpu events. */ if (group_leader->ctx->task != ctx->task) goto err_context; /* * Make sure we're both events for the same CPU; * grouping events for different CPUs is broken; since * you can never concurrently schedule them anyhow. */ if (group_leader->cpu != event->cpu) goto err_context; } else { if (group_leader->ctx != ctx) goto err_context; } /* * Only a group leader can be exclusive or pinned */ if (attr.exclusive || attr.pinned) goto err_context; } if (output_event) { err = perf_event_set_output(event, output_event); if (err) goto err_context; } event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); if (IS_ERR(event_file)) { err = PTR_ERR(event_file); event_file = NULL; goto err_context; } if (move_group) { gctx = __perf_event_ctx_lock_double(group_leader, ctx); if (gctx->task == TASK_TOMBSTONE) { err = -ESRCH; goto err_locked; } /* * Check if we raced against another sys_perf_event_open() call * moving the software group underneath us. */ if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { /* * If someone moved the group out from under us, check * if this new event wound up on the same ctx, if so * its the regular !move_group case, otherwise fail. */ if (gctx != ctx) { err = -EINVAL; goto err_locked; } else { perf_event_ctx_unlock(group_leader, gctx); move_group = 0; } } } else { mutex_lock(&ctx->mutex); } if (ctx->task == TASK_TOMBSTONE) { err = -ESRCH; goto err_locked; } if (!perf_event_validate_size(event)) { err = -E2BIG; goto err_locked; } /* * Must be under the same ctx::mutex as perf_install_in_context(), * because we need to serialize with concurrent event creation. */ if (!exclusive_event_installable(event, ctx)) { /* exclusive and group stuff are assumed mutually exclusive */ WARN_ON_ONCE(move_group); err = -EBUSY; goto err_locked; } WARN_ON_ONCE(ctx->parent_ctx); /* * This is the point on no return; we cannot fail hereafter. This is * where we start modifying current state. */ if (move_group) { /* * See perf_event_ctx_lock() for comments on the details * of swizzling perf_event::ctx. */ perf_remove_from_context(group_leader, 0); put_ctx(gctx); list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_remove_from_context(sibling, 0); put_ctx(gctx); } /* * Wait for everybody to stop referencing the events through * the old lists, before installing it on new lists. */ synchronize_rcu(); /* * Install the group siblings before the group leader. * * Because a group leader will try and install the entire group * (through the sibling list, which is still in-tact), we can * end up with siblings installed in the wrong context. * * By installing siblings first we NO-OP because they're not * reachable through the group lists. */ list_for_each_entry(sibling, &group_leader->sibling_list, group_entry) { perf_event__state_init(sibling); perf_install_in_context(ctx, sibling, sibling->cpu); get_ctx(ctx); } /* * Removing from the context ends up with disabled * event. What we want here is event in the initial * startup state, ready to be add into new context. */ perf_event__state_init(group_leader); perf_install_in_context(ctx, group_leader, group_leader->cpu); get_ctx(ctx); } /* * Precalculate sample_data sizes; do while holding ctx::mutex such * that we're serialized against further additions and before * perf_install_in_context() which is the point the event is active and * can use these values. */ perf_event__header_size(event); perf_event__id_header_size(event); event->owner = current; perf_install_in_context(ctx, event, event->cpu); perf_unpin_context(ctx); if (move_group) perf_event_ctx_unlock(group_leader, gctx); mutex_unlock(&ctx->mutex); if (task) { mutex_unlock(&task->signal->cred_guard_mutex); put_task_struct(task); } put_online_cpus(); mutex_lock(&current->perf_event_mutex); list_add_tail(&event->owner_entry, &current->perf_event_list); mutex_unlock(&current->perf_event_mutex); /* * Drop the reference on the group_event after placing the * new event on the sibling_list. This ensures destruction * of the group leader will find the pointer to itself in * perf_group_detach(). */ fdput(group); fd_install(event_fd, event_file); return event_fd; err_locked: if (move_group) perf_event_ctx_unlock(group_leader, gctx); mutex_unlock(&ctx->mutex); /* err_file: */ fput(event_file); err_context: perf_unpin_context(ctx); put_ctx(ctx); err_alloc: /* * If event_file is set, the fput() above will have called ->release() * and that will take care of freeing the event. */ if (!event_file) free_event(event); err_cred: if (task) mutex_unlock(&task->signal->cred_guard_mutex); err_cpus: put_online_cpus(); err_task: if (task) put_task_struct(task); err_group_fd: fdput(group); err_fd: put_unused_fd(event_fd); return err; } /** * perf_event_create_kernel_counter * * @attr: attributes of the counter to create * @cpu: cpu in which the counter is bound * @task: task to profile (NULL for percpu) */ struct perf_event * perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, struct task_struct *task, perf_overflow_handler_t overflow_handler, void *context) { struct perf_event_context *ctx; struct perf_event *event; int err; /* * Get the target context (task or percpu): */ event = perf_event_alloc(attr, cpu, task, NULL, NULL, overflow_handler, context, -1); if (IS_ERR(event)) { err = PTR_ERR(event); goto err; } /* Mark owner so we could distinguish it from user events. */ event->owner = TASK_TOMBSTONE; ctx = find_get_context(event->pmu, task, event); if (IS_ERR(ctx)) { err = PTR_ERR(ctx); goto err_free; } WARN_ON_ONCE(ctx->parent_ctx); mutex_lock(&ctx->mutex); if (ctx->task == TASK_TOMBSTONE) { err = -ESRCH; goto err_unlock; } if (!exclusive_event_installable(event, ctx)) { err = -EBUSY; goto err_unlock; } perf_install_in_context(ctx, event, cpu); perf_unpin_context(ctx); mutex_unlock(&ctx->mutex); return event; err_unlock: mutex_unlock(&ctx->mutex); perf_unpin_context(ctx); put_ctx(ctx); err_free: free_event(event); err: return ERR_PTR(err); } EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) { struct perf_event_context *src_ctx; struct perf_event_context *dst_ctx; struct perf_event *event, *tmp; LIST_HEAD(events); src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx; dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx; /* * See perf_event_ctx_lock() for comments on the details * of swizzling perf_event::ctx. */ mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); list_for_each_entry_safe(event, tmp, &src_ctx->event_list, event_entry) { perf_remove_from_context(event, 0); unaccount_event_cpu(event, src_cpu); put_ctx(src_ctx); list_add(&event->migrate_entry, &events); } /* * Wait for the events to quiesce before re-instating them. */ synchronize_rcu(); /* * Re-instate events in 2 passes. * * Skip over group leaders and only install siblings on this first * pass, siblings will not get enabled without a leader, however a * leader will enable its siblings, even if those are still on the old * context. */ list_for_each_entry_safe(event, tmp, &events, migrate_entry) { if (event->group_leader == event) continue; list_del(&event->migrate_entry); if (event->state >= PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_INACTIVE; account_event_cpu(event, dst_cpu); perf_install_in_context(dst_ctx, event, dst_cpu); get_ctx(dst_ctx); } /* * Once all the siblings are setup properly, install the group leaders * to make it go. */ list_for_each_entry_safe(event, tmp, &events, migrate_entry) { list_del(&event->migrate_entry); if (event->state >= PERF_EVENT_STATE_OFF) event->state = PERF_EVENT_STATE_INACTIVE; account_event_cpu(event, dst_cpu); perf_install_in_context(dst_ctx, event, dst_cpu); get_ctx(dst_ctx); } mutex_unlock(&dst_ctx->mutex); mutex_unlock(&src_ctx->mutex); } EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); static void sync_child_event(struct perf_event *child_event, struct task_struct *child) { struct perf_event *parent_event = child_event->parent; u64 child_val; if (child_event->attr.inherit_stat) perf_event_read_event(child_event, child); child_val = perf_event_count(child_event); /* * Add back the child's count to the parent's count: */ atomic64_add(child_val, &parent_event->child_count); atomic64_add(child_event->total_time_enabled, &parent_event->child_total_time_enabled); atomic64_add(child_event->total_time_running, &parent_event->child_total_time_running); } static void perf_event_exit_event(struct perf_event *child_event, struct perf_event_context *child_ctx, struct task_struct *child) { struct perf_event *parent_event = child_event->parent; /* * Do not destroy the 'original' grouping; because of the context * switch optimization the original events could've ended up in a * random child task. * * If we were to destroy the original group, all group related * operations would cease to function properly after this random * child dies. * * Do destroy all inherited groups, we don't care about those * and being thorough is better. */ raw_spin_lock_irq(&child_ctx->lock); WARN_ON_ONCE(child_ctx->is_active); if (parent_event) perf_group_detach(child_event); list_del_event(child_event, child_ctx); child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */ raw_spin_unlock_irq(&child_ctx->lock); /* * Parent events are governed by their filedesc, retain them. */ if (!parent_event) { perf_event_wakeup(child_event); return; } /* * Child events can be cleaned up. */ sync_child_event(child_event, child); /* * Remove this event from the parent's list */ WARN_ON_ONCE(parent_event->ctx->parent_ctx); mutex_lock(&parent_event->child_mutex); list_del_init(&child_event->child_list); mutex_unlock(&parent_event->child_mutex); /* * Kick perf_poll() for is_event_hup(). */ perf_event_wakeup(parent_event); free_event(child_event); put_event(parent_event); } static void perf_event_exit_task_context(struct task_struct *child, int ctxn) { struct perf_event_context *child_ctx, *clone_ctx = NULL; struct perf_event *child_event, *next; WARN_ON_ONCE(child != current); child_ctx = perf_pin_task_context(child, ctxn); if (!child_ctx) return; /* * In order to reduce the amount of tricky in ctx tear-down, we hold * ctx::mutex over the entire thing. This serializes against almost * everything that wants to access the ctx. * * The exception is sys_perf_event_open() / * perf_event_create_kernel_count() which does find_get_context() * without ctx::mutex (it cannot because of the move_group double mutex * lock thing). See the comments in perf_install_in_context(). */ mutex_lock(&child_ctx->mutex); /* * In a single ctx::lock section, de-schedule the events and detach the * context from the task such that we cannot ever get it scheduled back * in. */ raw_spin_lock_irq(&child_ctx->lock); task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL); /* * Now that the context is inactive, destroy the task <-> ctx relation * and mark the context dead. */ RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL); put_ctx(child_ctx); /* cannot be last */ WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE); put_task_struct(current); /* cannot be last */ clone_ctx = unclone_ctx(child_ctx); raw_spin_unlock_irq(&child_ctx->lock); if (clone_ctx) put_ctx(clone_ctx); /* * Report the task dead after unscheduling the events so that we * won't get any samples after PERF_RECORD_EXIT. We can however still * get a few PERF_RECORD_READ events. */ perf_event_task(child, child_ctx, 0); list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry) perf_event_exit_event(child_event, child_ctx, child); mutex_unlock(&child_ctx->mutex); put_ctx(child_ctx); } /* * When a child task exits, feed back event values to parent events. * * Can be called with cred_guard_mutex held when called from * install_exec_creds(). */ void perf_event_exit_task(struct task_struct *child) { struct perf_event *event, *tmp; int ctxn; mutex_lock(&child->perf_event_mutex); list_for_each_entry_safe(event, tmp, &child->perf_event_list, owner_entry) { list_del_init(&event->owner_entry); /* * Ensure the list deletion is visible before we clear * the owner, closes a race against perf_release() where * we need to serialize on the owner->perf_event_mutex. */ smp_store_release(&event->owner, NULL); } mutex_unlock(&child->perf_event_mutex); for_each_task_context_nr(ctxn) perf_event_exit_task_context(child, ctxn); /* * The perf_event_exit_task_context calls perf_event_task * with child's task_ctx, which generates EXIT events for * child contexts and sets child->perf_event_ctxp[] to NULL. * At this point we need to send EXIT events to cpu contexts. */ perf_event_task(child, NULL, 0); } static void perf_free_event(struct perf_event *event, struct perf_event_context *ctx) { struct perf_event *parent = event->parent; if (WARN_ON_ONCE(!parent)) return; mutex_lock(&parent->child_mutex); list_del_init(&event->child_list); mutex_unlock(&parent->child_mutex); put_event(parent); raw_spin_lock_irq(&ctx->lock); perf_group_detach(event); list_del_event(event, ctx); raw_spin_unlock_irq(&ctx->lock); free_event(event); } /* * Free an unexposed, unused context as created by inheritance by * perf_event_init_task below, used by fork() in case of fail. * * Not all locks are strictly required, but take them anyway to be nice and * help out with the lockdep assertions. */ void perf_event_free_task(struct task_struct *task) { struct perf_event_context *ctx; struct perf_event *event, *tmp; int ctxn; for_each_task_context_nr(ctxn) { ctx = task->perf_event_ctxp[ctxn]; if (!ctx) continue; mutex_lock(&ctx->mutex); again: list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry) perf_free_event(event, ctx); list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry) perf_free_event(event, ctx); if (!list_empty(&ctx->pinned_groups) || !list_empty(&ctx->flexible_groups)) goto again; mutex_unlock(&ctx->mutex); put_ctx(ctx); } } void perf_event_delayed_put(struct task_struct *task) { int ctxn; for_each_task_context_nr(ctxn) WARN_ON_ONCE(task->perf_event_ctxp[ctxn]); } struct file *perf_event_get(unsigned int fd) { struct file *file; file = fget_raw(fd); if (!file) return ERR_PTR(-EBADF); if (file->f_op != &perf_fops) { fput(file); return ERR_PTR(-EBADF); } return file; } const struct perf_event_attr *perf_event_attrs(struct perf_event *event) { if (!event) return ERR_PTR(-EINVAL); return &event->attr; } /* * inherit a event from parent task to child task: */ static struct perf_event * inherit_event(struct perf_event *parent_event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, struct perf_event *group_leader, struct perf_event_context *child_ctx) { enum perf_event_active_state parent_state = parent_event->state; struct perf_event *child_event; unsigned long flags; /* * Instead of creating recursive hierarchies of events, * we link inherited events back to the original parent, * which has a filp for sure, which we use as the reference * count: */ if (parent_event->parent) parent_event = parent_event->parent; child_event = perf_event_alloc(&parent_event->attr, parent_event->cpu, child, group_leader, parent_event, NULL, NULL, -1); if (IS_ERR(child_event)) return child_event; /* * is_orphaned_event() and list_add_tail(&parent_event->child_list) * must be under the same lock in order to serialize against * perf_event_release_kernel(), such that either we must observe * is_orphaned_event() or they will observe us on the child_list. */ mutex_lock(&parent_event->child_mutex); if (is_orphaned_event(parent_event) || !atomic_long_inc_not_zero(&parent_event->refcount)) { mutex_unlock(&parent_event->child_mutex); free_event(child_event); return NULL; } get_ctx(child_ctx); /* * Make the child state follow the state of the parent event, * not its attr.disabled bit. We hold the parent's mutex, * so we won't race with perf_event_{en, dis}able_family. */ if (parent_state >= PERF_EVENT_STATE_INACTIVE) child_event->state = PERF_EVENT_STATE_INACTIVE; else child_event->state = PERF_EVENT_STATE_OFF; if (parent_event->attr.freq) { u64 sample_period = parent_event->hw.sample_period; struct hw_perf_event *hwc = &child_event->hw; hwc->sample_period = sample_period; hwc->last_period = sample_period; local64_set(&hwc->period_left, sample_period); } child_event->ctx = child_ctx; child_event->overflow_handler = parent_event->overflow_handler; child_event->overflow_handler_context = parent_event->overflow_handler_context; /* * Precalculate sample_data sizes */ perf_event__header_size(child_event); perf_event__id_header_size(child_event); /* * Link it up in the child's context: */ raw_spin_lock_irqsave(&child_ctx->lock, flags); add_event_to_ctx(child_event, child_ctx); raw_spin_unlock_irqrestore(&child_ctx->lock, flags); /* * Link this into the parent event's child list */ list_add_tail(&child_event->child_list, &parent_event->child_list); mutex_unlock(&parent_event->child_mutex); return child_event; } static int inherit_group(struct perf_event *parent_event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, struct perf_event_context *child_ctx) { struct perf_event *leader; struct perf_event *sub; struct perf_event *child_ctr; leader = inherit_event(parent_event, parent, parent_ctx, child, NULL, child_ctx); if (IS_ERR(leader)) return PTR_ERR(leader); list_for_each_entry(sub, &parent_event->sibling_list, group_entry) { child_ctr = inherit_event(sub, parent, parent_ctx, child, leader, child_ctx); if (IS_ERR(child_ctr)) return PTR_ERR(child_ctr); } return 0; } static int inherit_task_group(struct perf_event *event, struct task_struct *parent, struct perf_event_context *parent_ctx, struct task_struct *child, int ctxn, int *inherited_all) { int ret; struct perf_event_context *child_ctx; if (!event->attr.inherit) { *inherited_all = 0; return 0; } child_ctx = child->perf_event_ctxp[ctxn]; if (!child_ctx) { /* * This is executed from the parent task context, so * inherit events that have been marked for cloning. * First allocate and initialize a context for the * child. */ child_ctx = alloc_perf_context(parent_ctx->pmu, child); if (!child_ctx) return -ENOMEM; child->perf_event_ctxp[ctxn] = child_ctx; } ret = inherit_group(event, parent, parent_ctx, child, child_ctx); if (ret) *inherited_all = 0; return ret; } /* * Initialize the perf_event context in task_struct */ static int perf_event_init_context(struct task_struct *child, int ctxn) { struct perf_event_context *child_ctx, *parent_ctx; struct perf_event_context *cloned_ctx; struct perf_event *event; struct task_struct *parent = current; int inherited_all = 1; unsigned long flags; int ret = 0; if (likely(!parent->perf_event_ctxp[ctxn])) return 0; /* * If the parent's context is a clone, pin it so it won't get * swapped under us. */ parent_ctx = perf_pin_task_context(parent, ctxn); if (!parent_ctx) return 0; /* * No need to check if parent_ctx != NULL here; since we saw * it non-NULL earlier, the only reason for it to become NULL * is if we exit, and since we're currently in the middle of * a fork we can't be exiting at the same time. */ /* * Lock the parent list. No need to lock the child - not PID * hashed yet and not running, so nobody can access it. */ mutex_lock(&parent_ctx->mutex); /* * We dont have to disable NMIs - we are only looking at * the list, not manipulating it: */ list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) { ret = inherit_task_group(event, parent, parent_ctx, child, ctxn, &inherited_all); if (ret) break; } /* * We can't hold ctx->lock when iterating the ->flexible_group list due * to allocations, but we need to prevent rotation because * rotate_ctx() will change the list from interrupt context. */ raw_spin_lock_irqsave(&parent_ctx->lock, flags); parent_ctx->rotate_disable = 1; raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) { ret = inherit_task_group(event, parent, parent_ctx, child, ctxn, &inherited_all); if (ret) break; } raw_spin_lock_irqsave(&parent_ctx->lock, flags); parent_ctx->rotate_disable = 0; child_ctx = child->perf_event_ctxp[ctxn]; if (child_ctx && inherited_all) { /* * Mark the child context as a clone of the parent * context, or of whatever the parent is a clone of. * * Note that if the parent is a clone, the holding of * parent_ctx->lock avoids it from being uncloned. */ cloned_ctx = parent_ctx->parent_ctx; if (cloned_ctx) { child_ctx->parent_ctx = cloned_ctx; child_ctx->parent_gen = parent_ctx->parent_gen; } else { child_ctx->parent_ctx = parent_ctx; child_ctx->parent_gen = parent_ctx->generation; } get_ctx(child_ctx->parent_ctx); } raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); mutex_unlock(&parent_ctx->mutex); perf_unpin_context(parent_ctx); put_ctx(parent_ctx); return ret; } /* * Initialize the perf_event context in task_struct */ int perf_event_init_task(struct task_struct *child) { int ctxn, ret; memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp)); mutex_init(&child->perf_event_mutex); INIT_LIST_HEAD(&child->perf_event_list); for_each_task_context_nr(ctxn) { ret = perf_event_init_context(child, ctxn); if (ret) { perf_event_free_task(child); return ret; } } return 0; } static void __init perf_event_init_all_cpus(void) { struct swevent_htable *swhash; int cpu; for_each_possible_cpu(cpu) { swhash = &per_cpu(swevent_htable, cpu); mutex_init(&swhash->hlist_mutex); INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu)); INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); #ifdef CONFIG_CGROUP_PERF INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu)); #endif INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); } } int perf_event_init_cpu(unsigned int cpu) { struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); mutex_lock(&swhash->hlist_mutex); if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { struct swevent_hlist *hlist; hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); WARN_ON(!hlist); rcu_assign_pointer(swhash->swevent_hlist, hlist); } mutex_unlock(&swhash->hlist_mutex); return 0; } #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE static void __perf_event_exit_context(void *__info) { struct perf_event_context *ctx = __info; struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); struct perf_event *event; raw_spin_lock(&ctx->lock); list_for_each_entry(event, &ctx->event_list, event_entry) __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); raw_spin_unlock(&ctx->lock); } static void perf_event_exit_cpu_context(int cpu) { struct perf_event_context *ctx; struct pmu *pmu; int idx; idx = srcu_read_lock(&pmus_srcu); list_for_each_entry_rcu(pmu, &pmus, entry) { ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx; mutex_lock(&ctx->mutex); smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); mutex_unlock(&ctx->mutex); } srcu_read_unlock(&pmus_srcu, idx); } #else static void perf_event_exit_cpu_context(int cpu) { } #endif int perf_event_exit_cpu(unsigned int cpu) { perf_event_exit_cpu_context(cpu); return 0; } static int perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) { int cpu; for_each_online_cpu(cpu) perf_event_exit_cpu(cpu); return NOTIFY_OK; } /* * Run the perf reboot notifier at the very last possible moment so that * the generic watchdog code runs as long as possible. */ static struct notifier_block perf_reboot_notifier = { .notifier_call = perf_reboot, .priority = INT_MIN, }; void __init perf_event_init(void) { int ret; idr_init(&pmu_idr); perf_event_init_all_cpus(); init_srcu_struct(&pmus_srcu); perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); perf_pmu_register(&perf_cpu_clock, NULL, -1); perf_pmu_register(&perf_task_clock, NULL, -1); perf_tp_register(); perf_event_init_cpu(smp_processor_id()); register_reboot_notifier(&perf_reboot_notifier); ret = init_hw_breakpoint(); WARN(ret, "hw_breakpoint initialization failed with: %d", ret); /* * Build time assertion that we keep the data_head at the intended * location. IOW, validation we got the __reserved[] size right. */ BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) != 1024); } ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, char *page) { struct perf_pmu_events_attr *pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr); if (pmu_attr->event_str) return sprintf(page, "%s\n", pmu_attr->event_str); return 0; } EXPORT_SYMBOL_GPL(perf_event_sysfs_show); static int __init perf_event_sysfs_init(void) { struct pmu *pmu; int ret; mutex_lock(&pmus_lock); ret = bus_register(&pmu_bus); if (ret) goto unlock; list_for_each_entry(pmu, &pmus, entry) { if (!pmu->name || pmu->type < 0) continue; ret = pmu_dev_alloc(pmu); WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); } pmu_bus_running = 1; ret = 0; unlock: mutex_unlock(&pmus_lock); return ret; } device_initcall(perf_event_sysfs_init); #ifdef CONFIG_CGROUP_PERF static struct cgroup_subsys_state * perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) { struct perf_cgroup *jc; jc = kzalloc(sizeof(*jc), GFP_KERNEL); if (!jc) return ERR_PTR(-ENOMEM); jc->info = alloc_percpu(struct perf_cgroup_info); if (!jc->info) { kfree(jc); return ERR_PTR(-ENOMEM); } return &jc->css; } static void perf_cgroup_css_free(struct cgroup_subsys_state *css) { struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); free_percpu(jc->info); kfree(jc); } static int __perf_cgroup_move(void *info) { struct task_struct *task = info; rcu_read_lock(); perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN); rcu_read_unlock(); return 0; } static void perf_cgroup_attach(struct cgroup_taskset *tset) { struct task_struct *task; struct cgroup_subsys_state *css; cgroup_taskset_for_each(task, css, tset) task_function_call(task, __perf_cgroup_move, task); } struct cgroup_subsys perf_event_cgrp_subsys = { .css_alloc = perf_cgroup_css_alloc, .css_free = perf_cgroup_css_free, .attach = perf_cgroup_attach, }; #endif /* CONFIG_CGROUP_PERF */
./CrossVul/dataset_final_sorted/CWE-190/c/good_3027_0
crossvul-cpp_data_good_1943_2
/* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * 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 Redis 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. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> /* This function provide us access to the original libc free(). This is useful * for instance to free results obtained by backtrace_symbols(). We need * to define this function before including zmalloc.h that may shadow the * free implementation if we use jemalloc or another non standard allocator. */ void zlibc_free(void *ptr) { free(ptr); } #include <string.h> #include <pthread.h> #include "config.h" #include "zmalloc.h" #include "atomicvar.h" #ifdef HAVE_MALLOC_SIZE #define PREFIX_SIZE (0) #else #if defined(__sun) || defined(__sparc) || defined(__sparc__) #define PREFIX_SIZE (sizeof(long long)) #else #define PREFIX_SIZE (sizeof(size_t)) #endif #endif #if PREFIX_SIZE > 0 #define ASSERT_NO_SIZE_OVERFLOW(sz) assert((sz) + PREFIX_SIZE > (sz)) #else #define ASSERT_NO_SIZE_OVERFLOW(sz) #endif /* Explicitly override malloc/free etc when using tcmalloc. */ #if defined(USE_TCMALLOC) #define malloc(size) tc_malloc(size) #define calloc(count,size) tc_calloc(count,size) #define realloc(ptr,size) tc_realloc(ptr,size) #define free(ptr) tc_free(ptr) #elif defined(USE_JEMALLOC) #define malloc(size) je_malloc(size) #define calloc(count,size) je_calloc(count,size) #define realloc(ptr,size) je_realloc(ptr,size) #define free(ptr) je_free(ptr) #define mallocx(size,flags) je_mallocx(size,flags) #define dallocx(ptr,flags) je_dallocx(ptr,flags) #endif #define update_zmalloc_stat_alloc(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ atomicIncr(used_memory,__n); \ } while(0) #define update_zmalloc_stat_free(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ atomicDecr(used_memory,__n); \ } while(0) static size_t used_memory = 0; pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; static void zmalloc_default_oom(size_t size) { fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n", size); fflush(stderr); abort(); } static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom; void *zmalloc(size_t size) { ASSERT_NO_SIZE_OVERFLOW(size); void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } /* Allocation and free functions that bypass the thread cache * and go straight to the allocator arena bins. * Currently implemented only for jemalloc. Used for online defragmentation. */ #ifdef HAVE_DEFRAG void *zmalloc_no_tcache(size_t size) { ASSERT_NO_SIZE_OVERFLOW(size); void *ptr = mallocx(size+PREFIX_SIZE, MALLOCX_TCACHE_NONE); if (!ptr) zmalloc_oom_handler(size); update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; } void zfree_no_tcache(void *ptr) { if (ptr == NULL) return; update_zmalloc_stat_free(zmalloc_size(ptr)); dallocx(ptr, MALLOCX_TCACHE_NONE); } #endif void *zcalloc(size_t size) { ASSERT_NO_SIZE_OVERFLOW(size); void *ptr = calloc(1, size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } void *zrealloc(void *ptr, size_t size) { ASSERT_NO_SIZE_OVERFLOW(size); #ifndef HAVE_MALLOC_SIZE void *realptr; #endif size_t oldsize; void *newptr; if (size == 0 && ptr != NULL) { zfree(ptr); return NULL; } if (ptr == NULL) return zmalloc(size); #ifdef HAVE_MALLOC_SIZE oldsize = zmalloc_size(ptr); newptr = realloc(ptr,size); if (!newptr) zmalloc_oom_handler(size); update_zmalloc_stat_free(oldsize); update_zmalloc_stat_alloc(zmalloc_size(newptr)); return newptr; #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); newptr = realloc(realptr,size+PREFIX_SIZE); if (!newptr) zmalloc_oom_handler(size); *((size_t*)newptr) = size; update_zmalloc_stat_free(oldsize+PREFIX_SIZE); update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)newptr+PREFIX_SIZE; #endif } /* Provide zmalloc_size() for systems where this function is not provided by * malloc itself, given that in that case we store a header with this * information as the first bytes of every allocation. */ #ifndef HAVE_MALLOC_SIZE size_t zmalloc_size(void *ptr) { void *realptr = (char*)ptr-PREFIX_SIZE; size_t size = *((size_t*)realptr); return size+PREFIX_SIZE; } size_t zmalloc_usable(void *ptr) { return zmalloc_size(ptr)-PREFIX_SIZE; } #endif void zfree(void *ptr) { #ifndef HAVE_MALLOC_SIZE void *realptr; size_t oldsize; #endif if (ptr == NULL) return; #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_free(zmalloc_size(ptr)); free(ptr); #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); update_zmalloc_stat_free(oldsize+PREFIX_SIZE); free(realptr); #endif } char *zstrdup(const char *s) { size_t l = strlen(s)+1; char *p = zmalloc(l); memcpy(p,s,l); return p; } size_t zmalloc_used_memory(void) { size_t um; atomicGet(used_memory,um); return um; } void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) { zmalloc_oom_handler = oom_handler; } /* Get the RSS information in an OS-specific way. * * WARNING: the function zmalloc_get_rss() is not designed to be fast * and may not be called in the busy loops where Redis tries to release * memory expiring or swapping out objects. * * For this kind of "fast RSS reporting" usages use instead the * function RedisEstimateRSS() that is a much faster (and less precise) * version of the function. */ #if defined(HAVE_PROC_STAT) #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> size_t zmalloc_get_rss(void) { int page = sysconf(_SC_PAGESIZE); size_t rss; char buf[4096]; char filename[256]; int fd, count; char *p, *x; snprintf(filename,256,"/proc/%d/stat",getpid()); if ((fd = open(filename,O_RDONLY)) == -1) return 0; if (read(fd,buf,4096) <= 0) { close(fd); return 0; } close(fd); p = buf; count = 23; /* RSS is the 24th field in /proc/<pid>/stat */ while(p && count--) { p = strchr(p,' '); if (p) p++; } if (!p) return 0; x = strchr(p,' '); if (!x) return 0; *x = '\0'; rss = strtoll(p,NULL,10); rss *= page; return rss; } #elif defined(HAVE_TASKINFO) #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/sysctl.h> #include <mach/task.h> #include <mach/mach_init.h> size_t zmalloc_get_rss(void) { task_t task = MACH_PORT_NULL; struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS) return 0; task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); return t_info.resident_size; } #elif defined(__FreeBSD__) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/user.h> #include <unistd.h> size_t zmalloc_get_rss(void) { struct kinfo_proc info; size_t infolen = sizeof(info); int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); if (sysctl(mib, 4, &info, &infolen, NULL, 0) == 0) return (size_t)info.ki_rssize; return 0L; } #elif defined(__NetBSD__) #include <sys/types.h> #include <sys/sysctl.h> #include <unistd.h> size_t zmalloc_get_rss(void) { struct kinfo_proc2 info; size_t infolen = sizeof(info); int mib[6]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); mib[4] = sizeof(info); mib[5] = 1; if (sysctl(mib, 4, &info, &infolen, NULL, 0) == 0) return (size_t)info.p_vm_rssize; return 0L; } #else size_t zmalloc_get_rss(void) { /* If we can't get the RSS in an OS-specific way for this system just * return the memory usage we estimated in zmalloc().. * * Fragmentation will appear to be always 1 (no fragmentation) * of course... */ return zmalloc_used_memory(); } #endif #if defined(USE_JEMALLOC) int zmalloc_get_allocator_info(size_t *allocated, size_t *active, size_t *resident) { uint64_t epoch = 1; size_t sz; *allocated = *resident = *active = 0; /* Update the statistics cached by mallctl. */ sz = sizeof(epoch); je_mallctl("epoch", &epoch, &sz, &epoch, sz); sz = sizeof(size_t); /* Unlike RSS, this does not include RSS from shared libraries and other non * heap mappings. */ je_mallctl("stats.resident", resident, &sz, NULL, 0); /* Unlike resident, this doesn't not include the pages jemalloc reserves * for re-use (purge will clean that). */ je_mallctl("stats.active", active, &sz, NULL, 0); /* Unlike zmalloc_used_memory, this matches the stats.resident by taking * into account all allocations done by this process (not only zmalloc). */ je_mallctl("stats.allocated", allocated, &sz, NULL, 0); return 1; } void set_jemalloc_bg_thread(int enable) { /* let jemalloc do purging asynchronously, required when there's no traffic * after flushdb */ char val = !!enable; je_mallctl("background_thread", NULL, 0, &val, 1); } int jemalloc_purge() { /* return all unused (reserved) pages to the OS */ char tmp[32]; unsigned narenas = 0; size_t sz = sizeof(unsigned); if (!je_mallctl("arenas.narenas", &narenas, &sz, NULL, 0)) { sprintf(tmp, "arena.%d.purge", narenas); if (!je_mallctl(tmp, NULL, 0, NULL, 0)) return 0; } return -1; } #else int zmalloc_get_allocator_info(size_t *allocated, size_t *active, size_t *resident) { *allocated = *resident = *active = 0; return 1; } void set_jemalloc_bg_thread(int enable) { ((void)(enable)); } int jemalloc_purge() { return 0; } #endif #if defined(__APPLE__) /* For proc_pidinfo() used later in zmalloc_get_smap_bytes_by_field(). * Note that this file cannot be included in zmalloc.h because it includes * a Darwin queue.h file where there is a "LIST_HEAD" macro (!) defined * conficting with Redis user code. */ #include <libproc.h> #endif /* Get the sum of the specified field (converted form kb to bytes) in * /proc/self/smaps. The field must be specified with trailing ":" as it * apperas in the smaps output. * * If a pid is specified, the information is extracted for such a pid, * otherwise if pid is -1 the information is reported is about the * current process. * * Example: zmalloc_get_smap_bytes_by_field("Rss:",-1); */ #if defined(HAVE_PROC_SMAPS) size_t zmalloc_get_smap_bytes_by_field(char *field, long pid) { char line[1024]; size_t bytes = 0; int flen = strlen(field); FILE *fp; if (pid == -1) { fp = fopen("/proc/self/smaps","r"); } else { char filename[128]; snprintf(filename,sizeof(filename),"/proc/%ld/smaps",pid); fp = fopen(filename,"r"); } if (!fp) return 0; while(fgets(line,sizeof(line),fp) != NULL) { if (strncmp(line,field,flen) == 0) { char *p = strchr(line,'k'); if (p) { *p = '\0'; bytes += strtol(line+flen,NULL,10) * 1024; } } } fclose(fp); return bytes; } #else /* Get sum of the specified field from libproc api call. * As there are per page value basis we need to convert * them accordingly. * * Note that AnonHugePages is a no-op as THP feature * is not supported in this platform */ size_t zmalloc_get_smap_bytes_by_field(char *field, long pid) { #if defined(__APPLE__) struct proc_regioninfo pri; if (proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, PROC_PIDREGIONINFO_SIZE) == PROC_PIDREGIONINFO_SIZE) { if (!strcmp(field, "Private_Dirty:")) { return (size_t)pri.pri_pages_dirtied * 4096; } else if (!strcmp(field, "Rss:")) { return (size_t)pri.pri_pages_resident * 4096; } else if (!strcmp(field, "AnonHugePages:")) { return 0; } } return 0; #endif ((void) field); ((void) pid); return 0; } #endif size_t zmalloc_get_private_dirty(long pid) { return zmalloc_get_smap_bytes_by_field("Private_Dirty:",pid); } /* Returns the size of physical memory (RAM) in bytes. * It looks ugly, but this is the cleanest way to achieve cross platform results. * Cleaned up from: * * http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system * * Note that this function: * 1) Was released under the following CC attribution license: * http://creativecommons.org/licenses/by/3.0/deed.en_US. * 2) Was originally implemented by David Robert Nadeau. * 3) Was modified for Redis by Matt Stancliff. * 4) This note exists in order to comply with the original license. */ size_t zmalloc_get_memory_size(void) { #if defined(__unix__) || defined(__unix) || defined(unix) || \ (defined(__APPLE__) && defined(__MACH__)) #if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64)) int mib[2]; mib[0] = CTL_HW; #if defined(HW_MEMSIZE) mib[1] = HW_MEMSIZE; /* OSX. --------------------- */ #elif defined(HW_PHYSMEM64) mib[1] = HW_PHYSMEM64; /* NetBSD, OpenBSD. --------- */ #endif int64_t size = 0; /* 64-bit */ size_t len = sizeof(size); if (sysctl( mib, 2, &size, &len, NULL, 0) == 0) return (size_t)size; return 0L; /* Failed? */ #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */ return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE); #elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM)) /* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */ int mib[2]; mib[0] = CTL_HW; #if defined(HW_REALMEM) mib[1] = HW_REALMEM; /* FreeBSD. ----------------- */ #elif defined(HW_PHYSMEM) mib[1] = HW_PHYSMEM; /* Others. ------------------ */ #endif unsigned int size = 0; /* 32-bit */ size_t len = sizeof(size); if (sysctl(mib, 2, &size, &len, NULL, 0) == 0) return (size_t)size; return 0L; /* Failed? */ #else return 0L; /* Unknown method to get the data. */ #endif #else return 0L; /* Unknown OS. */ #endif } #ifdef REDIS_TEST #define UNUSED(x) ((void)(x)) int zmalloc_test(int argc, char **argv) { void *ptr; UNUSED(argc); UNUSED(argv); printf("Initial used memory: %zu\n", zmalloc_used_memory()); ptr = zmalloc(123); printf("Allocated 123 bytes; used: %zu\n", zmalloc_used_memory()); ptr = zrealloc(ptr, 456); printf("Reallocated to 456 bytes; used: %zu\n", zmalloc_used_memory()); zfree(ptr); printf("Freed pointer; used: %zu\n", zmalloc_used_memory()); return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_1943_2
crossvul-cpp_data_good_1834_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M EEEEE M M OOO RRRR Y Y % % MM MM E MM MM O O R R Y Y % % M M M EEE M M M O O RRRR Y % % M M E M M O O R R Y % % M M EEEEE M M OOO R R Y % % % % % % MagickCore Memory Allocation Methods % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segregate our memory requirements from any program that calls our API. This % should help reduce the risk of others changing our program state or causing % memory corruption. % % Our custom memory allocation manager implements a best-fit allocation policy % using segregated free lists. It uses a linear distribution of size classes % for lower sizes and a power of two distribution of size classes at higher % sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits." % written by Yoo C. Chung. % % By default, ANSI memory methods are called (e.g. malloc). Use the % custom memory allocator by defining MAGICKCORE_ZERO_CONFIGURATION_SUPPORT % to allocate memory with private anonymous mapping rather than from the % heap. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/string_.h" #include "MagickCore/utility-private.h" /* Define declarations. */ #define BlockFooter(block,size) \ ((size_t *) ((char *) (block)+(size)-2*sizeof(size_t))) #define BlockHeader(block) ((size_t *) (block)-1) #define BlockSize 4096 #define BlockThreshold 1024 #define MaxBlockExponent 16 #define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1) #define MaxSegments 1024 #define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed) #define NextBlock(block) ((char *) (block)+SizeOfBlock(block)) #define NextBlockInList(block) (*(void **) (block)) #define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2))) #define PreviousBlockBit 0x01 #define PreviousBlockInList(block) (*((void **) (block)+1)) #define SegmentSize (2*1024*1024) #define SizeMask (~0x01) #define SizeOfBlock(block) (*BlockHeader(block) & SizeMask) /* Typedef declarations. */ typedef enum { UndefinedVirtualMemory, AlignedVirtualMemory, MapVirtualMemory, UnalignedVirtualMemory } VirtualMemoryType; typedef struct _DataSegmentInfo { void *allocation, *bound; MagickBooleanType mapped; size_t length; struct _DataSegmentInfo *previous, *next; } DataSegmentInfo; typedef struct _MagickMemoryMethods { AcquireMemoryHandler acquire_memory_handler; ResizeMemoryHandler resize_memory_handler; DestroyMemoryHandler destroy_memory_handler; } MagickMemoryMethods; struct _MemoryInfo { char filename[MagickPathExtent]; VirtualMemoryType type; size_t length; void *blob; size_t signature; }; typedef struct _MemoryPool { size_t allocation; void *blocks[MaxBlocks+1]; size_t number_segments; DataSegmentInfo *segments[MaxSegments], segment_pool[MaxSegments]; } MemoryPool; /* Global declarations. */ #if defined _MSC_VER static void* MSCMalloc(size_t size) { return malloc(size); } static void* MSCRealloc(void* ptr, size_t size) { return realloc(ptr, size); } static void MSCFree(void* ptr) { free(ptr); } #endif static MagickMemoryMethods memory_methods = { #if defined _MSC_VER (AcquireMemoryHandler) MSCMalloc, (ResizeMemoryHandler) MSCRealloc, (DestroyMemoryHandler) MSCFree #else (AcquireMemoryHandler) malloc, (ResizeMemoryHandler) realloc, (DestroyMemoryHandler) free #endif }; #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) static MemoryPool memory_pool; static SemaphoreInfo *memory_semaphore = (SemaphoreInfo *) NULL; static volatile DataSegmentInfo *free_segments = (DataSegmentInfo *) NULL; /* Forward declarations. */ static MagickBooleanType ExpandHeap(size_t); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e A l i g n e d M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireAlignedMemory() returns a pointer to a block of memory at least size % bytes whose address is a multiple of 16*sizeof(void *). % % The format of the AcquireAlignedMemory method is: % % void *AcquireAlignedMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { errno=ENOMEM; return((void *) NULL); } memory=NULL; alignment=CACHE_LINE_SIZE; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e B l o c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireBlock() returns a pointer to a block of memory at least size bytes % suitably aligned for any use. % % The format of the AcquireBlock method is: % % void *AcquireBlock(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ static inline size_t AllocationPolicy(size_t size) { register size_t blocksize; /* The linear distribution. */ assert(size != 0); assert(size % (4*sizeof(size_t)) == 0); if (size <= BlockThreshold) return(size/(4*sizeof(size_t))); /* Check for the largest block size. */ if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L)))) return(MaxBlocks-1L); /* Otherwise use a power of two distribution. */ blocksize=BlockThreshold/(4*sizeof(size_t)); for ( ; size > BlockThreshold; size/=2) blocksize++; assert(blocksize > (BlockThreshold/(4*sizeof(size_t)))); assert(blocksize < (MaxBlocks-1L)); return(blocksize); } static inline void InsertFreeBlock(void *block,const size_t i) { register void *next, *previous; size_t size; size=SizeOfBlock(block); previous=(void *) NULL; next=memory_pool.blocks[i]; while ((next != (void *) NULL) && (SizeOfBlock(next) < size)) { previous=next; next=NextBlockInList(next); } PreviousBlockInList(block)=previous; NextBlockInList(block)=next; if (previous != (void *) NULL) NextBlockInList(previous)=block; else memory_pool.blocks[i]=block; if (next != (void *) NULL) PreviousBlockInList(next)=block; } static inline void RemoveFreeBlock(void *block,const size_t i) { register void *next, *previous; next=NextBlockInList(block); previous=PreviousBlockInList(block); if (previous == (void *) NULL) memory_pool.blocks[i]=next; else NextBlockInList(previous)=next; if (next != (void *) NULL) PreviousBlockInList(next)=previous; } static void *AcquireBlock(size_t size) { register size_t i; register void *block; /* Find free block. */ size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t)); i=AllocationPolicy(size); block=memory_pool.blocks[i]; while ((block != (void *) NULL) && (SizeOfBlock(block) < size)) block=NextBlockInList(block); if (block == (void *) NULL) { i++; while (memory_pool.blocks[i] == (void *) NULL) i++; block=memory_pool.blocks[i]; if (i >= MaxBlocks) return((void *) NULL); } assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0); assert(SizeOfBlock(block) >= size); RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block))); if (SizeOfBlock(block) > size) { size_t blocksize; void *next; /* Split block. */ next=(char *) block+size; blocksize=SizeOfBlock(block)-size; *BlockHeader(next)=blocksize; *BlockFooter(next,blocksize)=blocksize; InsertFreeBlock(next,AllocationPolicy(blocksize)); *BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask); } assert(size == SizeOfBlock(block)); *BlockHeader(NextBlock(block))|=PreviousBlockBit; memory_pool.allocation+=size; return(block); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMagickMemory() returns a pointer to a block of memory at least size % bytes suitably aligned for any use. % % The format of the AcquireMagickMemory method is: % % void *AcquireMagickMemory(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *AcquireMagickMemory(const size_t size) { register void *memory; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size); #else if (memory_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&memory_semaphore); if (free_segments == (DataSegmentInfo *) NULL) { LockSemaphoreInfo(memory_semaphore); if (free_segments == (DataSegmentInfo *) NULL) { register ssize_t i; assert(2*sizeof(size_t) > (size_t) (~SizeMask)); (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool)); memory_pool.allocation=SegmentSize; memory_pool.blocks[MaxBlocks]=(void *) (-1); for (i=0; i < MaxSegments; i++) { if (i != 0) memory_pool.segment_pool[i].previous= (&memory_pool.segment_pool[i-1]); if (i != (MaxSegments-1)) memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]); } free_segments=(&memory_pool.segment_pool[0]); } UnlockSemaphoreInfo(memory_semaphore); } LockSemaphoreInfo(memory_semaphore); memory=AcquireBlock(size == 0 ? 1UL : size); if (memory == (void *) NULL) { if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse) memory=AcquireBlock(size == 0 ? 1UL : size); } UnlockSemaphoreInfo(memory_semaphore); #endif return(memory); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumMemory() returns a pointer to a block of memory at least % count * quantum bytes suitably aligned for any use. % % The format of the AcquireQuantumMemory method is: % % void *AcquireQuantumMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum) { size_t size; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { errno=ENOMEM; return((void *) NULL); } return(AcquireMagickMemory(size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e V i r t u a l M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireVirtualMemory() allocates a pointer to a block of memory at least size % bytes suitably aligned for any use. % % The format of the AcquireVirtualMemory method is: % % MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(DiskResource,length) != MagickFalse)) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file == -1) RelinquishMagickResource(DiskResource,length); else { if ((lseek(file,length-1,SEEK_SET) < 0) || (write(file,"",1) != 1)) RelinquishMagickResource(DiskResource,length); else { if (AcquireMagickResource(MapResource,length) == MagickFalse) RelinquishMagickResource(DiskResource,length); else { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else { RelinquishMagickResource(MapResource,length); RelinquishMagickResource(DiskResource,length); } } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyMagickMemory() copies size bytes from memory area source to the % destination. Copying between objects that overlap will take place % correctly. It returns destination. % % The format of the CopyMagickMemory method is: % % void *CopyMagickMemory(void *destination,const void *source, % const size_t size) % % A description of each parameter follows: % % o destination: the destination. % % o source: the source. % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *CopyMagickMemory(void *destination,const void *source, const size_t size) { register const unsigned char *p; register unsigned char *q; assert(destination != (void *) NULL); assert(source != (const void *) NULL); p=(const unsigned char *) source; q=(unsigned char *) destination; if (((q+size) < p) || (q > (p+size))) switch (size) { default: return(memcpy(destination,source,size)); case 8: *q++=(*p++); case 7: *q++=(*p++); case 6: *q++=(*p++); case 5: *q++=(*p++); case 4: *q++=(*p++); case 3: *q++=(*p++); case 2: *q++=(*p++); case 1: *q++=(*p++); case 0: return(destination); } return(memmove(destination,source,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagickMemory() deallocates memory associated with the memory manager. % % The format of the DestroyMagickMemory method is: % % DestroyMagickMemory(void) % */ MagickExport void DestroyMagickMemory(void) { #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) register ssize_t i; if (memory_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&memory_semaphore); LockSemaphoreInfo(memory_semaphore); for (i=0; i < (ssize_t) memory_pool.number_segments; i++) if (memory_pool.segments[i]->mapped == MagickFalse) memory_methods.destroy_memory_handler( memory_pool.segments[i]->allocation); else (void) UnmapBlob(memory_pool.segments[i]->allocation, memory_pool.segments[i]->length); free_segments=(DataSegmentInfo *) NULL; (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool)); UnlockSemaphoreInfo(memory_semaphore); RelinquishSemaphoreInfo(&memory_semaphore); #endif } #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d H e a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandHeap() get more memory from the system. It returns MagickTrue on % success otherwise MagickFalse. % % The format of the ExpandHeap method is: % % MagickBooleanType ExpandHeap(size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes we require. % */ static MagickBooleanType ExpandHeap(size_t size) { DataSegmentInfo *segment_info; MagickBooleanType mapped; register ssize_t i; register void *block; size_t blocksize; void *segment; blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize; assert(memory_pool.number_segments < MaxSegments); segment=MapBlob(-1,IOMode,0,blocksize); mapped=segment != (void *) NULL ? MagickTrue : MagickFalse; if (segment == (void *) NULL) segment=(void *) memory_methods.acquire_memory_handler(blocksize); if (segment == (void *) NULL) return(MagickFalse); segment_info=(DataSegmentInfo *) free_segments; free_segments=segment_info->next; segment_info->mapped=mapped; segment_info->length=blocksize; segment_info->allocation=segment; segment_info->bound=(char *) segment+blocksize; i=(ssize_t) memory_pool.number_segments-1; for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--) memory_pool.segments[i+1]=memory_pool.segments[i]; memory_pool.segments[i+1]=segment_info; memory_pool.number_segments++; size=blocksize-12*sizeof(size_t); block=(char *) segment_info->allocation+4*sizeof(size_t); *BlockHeader(block)=size | PreviousBlockBit; *BlockFooter(block,size)=size; InsertFreeBlock(block,AllocationPolicy(size)); block=NextBlock(block); assert(block < segment_info->bound); *BlockHeader(block)=2*sizeof(size_t); *BlockHeader(NextBlock(block))=PreviousBlockBit; return(MagickTrue); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k M e m o r y M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy % memory. % % The format of the GetMagickMemoryMethods() method is: % % void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler, % ResizeMemoryHandler *resize_memory_handler, % DestroyMemoryHandler *destroy_memory_handler) % % A description of each parameter follows: % % o acquire_memory_handler: method to acquire memory (e.g. malloc). % % o resize_memory_handler: method to resize memory (e.g. realloc). % % o destroy_memory_handler: method to destroy memory (e.g. free). % */ MagickExport void GetMagickMemoryMethods( AcquireMemoryHandler *acquire_memory_handler, ResizeMemoryHandler *resize_memory_handler, DestroyMemoryHandler *destroy_memory_handler) { assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL); assert(resize_memory_handler != (ResizeMemoryHandler *) NULL); assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL); *acquire_memory_handler=memory_methods.acquire_memory_handler; *resize_memory_handler=memory_methods.resize_memory_handler; *destroy_memory_handler=memory_methods.destroy_memory_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e m o r y B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMemoryBlob() returns the virtual memory blob associated with the % specified MemoryInfo structure. % % The format of the GetVirtualMemoryBlob method is: % % void *GetVirtualMemoryBlob(const MemoryInfo *memory_info) % % A description of each parameter follows: % % o memory_info: The MemoryInfo structure. */ MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info) { assert(memory_info != (const MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); return(memory_info->blob); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h A l i g n e d M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory() % or reuse. % % The format of the RelinquishAlignedMemory method is: % % void *RelinquishAlignedMemory(void *memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void *RelinquishAlignedMemory(void *memory) { if (memory == (void *) NULL) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) free(memory); #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) _aligned_free(memory); #else free(*((void **) memory-1)); #endif return(NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory() % or AcquireQuantumMemory() for reuse. % % The format of the RelinquishMagickMemory method is: % % void *RelinquishMagickMemory(void *memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void *RelinquishMagickMemory(void *memory) { if (memory == (void *) NULL) return((void *) NULL); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) memory_methods.destroy_memory_handler(memory); #else LockSemaphoreInfo(memory_semaphore); assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0); assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0); if ((*BlockHeader(memory) & PreviousBlockBit) == 0) { void *previous; /* Coalesce with previous adjacent block. */ previous=PreviousBlock(memory); RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous))); *BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) | (*BlockHeader(previous) & ~SizeMask); memory=previous; } if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0) { void *next; /* Coalesce with next adjacent block. */ next=NextBlock(memory); RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next))); *BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) | (*BlockHeader(memory) & ~SizeMask); } *BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory); *BlockHeader(NextBlock(memory))&=(~PreviousBlockBit); InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory))); UnlockSemaphoreInfo(memory_semaphore); #endif return((void *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h V i r t u a l M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory(). % % The format of the RelinquishVirtualMemory method is: % % MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) % % A description of each parameter follows: % % o memory_info: A pointer to a block of memory to free for reuse. % */ MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') { (void) RelinquishUniqueFileResource(memory_info->filename); RelinquishMagickResource(DiskResource,memory_info->length); } break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetMagickMemory() fills the first size bytes of the memory area pointed to % by memory with the constant byte c. % % The format of the ResetMagickMemory method is: % % void *ResetMagickMemory(void *memory,int byte,const size_t size) % % A description of each parameter follows: % % o memory: a pointer to a memory allocation. % % o byte: set the memory to this value. % % o size: size of the memory to reset. % */ MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size) { assert(memory != (void *) NULL); return(memset(memory,byte,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeMagickMemory() changes the size of the memory and returns a pointer to % the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ResizeMagickMemory method is: % % void *ResizeMagickMemory(void *memory,const size_t size) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. % % o size: the new size of the allocated memory. % */ #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) static inline void *ResizeBlock(void *block,size_t size) { register void *memory; if (block == (void *) NULL) return(AcquireBlock(size)); memory=AcquireBlock(size); if (memory == (void *) NULL) return((void *) NULL); if (size <= (SizeOfBlock(block)-sizeof(size_t))) (void) memcpy(memory,block,size); else (void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t)); memory_pool.allocation+=size; return(memory); } #endif MagickExport void *ResizeMagickMemory(void *memory,const size_t size) { register void *block; if (memory == (void *) NULL) return(AcquireMagickMemory(size)); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size); if (block == (void *) NULL) memory=RelinquishMagickMemory(memory); #else LockSemaphoreInfo(memory_semaphore); block=ResizeBlock(memory,size == 0 ? 1UL : size); if (block == (void *) NULL) { if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse) { UnlockSemaphoreInfo(memory_semaphore); memory=RelinquishMagickMemory(memory); ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } block=ResizeBlock(memory,size == 0 ? 1UL : size); assert(block != (void *) NULL); } UnlockSemaphoreInfo(memory_semaphore); memory=RelinquishMagickMemory(memory); #endif return(block); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e Q u a n t u m M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeQuantumMemory() changes the size of the memory and returns a pointer % to the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ResizeQuantumMemory method is: % % void *ResizeQuantumMemory(void *memory,const size_t count, % const size_t quantum) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t size; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { memory=RelinquishMagickMemory(memory); errno=ENOMEM; return((void *) NULL); } return(ResizeMagickMemory(memory,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M a g i c k M e m o r y M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy % memory. Your custom memory methods must be set prior to the % MagickCoreGenesis() method. % % The format of the SetMagickMemoryMethods() method is: % % SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler, % ResizeMemoryHandler resize_memory_handler, % DestroyMemoryHandler destroy_memory_handler) % % A description of each parameter follows: % % o acquire_memory_handler: method to acquire memory (e.g. malloc). % % o resize_memory_handler: method to resize memory (e.g. realloc). % % o destroy_memory_handler: method to destroy memory (e.g. free). % */ MagickExport void SetMagickMemoryMethods( AcquireMemoryHandler acquire_memory_handler, ResizeMemoryHandler resize_memory_handler, DestroyMemoryHandler destroy_memory_handler) { /* Set memory methods. */ if (acquire_memory_handler != (AcquireMemoryHandler) NULL) memory_methods.acquire_memory_handler=acquire_memory_handler; if (resize_memory_handler != (ResizeMemoryHandler) NULL) memory_methods.resize_memory_handler=resize_memory_handler; if (destroy_memory_handler != (DestroyMemoryHandler) NULL) memory_methods.destroy_memory_handler=destroy_memory_handler; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_1834_0
crossvul-cpp_data_good_1175_0
/* Copyright (c) 2004-2007, Sara Golemon <sarag@libssh2.org> * Copyright (c) 2005,2006 Mikhail Gusarov * Copyright (c) 2009-2014 by Daniel Stenberg * Copyright (c) 2010 Simon Josefsson * All rights reserved. * * 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 copyright holder nor the names * of any other 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. */ #include "libssh2_priv.h" #include <errno.h> #include <fcntl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_TIME_H #include <sys/time.h> #endif #ifdef HAVE_INTTYPES_H #include <inttypes.h> #endif /* Needed for struct iovec on some platforms */ #ifdef HAVE_SYS_UIO_H #include <sys/uio.h> #endif #include <sys/types.h> #include "transport.h" #include "channel.h" #include "packet.h" /* * libssh2_packet_queue_listener * * Queue a connection request for a listener */ static inline int packet_queue_listener(LIBSSH2_SESSION * session, unsigned char *data, unsigned long datalen, packet_queue_listener_state_t *listen_state) { /* * Look for a matching listener */ /* 17 = packet_type(1) + channel(4) + reason(4) + descr(4) + lang(4) */ unsigned long packet_len = 17 + (sizeof(FwdNotReq) - 1); unsigned char *p; LIBSSH2_LISTENER *listn = _libssh2_list_first(&session->listeners); char failure_code = SSH_OPEN_ADMINISTRATIVELY_PROHIBITED; int rc; (void) datalen; if(listen_state->state == libssh2_NB_state_idle) { unsigned char *s = data + (sizeof("forwarded-tcpip") - 1) + 5; listen_state->sender_channel = _libssh2_ntohu32(s); s += 4; listen_state->initial_window_size = _libssh2_ntohu32(s); s += 4; listen_state->packet_size = _libssh2_ntohu32(s); s += 4; listen_state->host_len = _libssh2_ntohu32(s); s += 4; listen_state->host = s; s += listen_state->host_len; listen_state->port = _libssh2_ntohu32(s); s += 4; listen_state->shost_len = _libssh2_ntohu32(s); s += 4; listen_state->shost = s; s += listen_state->shost_len; listen_state->sport = _libssh2_ntohu32(s); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Remote received connection from %s:%ld to %s:%ld", listen_state->shost, listen_state->sport, listen_state->host, listen_state->port); listen_state->state = libssh2_NB_state_allocated; } if(listen_state->state != libssh2_NB_state_sent) { while(listn) { if((listn->port == (int) listen_state->port) && (strlen(listn->host) == listen_state->host_len) && (memcmp (listn->host, listen_state->host, listen_state->host_len) == 0)) { /* This is our listener */ LIBSSH2_CHANNEL *channel = NULL; listen_state->channel = NULL; if(listen_state->state == libssh2_NB_state_allocated) { if(listn->queue_maxsize && (listn->queue_maxsize <= listn->queue_size)) { /* Queue is full */ failure_code = SSH_OPEN_RESOURCE_SHORTAGE; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Listener queue full, ignoring"); listen_state->state = libssh2_NB_state_sent; break; } channel = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_CHANNEL)); if(!channel) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate a channel for " "new connection"); failure_code = SSH_OPEN_RESOURCE_SHORTAGE; listen_state->state = libssh2_NB_state_sent; break; } listen_state->channel = channel; channel->session = session; channel->channel_type_len = sizeof("forwarded-tcpip") - 1; channel->channel_type = LIBSSH2_ALLOC(session, channel-> channel_type_len + 1); if(!channel->channel_type) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "Unable to allocate a channel for new" " connection"); LIBSSH2_FREE(session, channel); failure_code = SSH_OPEN_RESOURCE_SHORTAGE; listen_state->state = libssh2_NB_state_sent; break; } memcpy(channel->channel_type, "forwarded-tcpip", channel->channel_type_len + 1); channel->remote.id = listen_state->sender_channel; channel->remote.window_size_initial = LIBSSH2_CHANNEL_WINDOW_DEFAULT; channel->remote.window_size = LIBSSH2_CHANNEL_WINDOW_DEFAULT; channel->remote.packet_size = LIBSSH2_CHANNEL_PACKET_DEFAULT; channel->local.id = _libssh2_channel_nextid(session); channel->local.window_size_initial = listen_state->initial_window_size; channel->local.window_size = listen_state->initial_window_size; channel->local.packet_size = listen_state->packet_size; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Connection queued: channel %lu/%lu " "win %lu/%lu packet %lu/%lu", channel->local.id, channel->remote.id, channel->local.window_size, channel->remote.window_size, channel->local.packet_size, channel->remote.packet_size); p = listen_state->packet; *(p++) = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; _libssh2_store_u32(&p, channel->remote.id); _libssh2_store_u32(&p, channel->local.id); _libssh2_store_u32(&p, channel->remote.window_size_initial); _libssh2_store_u32(&p, channel->remote.packet_size); listen_state->state = libssh2_NB_state_created; } if(listen_state->state == libssh2_NB_state_created) { rc = _libssh2_transport_send(session, listen_state->packet, 17, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) return rc; else if(rc) { listen_state->state = libssh2_NB_state_idle; return _libssh2_error(session, rc, "Unable to send channel " "open confirmation"); } /* Link the channel into the end of the queue list */ if(listen_state->channel) { _libssh2_list_add(&listn->queue, &listen_state->channel->node); listn->queue_size++; } listen_state->state = libssh2_NB_state_idle; return 0; } } listn = _libssh2_list_next(&listn->node); } listen_state->state = libssh2_NB_state_sent; } /* We're not listening to you */ p = listen_state->packet; *(p++) = SSH_MSG_CHANNEL_OPEN_FAILURE; _libssh2_store_u32(&p, listen_state->sender_channel); _libssh2_store_u32(&p, failure_code); _libssh2_store_str(&p, FwdNotReq, sizeof(FwdNotReq) - 1); _libssh2_htonu32(p, 0); rc = _libssh2_transport_send(session, listen_state->packet, packet_len, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { listen_state->state = libssh2_NB_state_idle; return _libssh2_error(session, rc, "Unable to send open failure"); } listen_state->state = libssh2_NB_state_idle; return 0; } /* * packet_x11_open * * Accept a forwarded X11 connection */ static inline int packet_x11_open(LIBSSH2_SESSION * session, unsigned char *data, unsigned long datalen, packet_x11_open_state_t *x11open_state) { int failure_code = SSH_OPEN_CONNECT_FAILED; /* 17 = packet_type(1) + channel(4) + reason(4) + descr(4) + lang(4) */ unsigned long packet_len = 17 + (sizeof(X11FwdUnAvil) - 1); unsigned char *p; LIBSSH2_CHANNEL *channel = x11open_state->channel; int rc; (void) datalen; if(x11open_state->state == libssh2_NB_state_idle) { unsigned char *s = data + (sizeof("x11") - 1) + 5; x11open_state->sender_channel = _libssh2_ntohu32(s); s += 4; x11open_state->initial_window_size = _libssh2_ntohu32(s); s += 4; x11open_state->packet_size = _libssh2_ntohu32(s); s += 4; x11open_state->shost_len = _libssh2_ntohu32(s); s += 4; x11open_state->shost = s; s += x11open_state->shost_len; x11open_state->sport = _libssh2_ntohu32(s); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "X11 Connection Received from %s:%ld on channel %lu", x11open_state->shost, x11open_state->sport, x11open_state->sender_channel); x11open_state->state = libssh2_NB_state_allocated; } if(session->x11) { if(x11open_state->state == libssh2_NB_state_allocated) { channel = LIBSSH2_CALLOC(session, sizeof(LIBSSH2_CHANNEL)); if(!channel) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "allocate a channel for new connection"); failure_code = SSH_OPEN_RESOURCE_SHORTAGE; goto x11_exit; } channel->session = session; channel->channel_type_len = sizeof("x11") - 1; channel->channel_type = LIBSSH2_ALLOC(session, channel->channel_type_len + 1); if(!channel->channel_type) { _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "allocate a channel for new connection"); LIBSSH2_FREE(session, channel); failure_code = SSH_OPEN_RESOURCE_SHORTAGE; goto x11_exit; } memcpy(channel->channel_type, "x11", channel->channel_type_len + 1); channel->remote.id = x11open_state->sender_channel; channel->remote.window_size_initial = LIBSSH2_CHANNEL_WINDOW_DEFAULT; channel->remote.window_size = LIBSSH2_CHANNEL_WINDOW_DEFAULT; channel->remote.packet_size = LIBSSH2_CHANNEL_PACKET_DEFAULT; channel->local.id = _libssh2_channel_nextid(session); channel->local.window_size_initial = x11open_state->initial_window_size; channel->local.window_size = x11open_state->initial_window_size; channel->local.packet_size = x11open_state->packet_size; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "X11 Connection established: channel %lu/%lu " "win %lu/%lu packet %lu/%lu", channel->local.id, channel->remote.id, channel->local.window_size, channel->remote.window_size, channel->local.packet_size, channel->remote.packet_size); p = x11open_state->packet; *(p++) = SSH_MSG_CHANNEL_OPEN_CONFIRMATION; _libssh2_store_u32(&p, channel->remote.id); _libssh2_store_u32(&p, channel->local.id); _libssh2_store_u32(&p, channel->remote.window_size_initial); _libssh2_store_u32(&p, channel->remote.packet_size); x11open_state->state = libssh2_NB_state_created; } if(x11open_state->state == libssh2_NB_state_created) { rc = _libssh2_transport_send(session, x11open_state->packet, 17, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { x11open_state->state = libssh2_NB_state_idle; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_SEND, "Unable to send channel open " "confirmation"); } /* Link the channel into the session */ _libssh2_list_add(&session->channels, &channel->node); /* * Pass control to the callback, they may turn right around and * free the channel, or actually use it */ LIBSSH2_X11_OPEN(channel, (char *)x11open_state->shost, x11open_state->sport); x11open_state->state = libssh2_NB_state_idle; return 0; } } else failure_code = SSH_OPEN_RESOURCE_SHORTAGE; /* fall-trough */ x11_exit: p = x11open_state->packet; *(p++) = SSH_MSG_CHANNEL_OPEN_FAILURE; _libssh2_store_u32(&p, x11open_state->sender_channel); _libssh2_store_u32(&p, failure_code); _libssh2_store_str(&p, X11FwdUnAvil, sizeof(X11FwdUnAvil) - 1); _libssh2_htonu32(p, 0); rc = _libssh2_transport_send(session, x11open_state->packet, packet_len, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) { return rc; } else if(rc) { x11open_state->state = libssh2_NB_state_idle; return _libssh2_error(session, rc, "Unable to send open failure"); } x11open_state->state = libssh2_NB_state_idle; return 0; } /* * _libssh2_packet_add * * Create a new packet and attach it to the brigade. Called from the transport * layer when it has received a packet. * * The input pointer 'data' is pointing to allocated data that this function * is asked to deal with so on failure OR success, it must be freed fine. * The only exception is when the return code is LIBSSH2_ERROR_EAGAIN. * * This function will always be called with 'datalen' greater than zero. */ int _libssh2_packet_add(LIBSSH2_SESSION * session, unsigned char *data, size_t datalen, int macstate) { int rc = 0; unsigned char *message = NULL; unsigned char *language = NULL; size_t message_len = 0; size_t language_len = 0; LIBSSH2_CHANNEL *channelp = NULL; size_t data_head = 0; unsigned char msg = data[0]; switch(session->packAdd_state) { case libssh2_NB_state_idle: _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Packet type %d received, length=%d", (int) msg, (int) datalen); if((macstate == LIBSSH2_MAC_INVALID) && (!session->macerror || LIBSSH2_MACERROR(session, (char *) data, datalen))) { /* Bad MAC input, but no callback set or non-zero return from the callback */ LIBSSH2_FREE(session, data); return _libssh2_error(session, LIBSSH2_ERROR_INVALID_MAC, "Invalid MAC received"); } session->packAdd_state = libssh2_NB_state_allocated; break; case libssh2_NB_state_jump1: goto libssh2_packet_add_jump_point1; case libssh2_NB_state_jump2: goto libssh2_packet_add_jump_point2; case libssh2_NB_state_jump3: goto libssh2_packet_add_jump_point3; case libssh2_NB_state_jump4: goto libssh2_packet_add_jump_point4; case libssh2_NB_state_jump5: goto libssh2_packet_add_jump_point5; default: /* nothing to do */ break; } if(session->packAdd_state == libssh2_NB_state_allocated) { /* A couple exceptions to the packet adding rule: */ switch(msg) { /* byte SSH_MSG_DISCONNECT uint32 reason code string description in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ case SSH_MSG_DISCONNECT: if(datalen >= 5) { uint32_t reason = 0; struct string_buf buf; buf.data = (unsigned char *)data; buf.dataptr = buf.data; buf.len = datalen; buf.dataptr++; /* advance past type */ _libssh2_get_u32(&buf, &reason); _libssh2_get_string(&buf, &message, &message_len); _libssh2_get_string(&buf, &language, &language_len); if(session->ssh_msg_disconnect) { LIBSSH2_DISCONNECT(session, reason, (const char *)message, message_len, (const char *)language, language_len); } _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Disconnect(%d): %s(%s)", reason, message, language); } LIBSSH2_FREE(session, data); session->socket_state = LIBSSH2_SOCKET_DISCONNECTED; session->packAdd_state = libssh2_NB_state_idle; return _libssh2_error(session, LIBSSH2_ERROR_SOCKET_DISCONNECT, "socket disconnect"); /* byte SSH_MSG_IGNORE string data */ case SSH_MSG_IGNORE: if(datalen >= 2) { if(session->ssh_msg_ignore) { LIBSSH2_IGNORE(session, (char *) data + 1, datalen - 1); } } else if(session->ssh_msg_ignore) { LIBSSH2_IGNORE(session, "", 0); } LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; /* byte SSH_MSG_DEBUG boolean always_display string message in ISO-10646 UTF-8 encoding [RFC3629] string language tag [RFC3066] */ case SSH_MSG_DEBUG: if(datalen >= 2) { int always_display = data[1]; if(datalen >= 6) { struct string_buf buf; buf.data = (unsigned char *)data; buf.dataptr = buf.data; buf.len = datalen; buf.dataptr += 2; /* advance past type & always display */ _libssh2_get_string(&buf, &message, &message_len); _libssh2_get_string(&buf, &language, &language_len); } if(session->ssh_msg_debug) { LIBSSH2_DEBUG(session, always_display, (const char *)message, message_len, (const char *)language, language_len); } } /* * _libssh2_debug will actually truncate this for us so * that it's not an inordinate about of data */ _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Debug Packet: %s", message); LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; /* byte SSH_MSG_GLOBAL_REQUEST string request name in US-ASCII only boolean want reply .... request-specific data follows */ case SSH_MSG_GLOBAL_REQUEST: if(datalen >= 5) { uint32_t len = 0; unsigned char want_reply = 0; len = _libssh2_ntohu32(data + 1); if((len <= (UINT_MAX - 6) && (datalen >= (6 + len))) { want_reply = data[5 + len]; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Received global request type %.*s (wr %X)", len, data + 5, want_reply); } if(want_reply) { static const unsigned char packet = SSH_MSG_REQUEST_FAILURE; libssh2_packet_add_jump_point5: session->packAdd_state = libssh2_NB_state_jump5; rc = _libssh2_transport_send(session, &packet, 1, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) return rc; } } LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; /* byte SSH_MSG_CHANNEL_EXTENDED_DATA uint32 recipient channel uint32 data_type_code string data */ case SSH_MSG_CHANNEL_EXTENDED_DATA: /* streamid(4) */ data_head += 4; /* fall-through */ /* byte SSH_MSG_CHANNEL_DATA uint32 recipient channel string data */ case SSH_MSG_CHANNEL_DATA: /* packet_type(1) + channelno(4) + datalen(4) */ data_head += 9; if(datalen >= data_head) channelp = _libssh2_channel_locate(session, _libssh2_ntohu32(data + 1)); if(!channelp) { _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_UNKNOWN, "Packet received for unknown channel"); LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; } #ifdef LIBSSH2DEBUG { uint32_t stream_id = 0; if(msg == SSH_MSG_CHANNEL_EXTENDED_DATA) stream_id = _libssh2_ntohu32(data + 5); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "%d bytes packet_add() for %lu/%lu/%lu", (int) (datalen - data_head), channelp->local.id, channelp->remote.id, stream_id); } #endif if((channelp->remote.extended_data_ignore_mode == LIBSSH2_CHANNEL_EXTENDED_DATA_IGNORE) && (msg == SSH_MSG_CHANNEL_EXTENDED_DATA)) { /* Pretend we didn't receive this */ LIBSSH2_FREE(session, data); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Ignoring extended data and refunding %d bytes", (int) (datalen - 13)); if(channelp->read_avail + datalen - data_head >= channelp->remote.window_size) datalen = channelp->remote.window_size - channelp->read_avail + data_head; channelp->remote.window_size -= datalen - data_head; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "shrinking window size by %lu bytes to %lu, " "read_avail %lu", datalen - data_head, channelp->remote.window_size, channelp->read_avail); session->packAdd_channelp = channelp; /* Adjust the window based on the block we just freed */ libssh2_packet_add_jump_point1: session->packAdd_state = libssh2_NB_state_jump1; rc = _libssh2_channel_receive_window_adjust(session-> packAdd_channelp, datalen - 13, 1, NULL); if(rc == LIBSSH2_ERROR_EAGAIN) return rc; session->packAdd_state = libssh2_NB_state_idle; return 0; } /* * REMEMBER! remote means remote as source of data, * NOT remote window! */ if(channelp->remote.packet_size < (datalen - data_head)) { /* * Spec says we MAY ignore bytes sent beyond * packet_size */ _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_PACKET_EXCEEDED, "Packet contains more data than we offered" " to receive, truncating"); datalen = channelp->remote.packet_size + data_head; } if(channelp->remote.window_size <= channelp->read_avail) { /* * Spec says we MAY ignore bytes sent beyond * window_size */ _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED, "The current receive window is full," " data ignored"); LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; } /* Reset EOF status */ channelp->remote.eof = 0; if(channelp->read_avail + datalen - data_head > channelp->remote.window_size) { _libssh2_error(session, LIBSSH2_ERROR_CHANNEL_WINDOW_EXCEEDED, "Remote sent more data than current " "window allows, truncating"); datalen = channelp->remote.window_size - channelp->read_avail + data_head; } /* Update the read_avail counter. The window size will be * updated once the data is actually read from the queue * from an upper layer */ channelp->read_avail += datalen - data_head; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "increasing read_avail by %lu bytes to %lu/%lu", (long)(datalen - data_head), (long)channelp->read_avail, (long)channelp->remote.window_size); break; /* byte SSH_MSG_CHANNEL_EOF uint32 recipient channel */ case SSH_MSG_CHANNEL_EOF: if(datalen >= 5) channelp = _libssh2_channel_locate(session, _libssh2_ntohu32(data + 1)); if(!channelp) /* We may have freed already, just quietly ignore this... */ ; else { _libssh2_debug(session, LIBSSH2_TRACE_CONN, "EOF received for channel %lu/%lu", channelp->local.id, channelp->remote.id); channelp->remote.eof = 1; } LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; /* byte SSH_MSG_CHANNEL_REQUEST uint32 recipient channel string request type in US-ASCII characters only boolean want reply .... type-specific data follows */ case SSH_MSG_CHANNEL_REQUEST: if(datalen >= 9) { uint32_t channel = _libssh2_ntohu32(data + 1); uint32_t len = _libssh2_ntohu32(data + 5); unsigned char want_reply = 1; if((len + 9) < datalen) want_reply = data[len + 9]; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Channel %d received request type %.*s (wr %X)", channel, len, data + 9, want_reply); if(len == sizeof("exit-status") - 1 && (sizeof("exit-status") - 1 + 9) <= datalen && !memcmp("exit-status", data + 9, sizeof("exit-status") - 1)) { /* we've got "exit-status" packet. Set the session value */ if(datalen >= 20) channelp = _libssh2_channel_locate(session, channel); if(channelp && (sizeof("exit-status") + 13) <= datalen) { channelp->exit_status = _libssh2_ntohu32(data + 9 + sizeof("exit-status")); _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Exit status %lu received for " "channel %lu/%lu", channelp->exit_status, channelp->local.id, channelp->remote.id); } } else if(len == sizeof("exit-signal") - 1 && (sizeof("exit-signal") - 1 + 9) <= datalen && !memcmp("exit-signal", data + 9, sizeof("exit-signal") - 1)) { /* command terminated due to signal */ if(datalen >= 20) channelp = _libssh2_channel_locate(session, channel); if(channelp && (sizeof("exit-signal") + 13) <= datalen) { /* set signal name (without SIG prefix) */ uint32_t namelen = _libssh2_ntohu32(data + 9 + sizeof("exit-signal")); if(namelen <= UINT_MAX - 1) { channelp->exit_signal = LIBSSH2_ALLOC(session, namelen + 1); } else { channelp->exit_signal = NULL; } if(!channelp->exit_signal) rc = _libssh2_error(session, LIBSSH2_ERROR_ALLOC, "memory for signal name"); else if((sizeof("exit-signal") + 13 + namelen <= datalen)) { memcpy(channelp->exit_signal, data + 13 + sizeof("exit-signal"), namelen); channelp->exit_signal[namelen] = '\0'; /* TODO: save error message and language tag */ _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Exit signal %s received for " "channel %lu/%lu", channelp->exit_signal, channelp->local.id, channelp->remote.id); } } } if(want_reply) { unsigned char packet[5]; libssh2_packet_add_jump_point4: session->packAdd_state = libssh2_NB_state_jump4; packet[0] = SSH_MSG_CHANNEL_FAILURE; memcpy(&packet[1], data + 1, 4); rc = _libssh2_transport_send(session, packet, 5, NULL, 0); if(rc == LIBSSH2_ERROR_EAGAIN) return rc; } } LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return rc; /* byte SSH_MSG_CHANNEL_CLOSE uint32 recipient channel */ case SSH_MSG_CHANNEL_CLOSE: if(datalen >= 5) channelp = _libssh2_channel_locate(session, _libssh2_ntohu32(data + 1)); if(!channelp) { /* We may have freed already, just quietly ignore this... */ LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; } _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Close received for channel %lu/%lu", channelp->local.id, channelp->remote.id); channelp->remote.close = 1; channelp->remote.eof = 1; LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; /* byte SSH_MSG_CHANNEL_OPEN string "session" uint32 sender channel uint32 initial window size uint32 maximum packet size */ case SSH_MSG_CHANNEL_OPEN: if(datalen < 17) ; else if((datalen >= (sizeof("forwarded-tcpip") + 4)) && ((sizeof("forwarded-tcpip") - 1) == _libssh2_ntohu32(data + 1)) && (memcmp(data + 5, "forwarded-tcpip", sizeof("forwarded-tcpip") - 1) == 0)) { /* init the state struct */ memset(&session->packAdd_Qlstn_state, 0, sizeof(session->packAdd_Qlstn_state)); libssh2_packet_add_jump_point2: session->packAdd_state = libssh2_NB_state_jump2; rc = packet_queue_listener(session, data, datalen, &session->packAdd_Qlstn_state); } else if((datalen >= (sizeof("x11") + 4)) && ((sizeof("x11") - 1) == _libssh2_ntohu32(data + 1)) && (memcmp(data + 5, "x11", sizeof("x11") - 1) == 0)) { /* init the state struct */ memset(&session->packAdd_x11open_state, 0, sizeof(session->packAdd_x11open_state)); libssh2_packet_add_jump_point3: session->packAdd_state = libssh2_NB_state_jump3; rc = packet_x11_open(session, data, datalen, &session->packAdd_x11open_state); } if(rc == LIBSSH2_ERROR_EAGAIN) return rc; LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return rc; /* byte SSH_MSG_CHANNEL_WINDOW_ADJUST uint32 recipient channel uint32 bytes to add */ case SSH_MSG_CHANNEL_WINDOW_ADJUST: if(datalen < 9) ; else { uint32_t bytestoadd = _libssh2_ntohu32(data + 5); channelp = _libssh2_channel_locate(session, _libssh2_ntohu32(data + 1)); if(channelp) { channelp->local.window_size += bytestoadd; _libssh2_debug(session, LIBSSH2_TRACE_CONN, "Window adjust for channel %lu/%lu, " "adding %lu bytes, new window_size=%lu", channelp->local.id, channelp->remote.id, bytestoadd, channelp->local.window_size); } } LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return 0; default: break; } session->packAdd_state = libssh2_NB_state_sent; } if(session->packAdd_state == libssh2_NB_state_sent) { LIBSSH2_PACKET *packetp = LIBSSH2_ALLOC(session, sizeof(LIBSSH2_PACKET)); if(!packetp) { _libssh2_debug(session, LIBSSH2_ERROR_ALLOC, "memory for packet"); LIBSSH2_FREE(session, data); session->packAdd_state = libssh2_NB_state_idle; return LIBSSH2_ERROR_ALLOC; } packetp->data = data; packetp->data_len = datalen; packetp->data_head = data_head; _libssh2_list_add(&session->packets, &packetp->node); session->packAdd_state = libssh2_NB_state_sent1; } if((msg == SSH_MSG_KEXINIT && !(session->state & LIBSSH2_STATE_EXCHANGING_KEYS)) || (session->packAdd_state == libssh2_NB_state_sent2)) { if(session->packAdd_state == libssh2_NB_state_sent1) { /* * Remote wants new keys * Well, it's already in the brigade, * let's just call back into ourselves */ _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Renegotiating Keys"); session->packAdd_state = libssh2_NB_state_sent2; } /* * The KEXINIT message has been added to the queue. The packAdd and * readPack states need to be reset because _libssh2_kex_exchange * (eventually) calls upon _libssh2_transport_read to read the rest of * the key exchange conversation. */ session->readPack_state = libssh2_NB_state_idle; session->packet.total_num = 0; session->packAdd_state = libssh2_NB_state_idle; session->fullpacket_state = libssh2_NB_state_idle; memset(&session->startup_key_state, 0, sizeof(key_exchange_state_t)); /* * If there was a key reexchange failure, let's just hope we didn't * send NEWKEYS yet, otherwise remote will drop us like a rock */ rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state); if(rc == LIBSSH2_ERROR_EAGAIN) return rc; } session->packAdd_state = libssh2_NB_state_idle; return 0; } /* * _libssh2_packet_ask * * Scan the brigade for a matching packet type, optionally poll the socket for * a packet first */ int _libssh2_packet_ask(LIBSSH2_SESSION * session, unsigned char packet_type, unsigned char **data, size_t *data_len, int match_ofs, const unsigned char *match_buf, size_t match_len) { LIBSSH2_PACKET *packet = _libssh2_list_first(&session->packets); _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Looking for packet of type: %d", (int) packet_type); while(packet) { if(packet->data[0] == packet_type && (packet->data_len >= (match_ofs + match_len)) && (!match_buf || (memcmp(packet->data + match_ofs, match_buf, match_len) == 0))) { *data = packet->data; *data_len = packet->data_len; /* unlink struct from session->packets */ _libssh2_list_remove(&packet->node); LIBSSH2_FREE(session, packet); return 0; } packet = _libssh2_list_next(&packet->node); } return -1; } /* * libssh2_packet_askv * * Scan for any of a list of packet types in the brigade, optionally poll the * socket for a packet first */ int _libssh2_packet_askv(LIBSSH2_SESSION * session, const unsigned char *packet_types, unsigned char **data, size_t *data_len, int match_ofs, const unsigned char *match_buf, size_t match_len) { int i, packet_types_len = strlen((char *) packet_types); for(i = 0; i < packet_types_len; i++) { if(0 == _libssh2_packet_ask(session, packet_types[i], data, data_len, match_ofs, match_buf, match_len)) { return 0; } } return -1; } /* * _libssh2_packet_require * * Loops _libssh2_transport_read() until the packet requested is available * SSH_DISCONNECT or a SOCKET_DISCONNECTED will cause a bailout * * Returns negative on error * Returns 0 when it has taken care of the requested packet. */ int _libssh2_packet_require(LIBSSH2_SESSION * session, unsigned char packet_type, unsigned char **data, size_t *data_len, int match_ofs, const unsigned char *match_buf, size_t match_len, packet_require_state_t *state) { if(state->start == 0) { if(_libssh2_packet_ask(session, packet_type, data, data_len, match_ofs, match_buf, match_len) == 0) { /* A packet was available in the packet brigade */ return 0; } state->start = time(NULL); } while(session->socket_state == LIBSSH2_SOCKET_CONNECTED) { int ret = _libssh2_transport_read(session); if(ret == LIBSSH2_ERROR_EAGAIN) return ret; else if(ret < 0) { state->start = 0; /* an error which is not just because of blocking */ return ret; } else if(ret == packet_type) { /* Be lazy, let packet_ask pull it out of the brigade */ ret = _libssh2_packet_ask(session, packet_type, data, data_len, match_ofs, match_buf, match_len); state->start = 0; return ret; } else if(ret == 0) { /* nothing available, wait until data arrives or we time out */ long left = LIBSSH2_READ_TIMEOUT - (long)(time(NULL) - state->start); if(left <= 0) { state->start = 0; return LIBSSH2_ERROR_TIMEOUT; } return -1; /* no packet available yet */ } } /* Only reached if the socket died */ return LIBSSH2_ERROR_SOCKET_DISCONNECT; } /* * _libssh2_packet_burn * * Loops _libssh2_transport_read() until any packet is available and promptly * discards it. * Used during KEX exchange to discard badly guessed KEX_INIT packets */ int _libssh2_packet_burn(LIBSSH2_SESSION * session, libssh2_nonblocking_states * state) { unsigned char *data; size_t data_len; unsigned char i, all_packets[255]; int ret; if(*state == libssh2_NB_state_idle) { for(i = 1; i < 255; i++) { all_packets[i - 1] = i; } all_packets[254] = 0; if(_libssh2_packet_askv(session, all_packets, &data, &data_len, 0, NULL, 0) == 0) { i = data[0]; /* A packet was available in the packet brigade, burn it */ LIBSSH2_FREE(session, data); return i; } _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Blocking until packet becomes available to burn"); *state = libssh2_NB_state_created; } while(session->socket_state == LIBSSH2_SOCKET_CONNECTED) { ret = _libssh2_transport_read(session); if(ret == LIBSSH2_ERROR_EAGAIN) { return ret; } else if(ret < 0) { *state = libssh2_NB_state_idle; return ret; } else if(ret == 0) { /* FIXME: this might busyloop */ continue; } /* Be lazy, let packet_ask pull it out of the brigade */ if(0 == _libssh2_packet_ask(session, (unsigned char)ret, &data, &data_len, 0, NULL, 0)) { /* Smoke 'em if you got 'em */ LIBSSH2_FREE(session, data); *state = libssh2_NB_state_idle; return ret; } } /* Only reached if the socket died */ return LIBSSH2_ERROR_SOCKET_DISCONNECT; } /* * _libssh2_packet_requirev * * Loops _libssh2_transport_read() until one of a list of packet types * requested is available. SSH_DISCONNECT or a SOCKET_DISCONNECTED will cause * a bailout. packet_types is a null terminated list of packet_type numbers */ int _libssh2_packet_requirev(LIBSSH2_SESSION *session, const unsigned char *packet_types, unsigned char **data, size_t *data_len, int match_ofs, const unsigned char *match_buf, size_t match_len, packet_requirev_state_t * state) { if(_libssh2_packet_askv(session, packet_types, data, data_len, match_ofs, match_buf, match_len) == 0) { /* One of the packets listed was available in the packet brigade */ state->start = 0; return 0; } if(state->start == 0) { state->start = time(NULL); } while(session->socket_state != LIBSSH2_SOCKET_DISCONNECTED) { int ret = _libssh2_transport_read(session); if((ret < 0) && (ret != LIBSSH2_ERROR_EAGAIN)) { state->start = 0; return ret; } if(ret <= 0) { long left = LIBSSH2_READ_TIMEOUT - (long)(time(NULL) - state->start); if(left <= 0) { state->start = 0; return LIBSSH2_ERROR_TIMEOUT; } else if(ret == LIBSSH2_ERROR_EAGAIN) { return ret; } } if(strchr((char *) packet_types, ret)) { /* Be lazy, let packet_ask pull it out of the brigade */ return _libssh2_packet_askv(session, packet_types, data, data_len, match_ofs, match_buf, match_len); } } /* Only reached if the socket died */ state->start = 0; return LIBSSH2_ERROR_SOCKET_DISCONNECT; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_1175_0
crossvul-cpp_data_bad_401_1
/* * Description: * History: yang@haipo.me, 2016/03/30, create */ # include <stdlib.h> # include <assert.h> # include "ut_rpc.h" # include "ut_crc32.h" # include "ut_misc.h" int rpc_decode(nw_ses *ses, void *data, size_t max) { if (max < RPC_PKG_HEAD_SIZE) return 0; rpc_pkg *pkg = data; if (le32toh(pkg->magic) != RPC_PKG_MAGIC) return -1; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + le16toh(pkg->ext_size) + le32toh(pkg->body_size); if (max < pkg_size) return 0; uint32_t crc32 = le32toh(pkg->crc32); pkg->crc32 = 0; if (crc32 != generate_crc32c(data, pkg_size)) return -3; pkg->crc32 = crc32; pkg->magic = le32toh(pkg->magic); pkg->command = le32toh(pkg->command); pkg->pkg_type = le16toh(pkg->pkg_type); pkg->result = le32toh(pkg->result); pkg->sequence = le32toh(pkg->sequence); pkg->req_id = le64toh(pkg->req_id); pkg->body_size = le32toh(pkg->body_size); pkg->ext_size = le16toh(pkg->ext_size); return pkg_size; } int rpc_pack(rpc_pkg *pkg, void **data, uint32_t *size) { static void *send_buf; static size_t send_buf_size; uint32_t pkg_size = RPC_PKG_HEAD_SIZE + pkg->ext_size + pkg->body_size; if (send_buf_size < pkg_size) { if (send_buf) free(send_buf); send_buf_size = pkg_size * 2; send_buf = malloc(send_buf_size); assert(send_buf != NULL); } memcpy(send_buf, pkg, RPC_PKG_HEAD_SIZE); if (pkg->ext_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE, pkg->ext, pkg->ext_size); if (pkg->body_size) memcpy(send_buf + RPC_PKG_HEAD_SIZE + pkg->ext_size, pkg->body, pkg->body_size); pkg = send_buf; pkg->magic = htole32(RPC_PKG_MAGIC); pkg->command = htole32(pkg->command); pkg->pkg_type = htole16(pkg->pkg_type); pkg->result = htole32(pkg->result); pkg->sequence = htole32(pkg->sequence); pkg->req_id = htole64(pkg->req_id); pkg->body_size = htole32(pkg->body_size); pkg->ext_size = htole16(pkg->ext_size); pkg->crc32 = 0; pkg->crc32 = htole32(generate_crc32c(send_buf, pkg_size)); *data = send_buf; *size = pkg_size; return 0; } int rpc_send(nw_ses *ses, rpc_pkg *pkg) { void *data; uint32_t size; int ret = rpc_pack(pkg, &data, &size); if (ret < 0) return ret; return nw_ses_send(ses, data, size); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_401_1
crossvul-cpp_data_good_711_0
/* ** The Sleuth Kit ** ** This software is subject to the IBM Public License ver. 1.0, ** which was displayed prior to download and is included in the readme.txt ** file accompanying the Sleuth Kit files. It may also be requested from: ** Crucial Security Inc. ** 14900 Conference Center Drive ** Chantilly, VA 20151 ** ** Copyright (c) 2009 Brian Carrier. All rights reserved. ** ** Judson Powers [jpowers@atc-nycorp.com] ** Matt Stillerman [matt@atc-nycorp.com] ** Rob Joyce [rob@atc-nycorp.com] ** Copyright (c) 2008, 2012 ATC-NY. All rights reserved. ** This file contains data developed with support from the National ** Institute of Justice, Office of Justice Programs, U.S. Department of Justice. ** ** Wyatt Banks [wbanks@crucialsecurity.com] ** Copyright (c) 2005 Crucial Security Inc. All rights reserved. ** ** Brian Carrier [carrier@sleuthkit.org] ** Copyright (c) 2003-2005 Brian Carrier. All rights reserved ** ** Copyright (c) 1997,1998,1999, International Business Machines ** Corporation and others. All Rights Reserved. */ /* TCT * LICENSE * This software is distributed under the IBM Public License. * AUTHOR(S) * Wietse Venema * IBM T.J. Watson Research * P.O. Box 704 * Yorktown Heights, NY 10598, USA --*/ /* ** You may distribute the Sleuth Kit, or other software that incorporates ** part of all of the Sleuth Kit, in object code form under a license agreement, ** provided that: ** a) you comply with the terms and conditions of the IBM Public License ** ver 1.0; and ** b) the license agreement ** i) effectively disclaims on behalf of all Contributors all warranties ** and conditions, express and implied, including warranties or ** conditions of title and non-infringement, and implied warranties ** or conditions of merchantability and fitness for a particular ** purpose. ** ii) effectively excludes on behalf of all Contributors liability for ** damages, including direct, indirect, special, incidental and ** consequential damages such as lost profits. ** iii) states that any provisions which differ from IBM Public License ** ver. 1.0 are offered by that Contributor alone and not by any ** other party; and ** iv) states that the source code for the program is available from you, ** and informs licensees how to obtain it in a reasonable manner on or ** through a medium customarily used for software exchange. ** ** When the Sleuth Kit or other software that incorporates part or all of ** the Sleuth Kit is made available in source code form: ** a) it must be made available under IBM Public License ver. 1.0; and ** b) a copy of the IBM Public License ver. 1.0 must be included with ** each copy of the program. */ /** \file hfs.c * Contains the general internal TSK HFS metadata and data unit code */ #include "tsk_fs_i.h" #include "tsk_hfs.h" #include <stdarg.h> #ifdef TSK_WIN32 #include <string.h> #else #include <strings.h> #endif #define XSWAP(a,b) { a ^= b; b ^= a; a ^= b; } // Compression Stuff #ifdef HAVE_LIBZ #include <zlib.h> #endif #include "lzvn.h" // Forward declarations: static uint8_t hfs_load_attrs(TSK_FS_FILE * fs_file); static uint8_t hfs_load_extended_attrs(TSK_FS_FILE * file, unsigned char *isCompressed, unsigned char *cmpType, uint64_t * uncSize); void error_detected(uint32_t errnum, char *errstr, ...); void error_returned(char *errstr, ...); #ifdef HAVE_LIBZ /***************** ZLIB stuff *******************************/ // Adapted from zpipe.c (part of zlib) at http://zlib.net/zpipe.c #define CHUNK 16384 /* * Invokes the zlib library to inflate (uncompress) data. * * Returns and error code. Places the uncompressed data in a buffer supplied by the caller. Also * returns the uncompressed length, and the number of compressed bytes consumed. * * Will stop short of the end of compressed data, if a natural end of a compression unit is reached. Using * bytesConsumed, the caller can then advance the source pointer, and re-invoke the function. This will then * inflate the next following compression unit in the data stream. * * @param source - buffer of compressed data * @param sourceLen - length of the compressed data. * @param dest -- buffer to hold the uncompressed results * @param destLen -- length of the dest buffer * @param uncompressedLength -- return of the length of the uncompressed data found. * @param bytesConsumed -- return of the number of input bytes of compressed data used. * @return 0 on success, a negative number on error */ static int zlib_inflate(char *source, uint64_t sourceLen, char *dest, uint64_t destLen, uint64_t * uncompressedLength, unsigned long *bytesConsumed) // this is unsigned long because that's what zlib uses. { int ret; unsigned have; z_stream strm; unsigned char in[CHUNK]; unsigned char out[CHUNK]; // Some vars to help with copying bytes into "in" char *srcPtr = source; char *destPtr = dest; uint64_t srcAvail = sourceLen; //uint64_t uint64_t amtToCopy; uint64_t copiedSoFar = 0; /* allocate inflate state */ strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit(&strm); if (ret != Z_OK) { error_detected(TSK_ERR_FS_READ, "zlib_inflate: failed to initialize inflation engine (%d)", ret); return ret; } /* decompress until deflate stream ends or end of file */ do { // Copy up to CHUNK bytes into "in" from source, advancing the pointer, and // setting strm.avail_in equal to the number of bytes copied. if (srcAvail >= CHUNK) { amtToCopy = CHUNK; srcAvail -= CHUNK; } else { amtToCopy = srcAvail; srcAvail = 0; } // wipe out any previous value, copy in the bytes, advance the pointer, record number of bytes. memset(in, 0, CHUNK); if (amtToCopy > SIZE_MAX || amtToCopy > UINT_MAX) { error_detected(TSK_ERR_FS_READ, "zlib_inflate: amtToCopy in one chunk is too large"); return -100; } memcpy(in, srcPtr, (size_t) amtToCopy); // cast OK because of above test srcPtr += amtToCopy; strm.avail_in = (uInt) amtToCopy; // cast OK because of above test if (strm.avail_in == 0) break; strm.next_in = in; /* run inflate() on input until output buffer not full */ do { strm.avail_out = CHUNK; strm.next_out = out; ret = inflate(&strm, Z_NO_FLUSH); if (ret == Z_NEED_DICT) ret = Z_DATA_ERROR; // we don't have a custom dict if (ret < 0 && ret != Z_BUF_ERROR) { // Z_BUF_ERROR is not fatal error_detected(TSK_ERR_FS_READ, " zlib_inflate: zlib returned error %d (%s)", ret, strm.msg); (void) inflateEnd(&strm); return ret; } have = CHUNK - strm.avail_out; // Is there enough space in dest to copy the current chunk? if (copiedSoFar + have > destLen) { // There is not enough space, so better return an error error_detected(TSK_ERR_FS_READ, " zlib_inflate: not enough space in inflation destination\n"); (void) inflateEnd(&strm); return -200; } // Copy "have" bytes from out to destPtr, advance destPtr memcpy(destPtr, out, have); destPtr += have; copiedSoFar += have; } while ((strm.avail_out == 0) && (ret != Z_STREAM_END)); /* done when inflate() says it's done */ } while (ret != Z_STREAM_END); if (ret == Z_STREAM_END) *uncompressedLength = copiedSoFar; *bytesConsumed = strm.total_in; /* clean up and return */ (void) inflateEnd(&strm); return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR; } #endif /* may set error up to string 1 * returns 0 on success, 1 on failure */ uint8_t hfs_checked_read_random(TSK_FS_INFO * fs, char *buf, size_t len, TSK_OFF_T offs) { ssize_t r; r = tsk_fs_read(fs, offs, buf, len); if (r != len) { if (r >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } return 1; } return 0; } /********************************************************************** * * MISC FUNCS * **********************************************************************/ /* convert the HFS Time (seconds from 1/1/1904) * to UNIX (UTC seconds from 1/1/1970) * The number is borrowed from linux HFS driver source */ uint32_t hfs_convert_2_unix_time(uint32_t hfsdate) { if (hfsdate < NSEC_BTWN_1904_1970) return 0; return (uint32_t) (hfsdate - NSEC_BTWN_1904_1970); } /** * Convert a cnid (metadata address) to big endian array. * This is used to create the key for tree lookups. * @param cnid Metadata address to convert * @param array [out] Array to write data into. */ static void cnid_to_array(uint32_t cnid, uint8_t array[4]) { array[3] = (cnid >> 0) & 0xff; array[2] = (cnid >> 8) & 0xff; array[1] = (cnid >> 16) & 0xff; array[0] = (cnid >> 24) & 0xff; } /********************************************************************** * * Lookup Functions * **********************************************************************/ /* Compares the given HFS+ Extents B-tree key to key constructed * for finding the beginning of the data fork extents for the given * CNID. (That is, the search key uses the given CNID and has * fork = 0 and start_block = 0.) */ static int hfs_ext_compare_keys(HFS_INFO * hfs, uint32_t cnid, const hfs_btree_key_ext * key) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint32_t key_cnid; key_cnid = tsk_getu32(fs->endian, key->file_id); if (key_cnid < cnid) return -1; if (key_cnid > cnid) return 1; /* referring to the same cnids */ /* we are always looking for the data fork */ if (key->fork_type != HFS_EXT_KEY_TYPE_DATA) return 1; /* we are always looking for a start_block of zero (interested in the beginning of the extents, regardless of what the start_block is); all files except the bad blocks file should have a start_block greater than zero */ if (tsk_getu32(fs->endian, key->start_block) == 0) return 0; return 1; } /** \internal * Returns the length of an HFS+ B-tree INDEX key based on the tree header * structure and the length claimed in the record. With some trees, * the length given in the record is not used. * Note that this neither detects nor correctly handles 8-bit keys * (which should not be present in HFS+). * * This does not give the right answer for the Attributes File B-tree, for some * HFS+ file systems produced by the Apple OS, while it works for others. For * the Attributes file, INDEX keys should always be as stated in the record itself, * never the "maxKeyLen" of the B-tree header. * * In this software, this function is only invoked when dealing with the Extents file. In * that usage, it is not sufficiently well tested to know if it always gives the right * answer or not. We can only test that with a highly fragmented disk. * @param hfs File System * @param keylen Length of key as given in record * @param header Tree header * @returns Length of key */ uint16_t hfs_get_idxkeylen(HFS_INFO * hfs, uint16_t keylen, const hfs_btree_header_record * header) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); // if the flag is set, use the length given in the record if (tsk_getu32(fs->endian, header->attr) & HFS_BT_HEAD_ATTR_VARIDXKEYS) return keylen; else return tsk_getu16(fs->endian, header->maxKeyLen); } /** * Convert the extents runs to TSK_FS_ATTR_RUN runs. * * @param a_fs File system to analyze * @param a_extents Raw extents to process (in an array of 8) * @param a_start_off Starting block offset of these runs * @returns NULL on error or if no runs are in extents (test tsk_errno) */ static TSK_FS_ATTR_RUN * hfs_extents_to_attr(TSK_FS_INFO * a_fs, const hfs_ext_desc * a_extents, TSK_OFF_T a_start_off) { TSK_FS_ATTR_RUN *head_run = NULL; TSK_FS_ATTR_RUN *prev_run = NULL; int i; TSK_OFF_T cur_off = a_start_off; // since tsk_errno is checked as a return value, make sure it is clean. tsk_error_reset(); if (tsk_verbose) tsk_fprintf(stderr, "hfs_extents_to_attr: Converting extents from offset %" PRIuOFF " to runlist\n", a_start_off); for (i = 0; i < 8; ++i) { TSK_FS_ATTR_RUN *cur_run; uint32_t addr = tsk_getu32(a_fs->endian, a_extents[i].start_blk); uint32_t len = tsk_getu32(a_fs->endian, a_extents[i].blk_cnt); if (tsk_verbose) tsk_fprintf(stderr, "hfs_extents_to_attr: run %i at addr %" PRIu32 " with len %" PRIu32 "\n", i, addr, len); if ((addr == 0) && (len == 0)) { break; } // make a non-resident run if ((cur_run = tsk_fs_attr_run_alloc()) == NULL) { error_returned(" - hfs_extents_to_attr"); return NULL; } cur_run->addr = addr; cur_run->len = len; cur_run->offset = cur_off; if (head_run == NULL) head_run = cur_run; if (prev_run != NULL) prev_run->next = cur_run; cur_off += cur_run->len; prev_run = cur_run; } return head_run; } /** * Look in the extents catalog for entries for a given file. Add the runs * to the passed attribute structure. * * @param hfs File system being analyzed * @param cnid file id of file to search for * @param a_attr Attribute to add extents runs to * @param dataForkQ if true, then find extents for the data fork. If false, then find extents for the Resource fork. * @returns 1 on error and 0 on success */ static uint8_t hfs_ext_find_extent_record_attr(HFS_INFO * hfs, uint32_t cnid, TSK_FS_ATTR * a_attr, unsigned char dataForkQ) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint16_t nodesize; /* size of nodes (all, regardless of the name) */ uint32_t cur_node; /* node id of the current node */ char *node = NULL; uint8_t is_done; uint8_t desiredType; tsk_error_reset(); if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record_attr: Looking for extents for file %" PRIu32 " %s\n", cnid, dataForkQ ? "data fork" : "resource fork"); if (!hfs->has_extents_file) { // No extents file (which is optional), and so, no further extents are possible. return 0; } // Are we looking for extents of the data fork or the resource fork? desiredType = dataForkQ ? HFS_EXT_KEY_TYPE_DATA : HFS_EXT_KEY_TYPE_RSRC; // Load the extents attribute, if it has not been done so yet. if (hfs->extents_file == NULL) { ssize_t cnt; if ((hfs->extents_file = tsk_fs_file_open_meta(fs, NULL, HFS_EXTENTS_FILE_ID)) == NULL) { return 1; } /* cache the data attribute */ hfs->extents_attr = tsk_fs_attrlist_get(hfs->extents_file->meta->attr, TSK_FS_ATTR_TYPE_DEFAULT); if (!hfs->extents_attr) { tsk_error_errstr2_concat (" - Default Attribute not found in Extents File"); return 1; } // cache the extents file header cnt = tsk_fs_attr_read(hfs->extents_attr, 14, (char *) &(hfs->extents_header), sizeof(hfs_btree_header_record), 0); if (cnt != sizeof(hfs_btree_header_record)) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_ext_find_extent_record_attr: Error reading header"); return 1; } } // allocate a node buffer nodesize = tsk_getu16(fs->endian, hfs->extents_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) { return 1; } /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->extents_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: " "empty extents btree\n"); free(node); return 0; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; // sanity check if (cur_node > tsk_getu32(fs->endian, hfs->extents_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: Node %d too large for file", cur_node); free(node); return 1; } // read the current node cur_off = (TSK_OFF_T)cur_node * nodesize; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: reading node %" PRIu32 " at offset %" PRIuOFF "\n", cur_node, cur_off); cnt = tsk_fs_attr_read(hfs->extents_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_ext_find_extent_record_attr: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } // process the header / descriptor if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: Index node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); for (rec = 0; rec < num_rec; ++rec) { int cmp; size_t rec_off; hfs_btree_key_ext *key; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off + sizeof(hfs_btree_key_ext) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_ext *) & node[rec_off]; cmp = hfs_ext_compare_keys(hfs, cnid, key); if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: record %" PRIu16 " ; keylen %" PRIu16 " (FileId: %" PRIu32 ", ForkType: %" PRIu8 ", StartBlk: %" PRIu32 "); compare: %d\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->file_id), key->fork_type, tsk_getu32(fs->endian, key->start_block), cmp); /* save the info from this record unless it is bigger than cnid */ if ((cmp <= 0) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->extents_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } // we are bigger than cnid, so move on to the next node if (cmp > 0) { break; } } // check if we found a relevant node, if not stop. if (next_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record_attr: did not find any keys for %d in index node %d", cnid, cur_node); is_done = 1; break; } cur_node = next_node; } /* with a leaf, we process until we are past cnid. We move right too if we can */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: Leaf node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_ext *key; uint32_t rec_cnid; hfs_extents *extents; TSK_OFF_T ext_off = 0; int keylen; TSK_FS_ATTR_RUN *attr_run; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_ext *) & node[rec_off]; if (tsk_verbose) tsk_fprintf(stderr, "hfs_ext_find_extent_record: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ", %" PRIu8 ", %" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->file_id), key->fork_type, tsk_getu32(fs->endian, key->start_block)); rec_cnid = tsk_getu32(fs->endian, key->file_id); // see if this record is for our file // OLD logic, just handles the DATA fork // if (rec_cnid < cnid) { // continue; // } // else if ((rec_cnid > cnid) // || (key->fork_type != HFS_EXT_KEY_TYPE_DATA)) { // is_done = 1; // break; // } // NEW logic, handles both DATA and RSRC forks. if (rec_cnid < cnid) { continue; } if (rec_cnid > cnid) { is_done = 1; break; } if (key->fork_type != desiredType) { if (dataForkQ) { is_done = 1; break; } else continue; } // OK, this is one of the extents records that we are seeking, so save it. // Make sure there is room for the hfs_extents struct keylen = 2 + tsk_getu16(fs->endian, key->key_len); if (rec_off + keylen + sizeof(hfs_extents) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_ext_find_extent_record_attr: offset and keylenth of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } // get the starting offset of this extent ext_off = tsk_getu32(fs->endian, key->start_block); // convert the extents to the TSK format extents = (hfs_extents *) & node[rec_off + keylen]; attr_run = hfs_extents_to_attr(fs, extents->extents, ext_off); if ((attr_run == NULL) && (tsk_error_get_errno() != 0)) { tsk_error_errstr2_concat (" - hfs_ext_find_extent_record_attr"); free(node); return 1; } if (tsk_fs_attr_add_run(fs, a_attr, attr_run)) { tsk_error_errstr2_concat (" - hfs_ext_find_extent_record_attr"); free(node); return 1; } } cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; break; } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_ext_find_extent_record: btree node %" PRIu32 " (%" PRIuOFF ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; } /** \internal * Compares two Catalog B-tree keys. * @param hfs File System being analyzed * @param key1 Key 1 to compare * @param key2 Key 2 to compare * @returns -1 if key1 is smaller, 0 if equal, and 1 if key1 is larger */ int hfs_cat_compare_keys(HFS_INFO * hfs, const hfs_btree_key_cat * key1, const hfs_btree_key_cat * key2) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint32_t cnid1, cnid2; cnid1 = tsk_getu32(fs->endian, key1->parent_cnid); cnid2 = tsk_getu32(fs->endian, key2->parent_cnid); if (cnid1 < cnid2) return -1; if (cnid1 > cnid2) return 1; return hfs_unicode_compare(hfs, &key1->name, &key2->name); } /** \internal * * Traverse the HFS catalog file. Call the callback for each * record. * * @param hfs File system * @param a_cb callback * @param ptr Pointer to pass to callback * @returns 1 on error */ uint8_t hfs_cat_traverse(HFS_INFO * hfs, TSK_HFS_BTREE_CB a_cb, void *ptr) { TSK_FS_INFO *fs = &(hfs->fs_info); uint32_t cur_node; /* node id of the current node */ char *node; uint16_t nodesize; uint8_t is_done = 0; tsk_error_reset(); nodesize = tsk_getu16(fs->endian, hfs->catalog_header.nodesize); if ((node = (char *) tsk_malloc(nodesize)) == NULL) return 1; /* start at root node */ cur_node = tsk_getu32(fs->endian, hfs->catalog_header.rootNode); /* if the root node is zero, then the extents btree is empty */ /* if no files have overflow extents, the Extents B-tree still exists on disk, but is an empty B-tree containing only the header node */ if (cur_node == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: " "empty extents btree\n"); free(node); return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: starting at " "root node %" PRIu32 "; nodesize = %" PRIu16 "\n", cur_node, nodesize); /* Recurse down to the needed leaf nodes and then go forward */ is_done = 0; while (is_done == 0) { TSK_OFF_T cur_off; /* start address of cur_node */ uint16_t num_rec; /* number of records in this node */ ssize_t cnt; hfs_btree_node *node_desc; // sanity check if (cur_node > tsk_getu32(fs->endian, hfs->catalog_header.totalNodes)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node %d too large for file", cur_node); free(node); return 1; } // read the current node cur_off = cur_node * nodesize; cnt = tsk_fs_attr_read(hfs->catalog_attr, cur_off, node, nodesize, 0); if (cnt != nodesize) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_traverse: Error reading node %d at offset %" PRIuOFF, cur_node, cur_off); free(node); return 1; } // process the header / descriptor if (nodesize < sizeof(hfs_btree_node)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: Node size %d is too small to be valid", nodesize); free(node); return 1; } node_desc = (hfs_btree_node *) node; num_rec = tsk_getu16(fs->endian, node_desc->num_rec); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: node %" PRIu32 " @ %" PRIu64 " has %" PRIu16 " records\n", cur_node, cur_off, num_rec); if (num_rec == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: zero records in node %" PRIu32, cur_node); free(node); return 1; } /* With an index node, find the record with the largest key that is smaller * to or equal to cnid */ if (node_desc->type == HFS_BT_NODE_TYPE_IDX) { uint32_t next_node = 0; int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 " ; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ /* save the info from this record unless it is too big */ retval = a_cb(hfs, HFS_BT_NODE_TYPE_IDX, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } // record the closest entry else if ((retval == HFS_BTREE_CB_IDX_LT) || (next_node == 0)) { hfs_btree_index_record *idx_rec; int keylen = 2 + hfs_get_idxkeylen(hfs, tsk_getu16(fs->endian, key->key_len), &(hfs->catalog_header)); if (rec_off + keylen > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record and keylength %d in index node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off + keylen, nodesize); free(node); return 1; } idx_rec = (hfs_btree_index_record *) & node[rec_off + keylen]; next_node = tsk_getu32(fs->endian, idx_rec->childNode); } if (retval == HFS_BTREE_CB_IDX_EQGT) { // move down to the next node break; } } // check if we found a relevant node if (next_node == 0) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: did not find any keys in index node %d", cur_node); is_done = 1; break; } // TODO: Handle multinode loops if (next_node == cur_node) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: node %d references itself as next node", cur_node); is_done = 1; break; } cur_node = next_node; } /* With a leaf, we look for the specific record. */ else if (node_desc->type == HFS_BT_NODE_TYPE_LEAF) { int rec; for (rec = 0; rec < num_rec; ++rec) { size_t rec_off; hfs_btree_key_cat *key; uint8_t retval; int keylen; // get the record offset in the node rec_off = tsk_getu16(fs->endian, &node[nodesize - (rec + 1) * 2]); if (rec_off > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: offset of record %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, (int) rec_off, nodesize); free(node); return 1; } key = (hfs_btree_key_cat *) & node[rec_off]; keylen = 2 + tsk_getu16(hfs->fs_info.endian, key->key_len); if ((keylen) > nodesize) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_traverse: length of key %d in leaf node %d too large (%d vs %" PRIu16 ")", rec, cur_node, keylen, nodesize); free(node); return 1; } /* if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: record %" PRIu16 "; keylen %" PRIu16 " (%" PRIu32 ")\n", rec, tsk_getu16(fs->endian, key->key_len), tsk_getu32(fs->endian, key->parent_cnid)); */ // rec_cnid = tsk_getu32(fs->endian, key->file_id); retval = a_cb(hfs, HFS_BT_NODE_TYPE_LEAF, key, cur_off + rec_off, ptr); if (retval == HFS_BTREE_CB_LEAF_STOP) { is_done = 1; break; } else if (retval == HFS_BTREE_CB_ERR) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr2 ("hfs_cat_traverse: Callback returned error"); free(node); return 1; } } // move right to the next node if we got this far if (is_done == 0) { cur_node = tsk_getu32(fs->endian, node_desc->flink); if (cur_node == 0) { is_done = 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_traverse: moving forward to next leaf"); } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr("hfs_cat_traverse: btree node %" PRIu32 " (%" PRIu64 ") is neither index nor leaf (%" PRIu8 ")", cur_node, cur_off, node_desc->type); free(node); return 1; } } free(node); return 0; } typedef struct { const hfs_btree_key_cat *targ_key; TSK_OFF_T off; } HFS_CAT_GET_RECORD_OFFSET_DATA; static uint8_t hfs_cat_get_record_offset_cb(HFS_INFO * hfs, int8_t level_type, const hfs_btree_key_cat * cur_key, TSK_OFF_T key_off, void *ptr) { HFS_CAT_GET_RECORD_OFFSET_DATA *offset_data = (HFS_CAT_GET_RECORD_OFFSET_DATA *)ptr; const hfs_btree_key_cat *targ_key = offset_data->targ_key; if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_get_record_offset_cb: %s node want: %" PRIu32 " vs have: %" PRIu32 "\n", (level_type == HFS_BT_NODE_TYPE_IDX) ? "Index" : "Leaf", tsk_getu32(hfs->fs_info.endian, targ_key->parent_cnid), tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid)); if (level_type == HFS_BT_NODE_TYPE_IDX) { int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key); if (diff < 0) return HFS_BTREE_CB_IDX_LT; else return HFS_BTREE_CB_IDX_EQGT; } else { int diff = hfs_cat_compare_keys(hfs, cur_key, targ_key); // see if this record is for our file or if we passed the interesting entries if (diff < 0) { return HFS_BTREE_CB_LEAF_GO; } else if (diff == 0) { offset_data->off = key_off + 2 + tsk_getu16(hfs->fs_info.endian, cur_key->key_len); } return HFS_BTREE_CB_LEAF_STOP; } } /** \internal * Find the byte offset (from the start of the catalog file) to a record * in the catalog file. * @param hfs File System being analyzed * @param needle Key to search for * @returns Byte offset or 0 on error. 0 is also returned if catalog * record was not found. Check tsk_errno to determine if error occurred. */ static TSK_OFF_T hfs_cat_get_record_offset(HFS_INFO * hfs, const hfs_btree_key_cat * needle) { HFS_CAT_GET_RECORD_OFFSET_DATA offset_data; offset_data.off = 0; offset_data.targ_key = needle; if (hfs_cat_traverse(hfs, hfs_cat_get_record_offset_cb, &offset_data)) { return 0; } return offset_data.off; } /** \internal * Given a byte offset to a leaf record in teh catalog file, read the data as * a thread record. This will zero the buffer and read in the size of the thread * data. * @param hfs File System * @param off Byte offset of record in catalog file (not including key) * @param thread [out] Buffer to write thread data into. * @returns 0 on success, 1 on failure; sets up to error string 1 */ uint8_t hfs_cat_read_thread_record(HFS_INFO * hfs, TSK_OFF_T off, hfs_thread * thread) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); uint16_t uni_len; ssize_t cnt; memset(thread, 0, sizeof(hfs_thread)); cnt = tsk_fs_attr_read(hfs->catalog_attr, off, (char *) thread, 10, 0); if (cnt != 10) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_read_thread_record: Error reading catalog offset %" PRIuOFF " (header)", off); return 1; } if ((tsk_getu16(fs->endian, thread->rec_type) != HFS_FOLDER_THREAD) && (tsk_getu16(fs->endian, thread->rec_type) != HFS_FILE_THREAD)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_read_thread_record: unexpected record type %" PRIu16, tsk_getu16(fs->endian, thread->rec_type)); return 1; } uni_len = tsk_getu16(fs->endian, thread->name.length); if (uni_len > 255) { tsk_error_set_errno(TSK_ERR_FS_INODE_COR); tsk_error_set_errstr ("hfs_cat_read_thread_record: invalid string length (%" PRIu16 ")", uni_len); return 1; } cnt = tsk_fs_attr_read(hfs->catalog_attr, off + 10, (char *) thread->name.unicode, uni_len * 2, 0); if (cnt != uni_len * 2) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_read_thread_record: Error reading catalog offset %" PRIuOFF " (name)", off + 10); return 1; } return 0; } /** \internal * Read a catalog record into a local data structure. This reads the * correct amount, depending on if it is a file or folder. * @param hfs File system being analyzed * @param off Byte offset (in catalog file) of record (not including key) * @param record [out] Structure to read data into * @returns 1 on error */ uint8_t hfs_cat_read_file_folder_record(HFS_INFO * hfs, TSK_OFF_T off, hfs_file_folder * record) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); ssize_t cnt; char rec_type[2]; memset(record, 0, sizeof(hfs_file_folder)); cnt = tsk_fs_attr_read(hfs->catalog_attr, off, rec_type, 2, 0); if (cnt != 2) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_read_file_folder_record: Error reading record type from catalog offset %" PRIuOFF " (header)", off); return 1; } if (tsk_getu16(fs->endian, rec_type) == HFS_FOLDER_RECORD) { cnt = tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record, sizeof(hfs_folder), 0); if (cnt != sizeof(hfs_folder)) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_read_file_folder_record: Error reading catalog offset %" PRIuOFF " (folder)", off); return 1; } } else if (tsk_getu16(fs->endian, rec_type) == HFS_FILE_RECORD) { cnt = tsk_fs_attr_read(hfs->catalog_attr, off, (char *) record, sizeof(hfs_file), 0); if (cnt != sizeof(hfs_file)) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } tsk_error_set_errstr2 ("hfs_cat_read_file_folder_record: Error reading catalog offset %" PRIuOFF " (file)", off); return 1; } } else { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_read_file_folder_record: unexpected record type %" PRIu16, tsk_getu16(fs->endian, rec_type)); return 1; } return 0; } // hfs_lookup_hard_link appears to be unnecessary - it looks up the cnid // by seeing if there's a file/dir with the standard hard link name plus // linknum and returns the meta_addr. But this should always be the same as linknum, // and is very slow when there are many hard links, so it shouldn't be used. //static TSK_INUM_T //hfs_lookup_hard_link(HFS_INFO * hfs, TSK_INUM_T linknum, // unsigned char is_directory) //{ // char fBuff[30]; // TSK_FS_DIR *mdir; // size_t indx; // TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; // // memset(fBuff, 0, 30); // // if (is_directory) { // // tsk_take_lock(&(hfs->metadata_dir_cache_lock)); // if (hfs->dir_meta_dir == NULL) { // hfs->dir_meta_dir = // tsk_fs_dir_open_meta(fs, hfs->meta_dir_inum); // } // tsk_release_lock(&(hfs->metadata_dir_cache_lock)); // // if (hfs->dir_meta_dir == NULL) { // error_returned // ("hfs_lookup_hard_link: could not open the dir metadata directory"); // return 0; // } // else { // mdir = hfs->dir_meta_dir; // } // snprintf(fBuff, 30, "dir_%" PRIuINUM, linknum); // // } // else { // // tsk_take_lock(&(hfs->metadata_dir_cache_lock)); // if (hfs->meta_dir == NULL) { // hfs->meta_dir = tsk_fs_dir_open_meta(fs, hfs->meta_inum); // } // tsk_release_lock(&(hfs->metadata_dir_cache_lock)); // // if (hfs->meta_dir == NULL) { // error_returned // ("hfs_lookup_hard_link: could not open file metadata directory"); // return 0; // } // else { // mdir = hfs->meta_dir; // } // snprintf(fBuff, 30, "iNode%" PRIuINUM, linknum); // } // // for (indx = 0; indx < tsk_fs_dir_getsize(mdir); ++indx) { // if ((mdir->names != NULL) && mdir->names[indx].name && // (fs->name_cmp(fs, mdir->names[indx].name, fBuff) == 0)) { // // OK this is the one // return mdir->names[indx].meta_addr; // } // } // // // OK, we did not find that linknum // return 0; //} /* * Given a catalog entry, will test that entry to see if it is a hard link. * If it is a hard link, the function returns the inum (or cnid) of the target file. * If it is NOT a hard link, then then function returns the inum of the given entry. * In both cases, the parameter is_error is set to zero. * * If an ERROR occurs, if it is a mild error, then is_error is set to 1, and the * inum of the given entry is returned. This signals that hard link detection cannot * be carried out. * * If the error is serious, then is_error is set to 2 or 3, depending on the kind of error, and * the TSK error code is set, and the function returns zero. is_error==2 means that an error * occurred in looking up the target file in the Catalog. is_error==3 means that the given * entry appears to be a hard link, but the target file does not exist in the Catalog. * * @param hfs The file system * @param entry The catalog entry to check * @param is_error A Boolean that is returned indicating an error, or no error.\ * @return The inum (or cnid) of the hard link target, or of the given catalog entry, or zero. */ TSK_INUM_T hfs_follow_hard_link(HFS_INFO * hfs, hfs_file * cat, unsigned char *is_error) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_INUM_T cnid; time_t crtime; uint32_t file_type; uint32_t file_creator; *is_error = 0; // default, not an error if (cat == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_follow_hard_link: Pointer to Catalog entry (2nd arg) is null"); return 0; } cnid = tsk_getu32(fs->endian, cat->std.cnid); if (cnid < HFS_FIRST_USER_CNID) { // Can't be a hard link. And, cannot look up in Catalog file either! return cnid; } crtime = (time_t) hfs_convert_2_unix_time(tsk_getu32(fs->endian, cat->std.crtime)); file_type = tsk_getu32(fs->endian, cat->std.u_info.file_type); file_creator = tsk_getu32(fs->endian, cat->std.u_info.file_cr); // Only proceed with the rest of this if the flags etc are right if (file_type == HFS_HARDLINK_FILE_TYPE && file_creator == HFS_HARDLINK_FILE_CREATOR) { // see if we have the HFS+ Private Data dir for file links; // if not, it can't be a hard link. (We could warn the user, but // we also rely on this when finding the HFS+ Private Data dir in // the first place and we don't want a warning on every hfs_open.) if (hfs->meta_inum == 0) return cnid; // For this to work, we need the FS creation times. Is at least one of these set? if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime) && (!hfs->has_meta_crtime)) { uint32_t linkNum = tsk_getu32(fs->endian, cat->std.perm.special.inum); *is_error = 1; if (tsk_verbose) tsk_fprintf(stderr, "WARNING: hfs_follow_hard_link: File system creation times are not set. " "Cannot test inode for hard link. File type and creator indicate that this" " is a hard link (file), with LINK ID = %" PRIu32 "\n", linkNum); return cnid; } if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime)) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: hfs_follow_hard_link: Either the root folder or the" " file metadata folder is not accessible. Testing this potential hard link" " may be impaired.\n"); } // Now we need to check the creation time against the three FS creation times if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) || (hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime)) || (hfs->has_root_crtime && (crtime == hfs->root_crtime))) { // OK, this is a hard link to a file. uint32_t linkNum = tsk_getu32(fs->endian, cat->std.perm.special.inum); // We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found // that it was very ineffecient and always resulted in the same linkNum value. // We now just use linkNum return linkNum; } } else if (file_type == HFS_LINKDIR_FILE_TYPE && file_creator == HFS_LINKDIR_FILE_CREATOR) { // see if we have the HFS+ Private Directory Data dir for links; // if not, it can't be a hard link. (We could warn the user, but // we also rely on this when finding the HFS+ Private Directory Data dir in // the first place and we don't want a warning on every hfs_open.) if (hfs->meta_dir_inum == 0) return cnid; // For this to work, we need the FS creation times. Is at least one of these set? if ((!hfs->has_root_crtime) && (!hfs->has_meta_dir_crtime) && (!hfs->has_meta_crtime)) { uint32_t linkNum = tsk_getu32(fs->endian, cat->std.perm.special.inum); *is_error = 1; if (tsk_verbose) tsk_fprintf(stderr, "WARNING: hfs_follow_hard_link: File system creation times are not set. " "Cannot test inode for hard link. File type and creator indicate that this" " is a hard link (directory), with LINK ID = %" PRIu32 "\n", linkNum); return cnid; } if ((!hfs->has_root_crtime) || (!hfs->has_meta_crtime) || (!hfs->has_meta_dir_crtime)) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: hfs_follow_hard_link: Either the root folder or the" " file metadata folder or the directory metatdata folder is" " not accessible. Testing this potential hard linked folder " "may be impaired.\n"); } // Now we need to check the creation time against the three FS creation times if ((hfs->has_meta_crtime && (crtime == hfs->meta_crtime)) || (hfs->has_meta_dir_crtime && (crtime == hfs->metadir_crtime)) || (hfs->has_root_crtime && (crtime == hfs->root_crtime))) { // OK, this is a hard link to a directory. uint32_t linkNum = tsk_getu32(fs->endian, cat->std.perm.special.inum); // We used to resolve this ID to a file in X folder using hfs_lookup_hard_link, but found // that it was very ineffecient and always resulted in the same linkNum value. // We now just use linkNum return linkNum; } } // It cannot be a hard link (file or directory) return cnid; } /** \internal * Lookup an entry in the catalog file and save it into the entry. Do not * call this for the special files that do not have an entry in the catalog. * data structure. * @param hfs File system being analyzed * @param inum Address (cnid) of file to open * @param entry [out] Structure to read data into * @returns 1 on error or not found, 0 on success. Check tsk_errno * to differentiate between error and not found. If it is not found, then the * errno will be TSK_ERR_FS_INODE_NUM. Else, it will be some other value. */ uint8_t hfs_cat_file_lookup(HFS_INFO * hfs, TSK_INUM_T inum, HFS_ENTRY * entry, unsigned char follow_hard_link) { TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); hfs_btree_key_cat key; /* current catalog key */ hfs_thread thread; /* thread record */ hfs_file_folder record; /* file/folder record */ TSK_OFF_T off; tsk_error_reset(); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup: called for inum %" PRIuINUM "\n", inum); // Test if this is a special file that is not located in the catalog if ((inum == HFS_EXTENTS_FILE_ID) || (inum == HFS_CATALOG_FILE_ID) || (inum == HFS_ALLOCATION_FILE_ID) || (inum == HFS_STARTUP_FILE_ID) || (inum == HFS_ATTRIBUTES_FILE_ID)) { tsk_error_set_errno(TSK_ERR_FS_GENFS); tsk_error_set_errstr ("hfs_cat_file_lookup: Called on special file: %" PRIuINUM, inum); return 1; } /* first look up the thread record for the item we're searching for */ /* set up the thread record key */ memset((char *) &key, 0, sizeof(hfs_btree_key_cat)); cnid_to_array((uint32_t) inum, key.parent_cnid); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup: Looking up thread record (%" PRIuINUM ")\n", inum); /* look up the thread record */ off = hfs_cat_get_record_offset(hfs, &key); if (off == 0) { // no parsing error, just not found if (tsk_error_get_errno() == 0) { tsk_error_set_errno(TSK_ERR_FS_INODE_NUM); tsk_error_set_errstr ("hfs_cat_file_lookup: Error finding thread node for file (%" PRIuINUM ")", inum); } else { tsk_error_set_errstr2 (" hfs_cat_file_lookup: thread for file (%" PRIuINUM ")", inum); } return 1; } /* read the thread record */ if (hfs_cat_read_thread_record(hfs, off, &thread)) { tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")", inum); return 1; } /* now look up the actual file/folder record */ /* build key */ memset((char *) &key, 0, sizeof(hfs_btree_key_cat)); memcpy((char *) key.parent_cnid, (char *) thread.parent_cnid, sizeof(key.parent_cnid)); memcpy((char *) &key.name, (char *) &thread.name, sizeof(key.name)); if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup: Looking up file record (parent: %" PRIuINUM ")\n", (uint64_t) tsk_getu32(fs->endian, key.parent_cnid)); /* look up the record */ off = hfs_cat_get_record_offset(hfs, &key); if (off == 0) { // no parsing error, just not found if (tsk_error_get_errno() == 0) { tsk_error_set_errno(TSK_ERR_FS_INODE_NUM); tsk_error_set_errstr ("hfs_cat_file_lookup: Error finding record node %" PRIuINUM, inum); } else { tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")", inum); } return 1; } /* read the record */ if (hfs_cat_read_file_folder_record(hfs, off, &record)) { tsk_error_set_errstr2(" hfs_cat_file_lookup: file (%" PRIuINUM ")", inum); return 1; } /* these memcpy can be gotten rid of, really */ if (tsk_getu16(fs->endian, record.file.std.rec_type) == HFS_FOLDER_RECORD) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup: found folder record valence %" PRIu32 ", cnid %" PRIu32 "\n", tsk_getu32(fs->endian, record.folder.std.valence), tsk_getu32(fs->endian, record.folder.std.cnid)); memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_folder)); } else if (tsk_getu16(fs->endian, record.file.std.rec_type) == HFS_FILE_RECORD) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup: found file record cnid %" PRIu32 "\n", tsk_getu32(fs->endian, record.file.std.cnid)); memcpy((char *) &entry->cat, (char *) &record, sizeof(hfs_file)); } /* other cases already caught by hfs_cat_read_file_folder_record */ memcpy((char *) &entry->thread, (char *) &thread, sizeof(hfs_thread)); entry->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED; entry->inum = inum; if (follow_hard_link) { // TEST to see if this is a hard link unsigned char is_err; TSK_INUM_T target_cnid = hfs_follow_hard_link(hfs, &(entry->cat), &is_err); if (is_err > 1) { error_returned ("hfs_cat_file_lookup: error occurred while following a possible hard link for " "inum (cnid) = %" PRIuINUM, inum); return 1; } if (target_cnid != inum) { // This is a hard link, and we have got the cnid of the target file, so look it up. uint8_t res = hfs_cat_file_lookup(hfs, target_cnid, entry, FALSE); if (res != 0) { error_returned ("hfs_cat_file_lookup: error occurred while looking up the Catalog entry for " "the target of inum (cnid) = %" PRIuINUM " target", inum); } return 1; } // Target is NOT a hard link, so fall through to the non-hard link exit. } if (tsk_verbose) tsk_fprintf(stderr, "hfs_cat_file_lookup exiting\n"); return 0; } static uint8_t hfs_find_highest_inum_cb(HFS_INFO * hfs, int8_t level_type, const hfs_btree_key_cat * cur_key, TSK_OFF_T key_off, void *ptr) { // NOTE: This assumes that the biggest inum is the last one that we // see. the traverse method does not currently promise that as part of // its callback "contract". *((TSK_INUM_T*) ptr) = tsk_getu32(hfs->fs_info.endian, cur_key->parent_cnid); return HFS_BTREE_CB_IDX_LT; } /** \internal * Returns the largest inode number in file system * @param hfs File system being analyzed * @returns largest metadata address */ static TSK_INUM_T hfs_find_highest_inum(HFS_INFO * hfs) { // @@@ get actual number from Catalog file (go to far right) (we can't always trust the vol header) TSK_INUM_T inum; if (hfs_cat_traverse(hfs, hfs_find_highest_inum_cb, &inum)) { /* Catalog traversal failed, fallback on legacy method : if HFS_VH_ATTR_CNIDS_REUSED is set, then the maximum CNID is 2^32-1; if it's not set, then nextCatalogId is supposed to be larger than all CNIDs on disk. */ TSK_FS_INFO *fs = (TSK_FS_INFO *) & (hfs->fs_info); if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_CNIDS_REUSED) return (TSK_INUM_T) 0xffffffff; else return (TSK_INUM_T) tsk_getu32(fs->endian, hfs->fs->next_cat_id) - 1; } return inum; } static TSK_FS_META_MODE_ENUM hfs_mode_to_tsk_mode(uint16_t a_mode) { TSK_FS_META_MODE_ENUM mode = 0; if (a_mode & HFS_IN_ISUID) mode |= TSK_FS_META_MODE_ISUID; if (a_mode & HFS_IN_ISGID) mode |= TSK_FS_META_MODE_ISGID; if (a_mode & HFS_IN_ISVTX) mode |= TSK_FS_META_MODE_ISVTX; if (a_mode & HFS_IN_IRUSR) mode |= TSK_FS_META_MODE_IRUSR; if (a_mode & HFS_IN_IWUSR) mode |= TSK_FS_META_MODE_IWUSR; if (a_mode & HFS_IN_IXUSR) mode |= TSK_FS_META_MODE_IXUSR; if (a_mode & HFS_IN_IRGRP) mode |= TSK_FS_META_MODE_IRGRP; if (a_mode & HFS_IN_IWGRP) mode |= TSK_FS_META_MODE_IWGRP; if (a_mode & HFS_IN_IXGRP) mode |= TSK_FS_META_MODE_IXGRP; if (a_mode & HFS_IN_IROTH) mode |= TSK_FS_META_MODE_IROTH; if (a_mode & HFS_IN_IWOTH) mode |= TSK_FS_META_MODE_IWOTH; if (a_mode & HFS_IN_IXOTH) mode |= TSK_FS_META_MODE_IXOTH; return mode; } static TSK_FS_META_TYPE_ENUM hfs_mode_to_tsk_meta_type(uint16_t a_mode) { switch (a_mode & HFS_IN_IFMT) { case HFS_IN_IFIFO: return TSK_FS_META_TYPE_FIFO; case HFS_IN_IFCHR: return TSK_FS_META_TYPE_CHR; case HFS_IN_IFDIR: return TSK_FS_META_TYPE_DIR; case HFS_IN_IFBLK: return TSK_FS_META_TYPE_BLK; case HFS_IN_IFREG: return TSK_FS_META_TYPE_REG; case HFS_IN_IFLNK: return TSK_FS_META_TYPE_LNK; case HFS_IN_IFSOCK: return TSK_FS_META_TYPE_SOCK; case HFS_IFWHT: return TSK_FS_META_TYPE_WHT; case HFS_IFXATTR: return TSK_FS_META_TYPE_UNDEF; default: /* error */ return TSK_FS_META_TYPE_UNDEF; } } static uint8_t hfs_make_specialbase(TSK_FS_FILE * fs_file) { fs_file->meta->type = TSK_FS_META_TYPE_REG; fs_file->meta->mode = 0; fs_file->meta->nlink = 1; fs_file->meta->flags = (TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_ALLOC); fs_file->meta->uid = fs_file->meta->gid = 0; fs_file->meta->mtime = fs_file->meta->atime = fs_file->meta->ctime = fs_file->meta->crtime = 0; fs_file->meta->mtime_nano = fs_file->meta->atime_nano = fs_file->meta->ctime_nano = fs_file->meta->crtime_nano = 0; if (fs_file->meta->name2 == NULL) { if ((fs_file->meta->name2 = (TSK_FS_META_NAME_LIST *) tsk_malloc(sizeof(TSK_FS_META_NAME_LIST))) == NULL) { error_returned (" - hfs_make_specialbase, couldn't malloc space for a name list"); return 1; } fs_file->meta->name2->next = NULL; } if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } return 0; } /** * \internal * Create an FS_INODE structure for the catalog file. * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_catalog(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; unsigned char dummy1, dummy2; uint64_t dummy3; uint8_t result; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_catalog: Making virtual catalog file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_catalog"); return 1; } fs_file->meta->addr = HFS_CATALOG_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_CATALOGNAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz); // convert the runs in the volume header to attribute runs if (((attr_run = hfs_extents_to_attr(fs, hfs->fs->cat_file.extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_make_catalog"); return 1; } if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_catalog"); tsk_fs_attr_run_free(attr_run); return 1; } // initialize the data run if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->cat_file.logic_sz), 0, 0)) { error_returned(" - hfs_make_catalog"); tsk_fs_attr_run_free(attr_run); return 1; } // see if catalog file has additional runs if (hfs_ext_find_extent_record_attr(hfs, HFS_CATALOG_FILE_ID, fs_attr, TRUE)) { error_returned(" - hfs_make_catalog"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3); if (result != 0) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: Extended attributes failed to load for the Catalog file.\n"); tsk_error_reset(); } fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** * \internal * Create an FS_FILE for the extents file * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_extents(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_extents: Making virtual extents file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_extents"); return 1; } fs_file->meta->addr = HFS_EXTENTS_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_EXTENTSNAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz); if (((attr_run = hfs_extents_to_attr(fs, hfs->fs->ext_file.extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_make_extents"); return 1; } if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_extents"); tsk_fs_attr_run_free(attr_run); return 1; } // initialize the data run if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->ext_file.logic_sz), 0, 0)) { error_returned(" - hfs_make_extents"); tsk_fs_attr_run_free(attr_run); return 1; } //hfs_load_extended_attrs(fs_file); // Extents doesn't have an entry in itself fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** * \internal * Create an FS_INODE structure for the blockmap / allocation file. * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_blockmap(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; unsigned char dummy1, dummy2; uint64_t dummy3; uint8_t result; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_blockmap: Making virtual blockmap file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_blockmap"); return 1; } fs_file->meta->addr = HFS_ALLOCATION_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_ALLOCATIONNAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz); if (((attr_run = hfs_extents_to_attr(fs, hfs->fs->alloc_file.extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_make_blockmap"); return 1; } if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_blockmap"); tsk_fs_attr_run_free(attr_run); return 1; } // initialize the data run if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->alloc_file.logic_sz), 0, 0)) { error_returned(" - hfs_make_blockmap"); tsk_fs_attr_run_free(attr_run); return 1; } // see if catalog file has additional runs if (hfs_ext_find_extent_record_attr(hfs, HFS_ALLOCATION_FILE_ID, fs_attr, TRUE)) { error_returned(" - hfs_make_blockmap"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3); if (result != 0) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: Extended attributes failed to load for the Allocation file.\n"); tsk_error_reset(); } fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** * \internal * Create an FS_INODE structure for the startup / boot file. * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_startfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; unsigned char dummy1, dummy2; uint64_t dummy3; uint8_t result; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_startfile: Making virtual startup file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_startfile"); return 1; } fs_file->meta->addr = HFS_STARTUP_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_STARTUPNAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz); if (((attr_run = hfs_extents_to_attr(fs, hfs->fs->start_file.extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_make_startfile"); return 1; } if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_startfile"); tsk_fs_attr_run_free(attr_run); return 1; } // initialize the data run if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->start_file.logic_sz), 0, 0)) { error_returned(" - hfs_make_startfile"); tsk_fs_attr_run_free(attr_run); return 1; } // see if catalog file has additional runs if (hfs_ext_find_extent_record_attr(hfs, HFS_STARTUP_FILE_ID, fs_attr, TRUE)) { error_returned(" - hfs_make_startfile"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3); if (result != 0) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: Extended attributes failed to load for the Start file.\n"); tsk_error_reset(); } fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** * \internal * Create an FS_INODE structure for the attributes file. * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_attrfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs = (TSK_FS_INFO *) hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_attrfile: Making virtual attributes file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_attrfile"); return 1; } fs_file->meta->addr = HFS_ATTRIBUTES_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_ATTRIBUTESNAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz); if (((attr_run = hfs_extents_to_attr(fs, hfs->fs->attr_file.extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_make_attrfile"); return 1; } if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_attrfile"); tsk_fs_attr_run_free(attr_run); return 1; } // initialize the data run if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz), tsk_getu64(fs->endian, hfs->fs->attr_file.logic_sz), 0, 0)) { error_returned(" - hfs_make_attrfile"); tsk_fs_attr_run_free(attr_run); return 1; } // see if catalog file has additional runs if (hfs_ext_find_extent_record_attr(hfs, HFS_ATTRIBUTES_FILE_ID, fs_attr, TRUE)) { error_returned(" - hfs_make_attrfile"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } //hfs_load_extended_attrs(fs_file); fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** * \internal * Create an FS_FILE structure for the BadBlocks file. * * @param hfs File system to analyze * @param fs_file Structure to copy file information into. * @return 1 on error and 0 on success */ static uint8_t hfs_make_badblockfile(HFS_INFO * hfs, TSK_FS_FILE * fs_file) { TSK_FS_ATTR *fs_attr; unsigned char dummy1, dummy2; uint64_t dummy3; uint8_t result; if (tsk_verbose) tsk_fprintf(stderr, "hfs_make_badblockfile: Making virtual badblock file\n"); if (hfs_make_specialbase(fs_file)) { error_returned(" - hfs_make_badblockfile"); return 1; } fs_file->meta->addr = HFS_BAD_BLOCK_FILE_ID; strncpy(fs_file->meta->name2->name, HFS_BAD_BLOCK_FILE_NAME, TSK_FS_META_NAME_LIST_NSIZE); fs_file->meta->size = 0; if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_make_badblockfile"); return 1; } // add the run to the file. if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, NULL, TSK_FS_ATTR_TYPE_DEFAULT, HFS_FS_ATTR_ID_DATA, fs_file->meta->size, fs_file->meta->size, fs_file->meta->size, 0, 0)) { error_returned(" - hfs_make_badblockfile"); return 1; } // see if file has additional runs if (hfs_ext_find_extent_record_attr(hfs, HFS_BAD_BLOCK_FILE_ID, fs_attr, TRUE)) { error_returned(" - hfs_make_badblockfile"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } /* @@@ We have a chicken and egg problem here... The current design of * fs_attr_set() requires the size to be set, but we dont' know the size * until we look into the extents file (which adds to an attribute...). * This does not seem to be the best design... neeed a way to test this. */ fs_file->meta->size = fs_attr->nrd.initsize; fs_attr->size = fs_file->meta->size; fs_attr->nrd.allocsize = fs_file->meta->size; result = hfs_load_extended_attrs(fs_file, &dummy1, &dummy2, &dummy3); if (result != 0) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: Extended attributes failed to load for the BadBlocks file.\n"); tsk_error_reset(); } fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** \internal * Copy the catalog file or folder record entry into a TSK data structure. * @param a_hfs File system being analyzed * @param a_hfs_entry Catalog record entry (HFS_ENTRY *) * @param a_fs_file Structure to copy data into (TSK_FS_FILE *) * Returns 1 on error. */ static uint8_t hfs_dinode_copy(HFS_INFO * a_hfs, const HFS_ENTRY * a_hfs_entry, TSK_FS_FILE * a_fs_file) { // Note, a_hfs_entry->cat is really of type hfs_file. But, hfs_file_folder is a union // of that type with hfs_folder. Both of hfs_file and hfs_folder have the same first member. // So, this cast is appropriate. const hfs_file_folder *a_entry = (hfs_file_folder *) & (a_hfs_entry->cat); const hfs_file_fold_std *std; TSK_FS_META *a_fs_meta = a_fs_file->meta; TSK_FS_INFO *fs; uint16_t hfsmode; TSK_INUM_T iStd; // the inum (or CNID) that occurs in the standard file metadata if (a_entry == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_dinode_copy: a_entry = a_hfs_entry->cat is NULL"); return 1; } fs = (TSK_FS_INFO *) & a_hfs->fs_info; // Just a sanity check. The inum (or cnid) occurs in two places in the // entry data structure. iStd = tsk_getu32(fs->endian, a_entry->file.std.cnid); if (iStd != a_hfs_entry->inum) { if (tsk_verbose) tsk_fprintf(stderr, "WARNING: hfs_dinode_copy: HFS_ENTRY with conflicting values for inum (or cnid).\n"); } if (a_fs_meta == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("hfs_dinode_copy: a_fs_meta is NULL"); return 1; } // both files and folders start off the same std = &(a_entry->file.std); if (tsk_verbose) tsk_fprintf(stderr, "hfs_dinode_copy: called for file/folder %" PRIu32 "\n", tsk_getu32(fs->endian, std->cnid)); if (a_fs_meta->content_len < HFS_FILE_CONTENT_LEN) { if ((a_fs_meta = tsk_fs_meta_realloc(a_fs_meta, HFS_FILE_CONTENT_LEN)) == NULL) { return 1; } } a_fs_meta->attr_state = TSK_FS_META_ATTR_EMPTY; if (a_fs_meta->attr) { tsk_fs_attrlist_markunused(a_fs_meta->attr); } /* * Copy the file type specific stuff first */ hfsmode = tsk_getu16(fs->endian, std->perm.mode); if (tsk_getu16(fs->endian, std->rec_type) == HFS_FOLDER_RECORD) { // set the type of mode is not set if ((hfsmode & HFS_IN_IFMT) == 0) a_fs_meta->type = TSK_FS_META_TYPE_DIR; a_fs_meta->size = 0; memset(a_fs_meta->content_ptr, 0, HFS_FILE_CONTENT_LEN); } else if (tsk_getu16(fs->endian, std->rec_type) == HFS_FILE_RECORD) { hfs_fork *fork; // set the type of mode is not set if ((hfsmode & HFS_IN_IFMT) == 0) a_fs_meta->type = TSK_FS_META_TYPE_REG; a_fs_meta->size = tsk_getu64(fs->endian, a_entry->file.data.logic_sz); // copy the data and resource forks fork = (hfs_fork *) a_fs_meta->content_ptr; memcpy(fork, &(a_entry->file.data), sizeof(hfs_fork)); memcpy(&fork[1], &(a_entry->file.resource), sizeof(hfs_fork)); } else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_dinode_copy error: catalog entry is neither file nor folder\n"); return 1; } /* * Copy the standard stuff. * Use default values (as defined in spec) if mode is not defined. */ if ((hfsmode & HFS_IN_IFMT) == 0) { a_fs_meta->mode = 0; a_fs_meta->uid = 99; a_fs_meta->gid = 99; } else { a_fs_meta->mode = hfs_mode_to_tsk_mode(hfsmode); a_fs_meta->type = hfs_mode_to_tsk_meta_type(hfsmode); a_fs_meta->uid = tsk_getu32(fs->endian, std->perm.owner); a_fs_meta->gid = tsk_getu32(fs->endian, std->perm.group); } // this field is set only for "indirect" entries if (tsk_getu32(fs->endian, std->perm.special.nlink)) a_fs_meta->nlink = tsk_getu32(fs->endian, std->perm.special.nlink); else a_fs_meta->nlink = 1; a_fs_meta->mtime = hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->cmtime)); a_fs_meta->atime = hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->atime)); a_fs_meta->crtime = hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->crtime)); a_fs_meta->ctime = hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->amtime)); a_fs_meta->time2.hfs.bkup_time = hfs_convert_2_unix_time(tsk_getu32(fs->endian, std->bkup_date)); a_fs_meta->mtime_nano = a_fs_meta->atime_nano = a_fs_meta->ctime_nano = a_fs_meta->crtime_nano = 0; a_fs_meta->time2.hfs.bkup_time_nano = 0; a_fs_meta->addr = tsk_getu32(fs->endian, std->cnid); // All entries here are used. a_fs_meta->flags = TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_USED; if (std->perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) a_fs_meta->flags |= TSK_FS_META_FLAG_COMP; // We copy this inum (or cnid) here, because this file *might* have been a hard link. In // that case, we want to make sure that a_fs_file points consistently to the target of the // link. if (a_fs_file->name != NULL) { a_fs_file->name->meta_addr = a_fs_meta->addr; } /* TODO @@@ could fill in name2 with this entry's name and parent inode from Catalog entry */ /* set the link string (if the file is a link) * The size check is a sanity check so that we don't try to allocate * a huge amount of memory for a bad inode value */ if ((a_fs_meta->type == TSK_FS_META_TYPE_LNK) && (a_fs_meta->size >= 0) && (a_fs_meta->size < HFS_MAXPATHLEN)) { ssize_t bytes_read; a_fs_meta->link = tsk_malloc((size_t) a_fs_meta->size + 1); if (a_fs_meta->link == NULL) return 1; bytes_read = tsk_fs_file_read(a_fs_file, (TSK_OFF_T) 0, a_fs_meta->link, (size_t) a_fs_meta->size, TSK_FS_FILE_READ_FLAG_NONE); a_fs_meta->link[a_fs_meta->size] = '\0'; if (bytes_read != a_fs_meta->size) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_dinode_copy: failed to read contents of symbolic link; " "expected %u bytes but tsk_fs_file_read() returned %u\n", a_fs_meta->size, bytes_read); free(a_fs_meta->link); a_fs_meta->link = NULL; return 1; } } return 0; } /** \internal * Load a catalog file entry and save it in the TSK_FS_FILE structure. * * @param fs File system to read from. * @param a_fs_file Structure to read into. * @param inum File address to load * @returns 1 on error */ static uint8_t hfs_inode_lookup(TSK_FS_INFO * fs, TSK_FS_FILE * a_fs_file, TSK_INUM_T inum) { HFS_INFO *hfs = (HFS_INFO *) fs; HFS_ENTRY entry; if (a_fs_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("hfs_inode_lookup: fs_file is NULL"); return 1; } if (a_fs_file->meta == NULL) { a_fs_file->meta = tsk_fs_meta_alloc(HFS_FILE_CONTENT_LEN); } if (a_fs_file->meta == NULL) { return 1; } else { tsk_fs_meta_reset(a_fs_file->meta); } if (tsk_verbose) tsk_fprintf(stderr, "hfs_inode_lookup: looking up %" PRIuINUM "\n", inum); // @@@ Will need to add orphan stuff here too /* First see if this is a special entry * the special ones have their metadata stored in the volume header */ if (inum == HFS_EXTENTS_FILE_ID) { if (!hfs->has_extents_file) { error_detected(TSK_ERR_FS_INODE_NUM, "Extents File not present"); return 1; } return hfs_make_extents(hfs, a_fs_file); } else if (inum == HFS_CATALOG_FILE_ID) { return hfs_make_catalog(hfs, a_fs_file); } else if (inum == HFS_BAD_BLOCK_FILE_ID) { // Note: the Extents file and the BadBlocks file are really the same. if (!hfs->has_extents_file) { error_detected(TSK_ERR_FS_INODE_NUM, "BadBlocks File not present"); return 1; } return hfs_make_badblockfile(hfs, a_fs_file); } else if (inum == HFS_ALLOCATION_FILE_ID) { return hfs_make_blockmap(hfs, a_fs_file); } else if (inum == HFS_STARTUP_FILE_ID) { if (!hfs->has_startup_file) { error_detected(TSK_ERR_FS_INODE_NUM, "Startup File not present"); return 1; } return hfs_make_startfile(hfs, a_fs_file); } else if (inum == HFS_ATTRIBUTES_FILE_ID) { if (!hfs->has_attributes_file) { error_detected(TSK_ERR_FS_INODE_NUM, "Attributes File not present"); return 1; } return hfs_make_attrfile(hfs, a_fs_file); } /* Lookup inode and store it in the HFS structure */ if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE)) { return 1; } /* Copy the structure in hfs to generic fs_inode */ if (hfs_dinode_copy(hfs, &entry, a_fs_file)) { return 1; } /* If this is potentially a compressed file, its * actual size is unknown until we examine the * extended attributes */ if ((a_fs_file->meta->size == 0) && (a_fs_file->meta->type == TSK_FS_META_TYPE_REG) && (a_fs_file->meta->attr_state != TSK_FS_META_ATTR_ERROR) && ((a_fs_file->meta->attr_state != TSK_FS_META_ATTR_STUDIED) || (a_fs_file->meta->attr == NULL))) { hfs_load_attrs(a_fs_file); } return 0; } typedef struct { uint32_t offset; uint32_t length; } CMP_OFFSET_ENTRY; static int hfs_read_zlib_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) { int attrReadResult; hfs_resource_fork_header rfHeader; uint32_t dataOffset; uint32_t offsetTableOffset; char fourBytes[4]; // Size of the offset table, little endian uint32_t tableSize; // Size of the offset table char *offsetTableData = NULL; CMP_OFFSET_ENTRY *offsetTable = NULL; size_t indx; // Read the resource fork header attrReadResult = tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader, sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != sizeof(hfs_resource_fork_header)) { error_returned (" %s: trying to read the resource fork header", __func__); return 0; } // Begin to parse the resource fork. For now, we just need the data offset. dataOffset = tsk_getu32(TSK_BIG_ENDIAN, rfHeader.dataOffset); // The resource's data begins with an offset table, which defines blocks // of (optionally) zlib-compressed data (so that the OS can do file seeks // efficiently; each uncompressed block is 64KB). offsetTableOffset = dataOffset + 4; // read 4 bytes, the number of table entries, little endian attrReadResult = tsk_fs_attr_read(rAttr, offsetTableOffset, fourBytes, 4, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != 4) { error_returned (" %s: trying to read the offset table size, " "return value of %u should have been 4", __func__, attrReadResult); return 0; } tableSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes); // Each table entry is 8 bytes long offsetTableData = tsk_malloc(tableSize * 8); if (offsetTableData == NULL) { error_returned (" %s: space for the offset table raw data", __func__); return 0; } offsetTable = (CMP_OFFSET_ENTRY *) tsk_malloc(tableSize * sizeof(CMP_OFFSET_ENTRY)); if (offsetTable == NULL) { error_returned (" %s: space for the offset table", __func__); goto on_error; } attrReadResult = tsk_fs_attr_read(rAttr, offsetTableOffset + 4, offsetTableData, tableSize * 8, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != tableSize * 8) { error_returned (" %s: reading in the compression offset table, " "return value %u should have been %u", __func__, attrReadResult, tableSize * 8); goto on_error; } for (indx = 0; indx < tableSize; ++indx) { offsetTable[indx].offset = tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8); offsetTable[indx].length = tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + indx * 8 + 4); } free(offsetTableData); *offsetTableOut = offsetTable; *tableSizeOut = tableSize; *tableOffsetOut = offsetTableOffset; return 1; on_error: free(offsetTable); free(offsetTableData); return 0; } static int hfs_read_lzvn_block_table(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut) { int attrReadResult; char fourBytes[4]; uint32_t tableDataSize; uint32_t tableSize; // Size of the offset table char *offsetTableData = NULL; CMP_OFFSET_ENTRY *offsetTable = NULL; // The offset table is a sequence of 4-byte offsets of compressed // blocks. The first 4 bytes is thus the offset of the first block, // but also 4 times the number of entries in the table. attrReadResult = tsk_fs_attr_read(rAttr, 0, fourBytes, 4, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != 4) { error_returned (" %s: trying to read the offset table size, " "return value of %u should have been 4", __func__, attrReadResult); return 0; } tableDataSize = tsk_getu32(TSK_LIT_ENDIAN, fourBytes); offsetTableData = tsk_malloc(tableDataSize); if (offsetTableData == NULL) { error_returned (" %s: space for the offset table raw data", __func__); return 0; } // table entries are 4 bytes, last entry is end of data tableSize = tableDataSize / 4 - 1; offsetTable = (CMP_OFFSET_ENTRY *) tsk_malloc(tableSize * sizeof(CMP_OFFSET_ENTRY)); if (offsetTable == NULL) { error_returned (" %s: space for the offset table", __func__); goto on_error; } attrReadResult = tsk_fs_attr_read(rAttr, 0, offsetTableData, tableDataSize, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != tableDataSize) { error_returned (" %s: reading in the compression offset table, " "return value %u should have been %u", __func__, attrReadResult, tableDataSize); goto on_error; } uint32_t a = tableDataSize; uint32_t b; size_t i; for (i = 0; i < tableSize; ++i) { b = tsk_getu32(TSK_LIT_ENDIAN, offsetTableData + 4*(i+1)); offsetTable[i].offset = a; offsetTable[i].length = b - a; a = b; } free(offsetTableData); *offsetTableOut = offsetTable; *tableSizeOut = tableSize; *tableOffsetOut = 0; return 1; on_error: free(offsetTable); free(offsetTableData); return 0; } static int hfs_decompress_noncompressed_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) { // actually an uncompressed block of data; just copy if (tsk_verbose) tsk_fprintf(stderr, "%s: Copying an uncompressed compression unit\n", __func__); if ((len - 1) > COMPRESSION_UNIT_SIZE) { error_detected(TSK_ERR_FS_READ, "%s: uncompressed block length %u is longer " "than compression unit size %u", __func__, len - 1, COMPRESSION_UNIT_SIZE); return 0; } memcpy(uncBuf, rawBuf + 1, len - 1); *uncLen = len - 1; return 1; } #ifdef HAVE_LIBZ static int hfs_decompress_zlib_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) { // see if this block is compressed if (len > 0 && (rawBuf[0] & 0x0F) != 0x0F) { // Uncompress the chunk of data if (tsk_verbose) tsk_fprintf(stderr, "%s: Inflating the compression unit\n", __func__); unsigned long bytesConsumed; int infResult = zlib_inflate(rawBuf, (uint64_t) len, uncBuf, (uint64_t) COMPRESSION_UNIT_SIZE, uncLen, &bytesConsumed); if (infResult != 0) { error_returned (" %s: zlib inflation (uncompression) failed", __func__, infResult); return 0; } if (bytesConsumed != len) { error_detected(TSK_ERR_FS_READ, " %s, decompressor did not consume the whole compressed data", __func__); return 0; } return 1; } else { // actually an uncompressed block of data; just copy return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen); } } #endif static int hfs_decompress_lzvn_block(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) { // see if this block is compressed if (len > 0 && rawBuf[0] != 0x06) { *uncLen = lzvn_decode_buffer(uncBuf, COMPRESSION_UNIT_SIZE, rawBuf, len); return 1; // apparently this can't fail } else { // actually an uncompressed block of data; just copy return hfs_decompress_noncompressed_block(rawBuf, len, uncBuf, uncLen); } } static ssize_t read_and_decompress_block( const TSK_FS_ATTR* rAttr, char* rawBuf, char* uncBuf, const CMP_OFFSET_ENTRY* offsetTable, uint32_t offsetTableSize, uint32_t offsetTableOffset, size_t indx, int (*decompress_block)(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen) ) { int attrReadResult; uint32_t offset = offsetTableOffset + offsetTable[indx].offset; uint32_t len = offsetTable[indx].length; uint64_t uncLen; if (tsk_verbose) tsk_fprintf(stderr, "%s: Reading compression unit %d, length %d\n", __func__, indx, len); /* Github #383 referenced that if len is 0, then the below code causes * problems. Added this check, but I don't have data to verify this on. * it looks like it should at least not crash, but it isn't clear if it * will also do the right thing and if should actually break here * instead. */ if (len == 0) { return 0; } if (len > COMPRESSION_UNIT_SIZE + 1) { error_detected(TSK_ERR_FS_READ, "%s: block size is too large: %u", __func__, len); return -1; } // Read in the block of compressed data attrReadResult = tsk_fs_attr_read(rAttr, offset, rawBuf, len, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult != len) { char msg[] = "%s%s: reading in the compression offset table, " "return value %u should have been %u"; if (attrReadResult < 0 ) { error_returned(msg, " ", __func__, attrReadResult, len); } else { error_detected(TSK_ERR_FS_READ, "", __func__, attrReadResult, len); } return -1; } if (!decompress_block(rawBuf, len, uncBuf, &uncLen)) { return -1; } // If size is a multiple of COMPRESSION_UNIT_SIZE, // expected uncompressed length is COMPRESSION_UNIT_SIZE const uint32_t expUncLen = indx == offsetTableSize - 1 ? ((rAttr->fs_file->meta->size - 1) % COMPRESSION_UNIT_SIZE) + 1 : COMPRESSION_UNIT_SIZE; if (uncLen != expUncLen) { error_detected(TSK_ERR_FS_READ, "%s: compressed block decompressed to %u bytes, " "should have been %u bytes", __func__, uncLen, expUncLen); return -1; } // There are now uncLen bytes of uncompressed data available from // this comp unit. return (ssize_t)uncLen; } static uint8_t hfs_attr_walk_compressed_rsrc(const TSK_FS_ATTR * fs_attr, int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr, int (*read_block_table)(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut), int (*decompress_block)(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)) { TSK_FS_INFO *fs; TSK_FS_FILE *fs_file; const TSK_FS_ATTR *rAttr; // resource fork attribute char *rawBuf = NULL; // compressed data char *uncBuf = NULL; // uncompressed data uint32_t offsetTableOffset; uint32_t offsetTableSize; // The number of table entries CMP_OFFSET_ENTRY *offsetTable = NULL; size_t indx; // index for looping over the offset table TSK_OFF_T off = 0; // the offset in the uncompressed data stream consumed thus far if (tsk_verbose) tsk_fprintf(stderr, "%s: Entered, because this is a compressed file with compressed data in the resource fork\n", __func__); // clean up any error messages that are lying around tsk_error_reset(); if ((fs_attr == NULL) || (fs_attr->fs_file == NULL) || (fs_attr->fs_file->meta == NULL) || (fs_attr->fs_file->fs_info == NULL)) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("%s: Null arguments given\n", __func__); return 1; } // Check that the ATTR being read is the main DATA resource, 128-0, // because this is the only one that can be compressed in HFS+ if ((fs_attr->id != HFS_FS_ATTR_ID_DATA) || (fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) { error_detected(TSK_ERR_FS_ARG, "%s: arg specified an attribute %u-%u that is not the data fork, " "Only the data fork can be compressed.", __func__, fs_attr->type, fs_attr->id); return 1; } /* This MUST be a compressed attribute */ if (!(fs_attr->flags & TSK_FS_ATTR_COMP)) { error_detected(TSK_ERR_FS_FWALK, "%s: called with non-special attribute: %x", __func__, fs_attr->flags); return 1; } fs = fs_attr->fs_file->fs_info; fs_file = fs_attr->fs_file; /******** Open the Resource Fork ***********/ // find the attribute for the resource fork rAttr = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC, TRUE); if (rAttr == NULL) { error_returned (" %s: could not get the attribute for the resource fork of the file", __func__); return 1; } // read the offset table from the fork header if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) { return 1; } // Allocate two buffers for the raw and uncompressed data /* Raw data can be COMPRESSION_UNIT_SIZE+1 if the data is not * compressed and there is a 1-byte flag that indicates that * the data is not compressed. */ rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1); if (rawBuf == NULL) { error_returned (" %s: buffers for reading and uncompressing", __func__); goto on_error; } uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE); if (uncBuf == NULL) { error_returned (" %s: buffers for reading and uncompressing", __func__); goto on_error; } // FOR entry in the table DO for (indx = 0; indx < offsetTableSize; ++indx) { ssize_t uncLen; // uncompressed length unsigned int blockSize; uint64_t lumpSize; uint64_t remaining; char *lumpStart; switch ((uncLen = read_and_decompress_block( rAttr, rawBuf, uncBuf, offsetTable, offsetTableSize, offsetTableOffset, indx, decompress_block))) { case -1: goto on_error; case 0: continue; default: break; } // Call the a_action callback with "Lumps" // that are at most the block size. blockSize = fs->block_size; remaining = uncLen; lumpStart = uncBuf; while (remaining > 0) { int retval; // action return value lumpSize = remaining <= blockSize ? remaining : blockSize; // Apply the callback function if (tsk_verbose) tsk_fprintf(stderr, "%s: Calling action on lump of size %" PRIu64 " offset %" PRIu64 " in the compression unit\n", __func__, lumpSize, uncLen - remaining); if (lumpSize > SIZE_MAX) { error_detected(TSK_ERR_FS_FWALK, " %s: lumpSize is too large for the action", __func__); goto on_error; } retval = a_action(fs_attr->fs_file, off, 0, lumpStart, (size_t) lumpSize, // cast OK because of above test TSK_FS_BLOCK_FLAG_COMP, ptr); if (retval == TSK_WALK_ERROR) { error_detected(TSK_ERR_FS | 201, "%s: callback returned an error", __func__); goto on_error; } else if (retval == TSK_WALK_STOP) { break; } // Find the next lump off += lumpSize; remaining -= lumpSize; lumpStart += lumpSize; } } // Done, so free up the allocated resources. free(offsetTable); free(rawBuf); free(uncBuf); return 0; on_error: free(offsetTable); free(rawBuf); free(uncBuf); return 0; } #ifdef HAVE_LIBZ static uint8_t hfs_attr_walk_zlib_rsrc(const TSK_FS_ATTR * fs_attr, int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr) { return hfs_attr_walk_compressed_rsrc( fs_attr, flags, a_action, ptr, hfs_read_zlib_block_table, hfs_decompress_zlib_block ); } #endif static uint8_t hfs_attr_walk_lzvn_rsrc(const TSK_FS_ATTR * fs_attr, int flags, TSK_FS_FILE_WALK_CB a_action, void *ptr) { return hfs_attr_walk_compressed_rsrc( fs_attr, flags, a_action, ptr, hfs_read_lzvn_block_table, hfs_decompress_lzvn_block ); } /** \internal * * @returns number of bytes read or -1 on error (incl if offset is past EOF) */ static ssize_t hfs_file_read_compressed_rsrc(const TSK_FS_ATTR * a_fs_attr, TSK_OFF_T a_offset, char *a_buf, size_t a_len, int (*read_block_table)(const TSK_FS_ATTR *rAttr, CMP_OFFSET_ENTRY** offsetTableOut, uint32_t* tableSizeOut, uint32_t* tableOffsetOut), int (*decompress_block)(char* rawBuf, uint32_t len, char* uncBuf, uint64_t* uncLen)) { TSK_FS_FILE *fs_file; const TSK_FS_ATTR *rAttr; char *rawBuf = NULL; char *uncBuf = NULL; uint32_t offsetTableOffset; uint32_t offsetTableSize; // Size of the offset table CMP_OFFSET_ENTRY *offsetTable = NULL; size_t indx; // index for looping over the offset table uint32_t startUnit = 0; uint32_t startUnitOffset = 0; uint32_t endUnit = 0; uint64_t bytesCopied; if (tsk_verbose) tsk_fprintf(stderr, "%s: called because this file is compressed, with data in the resource fork\n", __func__); // Reading zero bytes? OK at any offset, I say! if (a_len == 0) return 0; if (a_offset < 0) { error_detected(TSK_ERR_FS_ARG, "%s: reading from file at a negative offset, or negative length", __func__); return -1; } if (a_len > SIZE_MAX / 2) { error_detected(TSK_ERR_FS_ARG, "%s: trying to read more than SIZE_MAX/2 is not supported.", __func__); return -1; } if ((a_fs_attr == NULL) || (a_fs_attr->fs_file == NULL) || (a_fs_attr->fs_file->meta == NULL) || (a_fs_attr->fs_file->fs_info == NULL)) { error_detected(TSK_ERR_FS_ARG, "%s: NULL parameters passed", __func__); return -1; } // This should be a compressed file. If not, that's an error! if (!(a_fs_attr->flags & TSK_FS_ATTR_COMP)) { error_detected(TSK_ERR_FS_ARG, "%s: called with non-special attribute: %x", __func__, a_fs_attr->flags); return -1; } // Check that the ATTR being read is the main DATA resource, 4352-0, // because this is the only one that can be compressed in HFS+ if ((a_fs_attr->id != HFS_FS_ATTR_ID_DATA) || (a_fs_attr->type != TSK_FS_ATTR_TYPE_HFS_DATA)) { error_detected(TSK_ERR_FS_ARG, "%s: arg specified an attribute %u-%u that is not the data fork, " "Only the data fork can be compressed.", __func__, a_fs_attr->type, a_fs_attr->id); return -1; } /******** Open the Resource Fork ***********/ // The file fs_file = a_fs_attr->fs_file; // find the attribute for the resource fork rAttr = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC, TRUE); if (rAttr == NULL) { error_returned (" %s: could not get the attribute for the resource fork of the file", __func__); return -1; } // read the offset table from the fork header if (!read_block_table(rAttr, &offsetTable, &offsetTableSize, &offsetTableOffset)) { return -1; } // Compute the range of compression units needed for the request startUnit = a_offset / COMPRESSION_UNIT_SIZE; startUnitOffset = a_offset % COMPRESSION_UNIT_SIZE; endUnit = (a_offset + a_len - 1) / COMPRESSION_UNIT_SIZE; if (startUnit >= offsetTableSize || endUnit >= offsetTableSize) { error_detected(TSK_ERR_FS_ARG, "%s: range of bytes requested %lld - %lld falls past the " "end of the uncompressed stream %llu\n", __func__, a_offset, a_offset + a_len, offsetTable[offsetTableSize-1].offset + offsetTable[offsetTableSize-1].length); goto on_error; } if (tsk_verbose) tsk_fprintf(stderr, "%s: reading compression units: %" PRIu32 " to %" PRIu32 "\n", __func__, startUnit, endUnit); bytesCopied = 0; // Allocate buffers for the raw and uncompressed data /* Raw data can be COMPRESSION_UNIT_SIZE+1 if the zlib data is not * compressed and there is a 1-byte flag that indicates that * the data is not compressed. */ rawBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE + 1); if (rawBuf == NULL) { error_returned (" %s: buffers for reading and uncompressing", __func__); goto on_error; } uncBuf = (char *) tsk_malloc(COMPRESSION_UNIT_SIZE); if (uncBuf == NULL) { error_returned (" %s: buffers for reading and uncompressing", __func__); goto on_error; } // Read from the indicated comp units for (indx = startUnit; indx <= endUnit; ++indx) { uint64_t uncLen; char *uncBufPtr = uncBuf; size_t bytesToCopy; switch ((uncLen = read_and_decompress_block( rAttr, rawBuf, uncBuf, offsetTable, offsetTableSize, offsetTableOffset, indx, decompress_block))) { case -1: goto on_error; case 0: continue; default: break; } // If this is the first comp unit, then we must skip over the // startUnitOffset bytes. if (indx == startUnit) { uncLen -= startUnitOffset; uncBufPtr += startUnitOffset; } // How many bytes to copy from this compression unit? if (bytesCopied + uncLen < (uint64_t) a_len) // cast OK because a_len > 0 bytesToCopy = (size_t) uncLen; // uncLen <= size of compression unit, which is small, so cast is OK else bytesToCopy = (size_t) (((uint64_t) a_len) - bytesCopied); // diff <= compression unit size, so cast is OK // Copy into the output buffer, and update bookkeeping. memcpy(a_buf + bytesCopied, uncBufPtr, bytesToCopy); bytesCopied += bytesToCopy; } // Well, we don't know (without a lot of work) what the // true uncompressed size of the stream is. All we know is the "upper bound" which // assumes that all of the compression units expand to their full size. If we did // know the true size, then we could reject requests that go beyond the end of the // stream. Instead, we treat the stream as if it is padded out to the full size of // the last compression unit with zeros. // Have we read and copied all of the bytes requested? if (bytesCopied < a_len) { // set the remaining bytes to zero memset(a_buf + bytesCopied, 0, a_len - (size_t) bytesCopied); // cast OK because diff must be < compression unit size } free(offsetTable); free(rawBuf); free(uncBuf); return (ssize_t) bytesCopied; // cast OK, cannot be greater than a_len which cannot be greater than SIZE_MAX/2 (rounded down). on_error: free(offsetTable); free(rawBuf); free(uncBuf); return -1; } #ifdef HAVE_LIBZ static ssize_t hfs_file_read_zlib_rsrc(const TSK_FS_ATTR * a_fs_attr, TSK_OFF_T a_offset, char *a_buf, size_t a_len) { return hfs_file_read_compressed_rsrc( a_fs_attr, a_offset, a_buf, a_len, hfs_read_zlib_block_table, hfs_decompress_zlib_block ); } #endif static ssize_t hfs_file_read_lzvn_rsrc(const TSK_FS_ATTR * a_fs_attr, TSK_OFF_T a_offset, char *a_buf, size_t a_len) { return hfs_file_read_compressed_rsrc( a_fs_attr, a_offset, a_buf, a_len, hfs_read_lzvn_block_table, hfs_decompress_lzvn_block ); } static int hfs_decompress_noncompressed_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) { if (tsk_verbose) tsk_fprintf(stderr, "%s: Leading byte, 0x%02x, indicates that the data is not really compressed.\n" "%s: Loading the default DATA attribute.", __func__, rawBuf[0], __func__); *dstBuf = rawBuf + 1; // + 1 indicator byte *dstSize = uncSize; *dstBufFree = FALSE; return 1; } static int hfs_decompress_zlib_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) { if ((rawBuf[0] & 0x0F) == 0x0F) { return hfs_decompress_noncompressed_attr( rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree); } else { #ifdef HAVE_LIBZ char* uncBuf = NULL; uint64_t uLen; unsigned long bytesConsumed; int infResult; if (tsk_verbose) tsk_fprintf(stderr, "%s: Uncompressing (inflating) data.", __func__); // Uncompress the remainder of the attribute, and load as 128-0 // Note: cast is OK because uncSize will be quite modest, < 4000. uncBuf = (char *) tsk_malloc((size_t) uncSize + 100); // add some extra space if (uncBuf == NULL) { error_returned (" - %s, space for the uncompressed attr", __func__); return 0; } infResult = zlib_inflate(rawBuf, (uint64_t) rawSize, uncBuf, (uint64_t) (uncSize + 100), &uLen, &bytesConsumed); if (infResult != 0) { error_returned (" %s, zlib could not uncompress attr", __func__); free(uncBuf); return 0; } if (bytesConsumed != rawSize) { error_detected(TSK_ERR_FS_READ, " %s, decompressor did not consume the whole compressed data", __func__); free(uncBuf); return 0; } *dstBuf = uncBuf; *dstSize = uncSize; *dstBufFree = TRUE; #else // ZLIB compression library is not available, so we will load a // zero-length default DATA attribute. Without this, icat may // misbehave. if (tsk_verbose) tsk_fprintf(stderr, "%s: ZLIB not available, so loading an empty default DATA attribute.\n", __func__); // Dummy is one byte long, so the ptr is not null, but we set the // length to zero bytes, so it is never read. static uint8_t dummy[1]; *dstBuf = dummy; *dstSize = 0; *dstBufFree = FALSE; #endif } return 1; } static int hfs_decompress_lzvn_attr(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree) { if (rawBuf[0] == 0x06) { return hfs_decompress_noncompressed_attr( rawBuf, rawSize, uncSize, dstBuf, dstSize, dstBufFree); } char* uncBuf = (char *) tsk_malloc((size_t) uncSize); *dstSize = lzvn_decode_buffer(uncBuf, uncSize, rawBuf, rawSize); *dstBuf = uncBuf; *dstBufFree = TRUE; return 1; } static int hfs_file_read_compressed_attr(TSK_FS_FILE* fs_file, uint8_t cmpType, char* buffer, uint32_t attributeLength, uint64_t uncSize, int (*decompress_attr)(char* rawBuf, uint32_t rawSize, uint64_t uncSize, char** dstBuf, uint64_t* dstSize, int* dstBufFree)) { // Data is inline. We will load the uncompressed data as a // resident attribute. if (tsk_verbose) tsk_fprintf(stderr, "%s: Compressed data is inline in the attribute, will load this as the default DATA attribute.\n", __func__); if (attributeLength <= 16) { if (tsk_verbose) tsk_fprintf(stderr, "%s: WARNING, Compression Record of type %u is not followed by" " compressed data. No data will be loaded into the DATA" " attribute.\n", __func__, cmpType); // oddly, this is not actually considered an error return 1; } TSK_FS_ATTR *fs_attr_unc; // There is data following the compression record, as there should be. if ((fs_attr_unc = tsk_fs_attrlist_getnew( fs_file->meta->attr, TSK_FS_ATTR_RES)) == NULL) { error_returned(" - %s, FS_ATTR for uncompressed data", __func__); return 0; } char* dstBuf; uint64_t dstSize; int dstBufFree = FALSE; if (!decompress_attr(buffer + 16, attributeLength - 16, uncSize, &dstBuf, &dstSize, &dstBufFree)) { return 0; } if (dstSize != uncSize) { error_detected(TSK_ERR_FS_READ, " %s, actual uncompressed size not equal to the size in the compression record", __func__); goto on_error; } if (tsk_verbose) tsk_fprintf(stderr, "%s: Loading decompressed data as default DATA attribute.", __func__); // Load the remainder of the attribute as 128-0 // set the details in the fs_attr structure. // Note, we are loading this as a RESIDENT attribute. if (tsk_fs_attr_set_str(fs_file, fs_attr_unc, "DATA", TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, dstBuf, dstSize)) { error_returned(" - %s", __func__); goto on_error; } if (dstBufFree) { free(dstBuf); } return 1; on_error: if (dstBufFree) { free(dstBuf); } return 0; } static int hfs_file_read_zlib_attr(TSK_FS_FILE* fs_file, char* buffer, uint32_t attributeLength, uint64_t uncSize) { return hfs_file_read_compressed_attr( fs_file, DECMPFS_TYPE_ZLIB_ATTR, buffer, attributeLength, uncSize, hfs_decompress_zlib_attr ); } static int hfs_file_read_lzvn_attr(TSK_FS_FILE* fs_file, char* buffer, uint32_t attributeLength, uint64_t uncSize) { return hfs_file_read_compressed_attr( fs_file, DECMPFS_TYPE_LZVN_ATTR, buffer, attributeLength, uncSize, hfs_decompress_lzvn_attr ); } typedef struct { TSK_FS_INFO *fs; // the HFS file system TSK_FS_FILE *file; // the Attributes file, if open hfs_btree_header_record *header; // the Attributes btree header record. // For Convenience, unpacked values. TSK_ENDIAN_ENUM endian; uint32_t rootNode; uint16_t nodeSize; uint16_t maxKeyLen; } ATTR_FILE_T; /** \internal * Open the Attributes file, and read the btree header record. Fill in the fields of the ATTR_FILE_T struct. * * @param fs -- the HFS file system * @param header -- the header record struct * * @return 1 on error, 0 on success */ static uint8_t open_attr_file(TSK_FS_INFO * fs, ATTR_FILE_T * attr_file) { int cnt; // will hold bytes read hfs_btree_header_record *hrec; // clean up any error messages that are lying around tsk_error_reset(); if (fs == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("open_attr_file: fs is NULL"); return 1; } if (attr_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("open_attr_file: attr_file is NULL"); return 1; } // Open the Attributes File attr_file->file = tsk_fs_file_open_meta(fs, NULL, HFS_ATTRIBUTES_FILE_ID); if (attr_file->file == NULL) { tsk_error_set_errno(TSK_ERR_FS_READ); tsk_error_set_errstr ("open_attr_file: could not open the Attributes file"); return 1; } // Allocate some space for the Attributes btree header record (which // is passed back to the caller) hrec = (hfs_btree_header_record *) malloc(sizeof(hfs_btree_header_record)); if (hrec == NULL) { tsk_error_set_errno(TSK_ERR_FS); tsk_error_set_errstr ("open_attr_file: could not malloc space for Attributes header record"); return 1; } // Read the btree header record cnt = tsk_fs_file_read(attr_file->file, 14, (char *) hrec, sizeof(hfs_btree_header_record), (TSK_FS_FILE_READ_FLAG_ENUM) 0); if (cnt != sizeof(hfs_btree_header_record)) { tsk_error_set_errno(TSK_ERR_FS_READ); tsk_error_set_errstr ("open_attr_file: could not open the Attributes file"); tsk_fs_file_close(attr_file->file); free(hrec); return 1; } // Fill in the fields of the attr_file struct (which was passed in by the caller) attr_file->fs = fs; attr_file->header = hrec; attr_file->endian = fs->endian; attr_file->nodeSize = tsk_getu16(attr_file->endian, hrec->nodesize); attr_file->rootNode = tsk_getu32(attr_file->endian, hrec->rootNode); attr_file->maxKeyLen = tsk_getu16(attr_file->endian, hrec->maxKeyLen); return 0; } /** \internal * Closes and frees the data structures associated with ATTR_FILE_T */ static uint8_t close_attr_file(ATTR_FILE_T * attr_file) { if (attr_file == NULL) { tsk_error_set_errno(TSK_ERR_FS_READ); tsk_error_set_errstr("close_attr_file: NULL attr_file arg"); return 1; } if (attr_file->file != NULL) { tsk_fs_file_close(attr_file->file); attr_file->file = NULL; } if (attr_file->header != NULL) { free(attr_file->header); attr_file->header = NULL; } attr_file->rootNode = 0; attr_file->nodeSize = 0; // Note that we leave the fs component alone. return 0; } static const char * hfs_attrTypeName(uint32_t typeNum) { switch (typeNum) { case TSK_FS_ATTR_TYPE_HFS_DEFAULT: return "DFLT"; case TSK_FS_ATTR_TYPE_HFS_DATA: return "DATA"; case TSK_FS_ATTR_TYPE_HFS_EXT_ATTR: return "ExATTR"; case TSK_FS_ATTR_TYPE_HFS_COMP_REC: return "CMPF"; case TSK_FS_ATTR_TYPE_HFS_RSRC: return "RSRC"; default: return "UNKN"; } } // TODO: Function description missing here no idea what it is supposed to return // in which circumstances. static uint8_t hfs_load_extended_attrs(TSK_FS_FILE * fs_file, unsigned char *isCompressed, unsigned char *cmpType, uint64_t *uncompressedSize) { TSK_FS_INFO *fs = fs_file->fs_info; uint64_t fileID; ATTR_FILE_T attrFile; int cnt; // count of chars read from file. uint8_t *nodeData; TSK_ENDIAN_ENUM endian; hfs_btree_node *nodeDescriptor; // The node descriptor uint32_t nodeID; // The number or ID of the Attributes file node to read. hfs_btree_key_attr *keyB; // ptr to the key of the Attr file record. unsigned char done; // Flag to indicate that we are done looping over leaf nodes uint16_t attribute_counter = 2; // The ID of the next attribute to be loaded. HFS_INFO *hfs; char *buffer = NULL; // buffer to hold the attribute TSK_LIST *nodeIDs_processed = NULL; // Keep track of node IDs to prevent an infinite loop tsk_error_reset(); // The CNID (or inode number) of the file // Note that in TSK such numbers are 64 bits, but in HFS+ they are only 32 bits. fileID = fs_file->meta->addr; if (fs == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_load_extended_attrs: NULL fs arg"); return 1; } hfs = (HFS_INFO *) fs; if (!hfs->has_attributes_file) { // No attributes file, and so, no extended attributes return 0; } if (tsk_verbose) { tsk_fprintf(stderr, "hfs_load_extended_attrs: Processing file %" PRIuINUM "\n", fileID); } // Open the Attributes File if (open_attr_file(fs, &attrFile)) { error_returned ("hfs_load_extended_attrs: could not open Attributes file"); return 1; } // Is the Attributes file empty? if (attrFile.rootNode == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: Attributes file is empty\n"); close_attr_file(&attrFile); *isCompressed = FALSE; *cmpType = 0; return 0; } // A place to hold one node worth of data nodeData = (uint8_t *) malloc(attrFile.nodeSize); if (nodeData == NULL) { error_detected(TSK_ERR_AUX_MALLOC, "hfs_load_extended_attrs: Could not malloc space for an Attributes file node"); goto on_error; } // Initialize these *isCompressed = FALSE; *cmpType = 0; endian = attrFile.fs->endian; // Start with the root node nodeID = attrFile.rootNode; // While loop, over nodes in path from root node to the correct LEAF node. while (1) { uint16_t numRec; // Number of records in the node int recIndx; // index for looping over records if (tsk_verbose) { tsk_fprintf(stderr, "hfs_load_extended_attrs: Reading Attributes File node with ID %" PRIu32 "\n", nodeID); } /* Make sure we do not get into an infinite loop */ if (tsk_list_find(nodeIDs_processed, nodeID)) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Infinite loop detected - trying to read node %" PRIu32 " which has already been processed", nodeID); goto on_error; } /* Read the node */ cnt = tsk_fs_file_read(attrFile.file, (TSK_OFF_T)nodeID * attrFile.nodeSize, (char *) nodeData, attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0); if (cnt != attrFile.nodeSize) { error_returned ("hfs_load_extended_attrs: Could not read in a node from the Attributes File"); goto on_error; } /* Save this node ID to the list of processed nodes */ if (tsk_list_add(&nodeIDs_processed, nodeID)) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Could not save nodeID to the list of processed nodes"); goto on_error; } /** Node has a: * Descriptor * Set of records * Table at the end with pointers to the records */ // Parse the Node header nodeDescriptor = (hfs_btree_node *) nodeData; // If we are at a leaf node, then we have found the right node if (nodeDescriptor->type == HFS_ATTR_NODE_LEAF) { break; } // This had better be an INDEX node, if not its an error else if (nodeDescriptor->type != HFS_ATTR_NODE_INDEX) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Reached a non-INDEX and non-LEAF node in searching the Attributes File"); goto on_error; } // OK, we are in an INDEX node. loop over the records to find the last one whose key is // smaller than or equal to the desired key numRec = tsk_getu16(endian, nodeDescriptor->num_rec); if (numRec == 0) { // This is wrong, there must always be at least 1 record in an INDEX node. error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs:Attributes File index node %" PRIu32 " has zero records", nodeID); goto on_error; } for (recIndx = 0; recIndx < numRec; ++recIndx) { uint16_t keyLength; int comp; // comparison result char *compStr; // comparison result, as a string uint8_t *recData; // pointer to the data part of the record uint32_t keyFileID; // The offset to the record is stored in table at end of node uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry); //uint8_t * nextRecOffsetData = &nodeData[attrFile.nodeSize - 2* (recIndx+2)]; // make sure the record and first fields are in the buffer if (recOffset + 14 > attrFile.nodeSize) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Unable to process attribute (offset too big)"); goto on_error; } // Pointer to first byte of record uint8_t *recordBytes = &nodeData[recOffset]; // Cast that to the Attributes file key (n.b., the key is the first thing in the record) keyB = (hfs_btree_key_attr *) recordBytes; // Is this key less than what we are seeking? //int comp = comp_attr_key(endian, keyB, fileID, attrName, startBlock); keyFileID = tsk_getu32(endian, keyB->file_id); if (keyFileID < fileID) { comp = -1; compStr = "less than"; } else if (keyFileID > fileID) { comp = 1; compStr = "greater than"; } else { comp = 0; compStr = "equal to"; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: INDEX record %d, fileID %" PRIu32 " is %s the file ID we are seeking, %" PRIu32 ".\n", recIndx, keyFileID, compStr, fileID); if (comp > 0) { // The key of this record is greater than what we are seeking if (recIndx == 0) { // This is the first record, so no records are appropriate // Nothing in this btree will match. We can stop right here. goto on_exit; } // This is not the first record, so, the previous record's child is the one we want. break; } // CASE: key in this record matches the key we are seeking. The previous record's child // is the one we want. However, if this is the first record, then we want THIS record's child. if (comp == 0 && recIndx != 0) { break; } // Extract the child node ID from the record data (stored after the key) keyLength = tsk_getu16(endian, keyB->key_len); // make sure the fields we care about are still in the buffer // +2 is because key_len doesn't include its own length // +4 is because of the amount of data we read from the data if (recOffset + keyLength + 2 + 4 > attrFile.nodeSize) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Unable to process attribute"); goto on_error; } recData = &recordBytes[keyLength + 2]; // Data must start on an even offset from the beginning of the record. // So, correct this if needed. if ((recData - recordBytes) % 2) { recData += 1; } // The next four bytes should be the Node ID of the child of this node. nodeID = tsk_getu32(endian, recData); // At this point, either comp<0 or comp=0 && recIndx=0. In the latter case we want to // descend to the child of this node, so we break. if (recIndx == 0 && comp == 0) { break; } // CASE: key in this record is less than key we seek. comp < 0 // So, continue looping over records in this node. } // END loop over records } // END while loop over Nodes in path from root to LEAF node // At this point nodeData holds the contents of a LEAF node with the right range of keys // and nodeDescriptor points to the descriptor of that node. // Loop over successive LEAF nodes, starting with this one done = FALSE; while (!done) { uint16_t numRec; // number of records unsigned int recIndx; // index for looping over records if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: Attributes File LEAF Node %" PRIu32 ".\n", nodeID); numRec = tsk_getu16(endian, nodeDescriptor->num_rec); // Note, leaf node could have one (or maybe zero) records // Loop over the records in this node for (recIndx = 0; recIndx < numRec; ++recIndx) { // The offset to the record is stored in table at end of node uint8_t *recOffsetTblEntry = &nodeData[attrFile.nodeSize - (2 * (recIndx + 1))]; // data describing where this record is uint16_t recOffset = tsk_getu16(endian, recOffsetTblEntry); int comp; // comparison result char *compStr; // comparison result as a string uint32_t keyFileID; // make sure the record and first fields are in the buffer if (recOffset + 14 > attrFile.nodeSize) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Unable to process attribute (offset too big)"); goto on_error; } // Pointer to first byte of record uint8_t *recordBytes = &nodeData[recOffset]; // Cast that to the Attributes file key keyB = (hfs_btree_key_attr *) recordBytes; // Compare recordBytes key to the key that we are seeking keyFileID = tsk_getu32(endian, keyB->file_id); //fprintf(stdout, " Key file ID = %lu\n", keyFileID); if (keyFileID < fileID) { comp = -1; compStr = "less than"; } else if (keyFileID > fileID) { comp = 1; compStr = "greater than"; } else { comp = 0; compStr = "equal to"; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: LEAF Record key file ID %" PRIu32 " is %s the desired file ID %" PRIu32 "\n", keyFileID, compStr, fileID); // Are they the same? if (comp == 0) { // Yes, so load this attribute uint8_t *recData; // pointer to the data part of the recordBytes hfs_attr_data *attrData; uint32_t attributeLength; uint32_t nameLength; uint32_t recordType; uint16_t keyLength; int conversionResult; char nameBuff[HFS_MAX_ATTR_NAME_LEN_UTF8_B+1]; TSK_FS_ATTR_TYPE_ENUM attrType; TSK_FS_ATTR *fs_attr; // Points to the attribute to be loaded. keyLength = tsk_getu16(endian, keyB->key_len); // make sure the fields we care about are still in the buffer // +2 because key_len doesn't include its own length // +16 for the amount of data we'll read from data if (recOffset + keyLength + 2 + 16 > attrFile.nodeSize) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Unable to process attribute"); goto on_error; } recData = &recordBytes[keyLength + 2]; // Data must start on an even offset from the beginning of the record. // So, correct this if needed. if ((recData - recordBytes) % 2) { recData += 1; } attrData = (hfs_attr_data *) recData; // Check we can process the record type before allocating memory recordType = tsk_getu32(endian, attrData->record_type); if (recordType != HFS_ATTR_RECORD_INLINE_DATA) { error_detected(TSK_ERR_FS_UNSUPTYPE, "hfs_load_extended_attrs: Unsupported record type: (%d)", recordType); goto on_error; } // This is the length of the useful data, not including the record header attributeLength = tsk_getu32(endian, attrData->attr_size); // Check the attribute fits in the node //if (recordType != HFS_ATTR_RECORD_INLINE_DATA) { if (recOffset + keyLength + 2 + attributeLength > attrFile.nodeSize) { error_detected(TSK_ERR_FS_READ, "hfs_load_extended_attrs: Unable to process attribute"); goto on_error; } // attr_name_len is in UTF_16 chars nameLength = tsk_getu16(endian, keyB->attr_name_len); if (2*nameLength > HFS_MAX_ATTR_NAME_LEN_UTF16_B) { error_detected(TSK_ERR_FS_CORRUPT, "hfs_load_extended_attrs: Name length (%d) is too long.", nameLength); goto on_error; } buffer = tsk_malloc(attributeLength); if (buffer == NULL) { error_detected(TSK_ERR_AUX_MALLOC, "hfs_load_extended_attrs: Could not malloc space for the attribute."); goto on_error; } memcpy(buffer, attrData->attr_data, attributeLength); // Use the "attr_name" part of the key as the attribute name // but must convert to UTF8. Unfortunately, there does not seem to // be any easy way to determine how long the converted string will // be because UTF8 is a variable length encoding. However, the longest // it will be is 3 * the max number of UTF16 code units. Add one for null // termination. (thanks Judson!) conversionResult = hfs_UTF16toUTF8(fs, keyB->attr_name, nameLength, nameBuff, HFS_MAX_ATTR_NAME_LEN_UTF8_B+1, 0); if (conversionResult != 0) { error_returned ("-- hfs_load_extended_attrs could not convert the attr_name in the btree key into a UTF8 attribute name"); goto on_error; } // What is the type of this attribute? If it is a compression record, then // use TSK_FS_ATTR_TYPE_HFS_COMP_REC. Else, use TSK_FS_ATTR_TYPE_HFS_EXT_ATTR // Only "inline data" kind of record is handled. if (strcmp(nameBuff, "com.apple.decmpfs") == 0 && tsk_getu32(endian, attrData->record_type) == HFS_ATTR_RECORD_INLINE_DATA) { // Now, look at the compression record DECMPFS_DISK_HEADER *cmph = (DECMPFS_DISK_HEADER *) buffer; *cmpType = tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type); uint64_t uncSize = tsk_getu64(TSK_LIT_ENDIAN, cmph->uncompressed_size); if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: This attribute is a compression record.\n"); attrType = TSK_FS_ATTR_TYPE_HFS_COMP_REC; *isCompressed = TRUE; // The data is governed by a compression record (but might not be compressed) *uncompressedSize = uncSize; switch (*cmpType) { // Data is inline. We will load the uncompressed // data as a resident attribute. case DECMPFS_TYPE_ZLIB_ATTR: if (!hfs_file_read_zlib_attr( fs_file, buffer, attributeLength, uncSize)) { goto on_error; } break; case DECMPFS_TYPE_LZVN_ATTR: if (!hfs_file_read_lzvn_attr( fs_file, buffer, attributeLength, uncSize)) { goto on_error; } break; // Data is compressed in the resource fork case DECMPFS_TYPE_ZLIB_RSRC: case DECMPFS_TYPE_LZVN_RSRC: if (tsk_verbose) tsk_fprintf(stderr, "%s: Compressed data is in the file Resource Fork.\n", __func__); break; } } else { // Attrbute name is NOT com.apple.decmpfs attrType = TSK_FS_ATTR_TYPE_HFS_EXT_ATTR; } // END if attribute name is com.apple.decmpfs ELSE clause if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_RES)) == NULL) { error_returned(" - hfs_load_extended_attrs"); goto on_error; } if (tsk_verbose) { tsk_fprintf(stderr, "hfs_load_extended_attrs: loading attribute %s, type %u (%s)\n", nameBuff, (uint32_t) attrType, hfs_attrTypeName((uint32_t) attrType)); } // set the details in the fs_attr structure if (tsk_fs_attr_set_str(fs_file, fs_attr, nameBuff, attrType, attribute_counter, buffer, attributeLength)) { error_returned(" - hfs_load_extended_attrs"); goto on_error; } free(buffer); buffer = NULL; ++attribute_counter; } // END if comp == 0 if (comp == 1) { // since this record key is greater than our search key, all // subsequent records will also be greater. done = TRUE; break; } } // END loop over records in one LEAF node /* * We get to this point if either: * * 1. We finish the loop over records and we are still loading attributes * for the given file. In this case we are NOT done, and must read in * the next leaf node, and process its records. The following code * loads the next leaf node before we return to the top of the loop. * * 2. We "broke" out of the loop over records because we found a key that * whose file ID is greater than the one we are working on. In that case * we are done. The following code does not run, and we exit the * while loop over successive leaf nodes. */ if (!done) { // We did not finish loading the attributes when we got to the end of that node, // so we must get the next node, and continue. // First determine the nodeID of the next LEAF node uint32_t newNodeID = tsk_getu32(endian, nodeDescriptor->flink); //fprintf(stdout, "Next Node ID = %u\n", newNodeID); if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: Processed last record of THIS node, still gathering attributes.\n"); // If we are at the very last leaf node in the btree, then // this "flink" will be zero. We break out of this loop over LEAF nodes. if (newNodeID == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: But, there are no more leaf nodes, so we are done.\n"); break; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_extended_attrs: Reading the next LEAF node %" PRIu32 ".\n", nodeID); nodeID = newNodeID; cnt = tsk_fs_file_read(attrFile.file, nodeID * attrFile.nodeSize, (char *) nodeData, attrFile.nodeSize, (TSK_FS_FILE_READ_FLAG_ENUM) 0); if (cnt != attrFile.nodeSize) { error_returned ("hfs_load_extended_attrs: Could not read in the next LEAF node from the Attributes File btree"); goto on_error; } // Parse the Node header nodeDescriptor = (hfs_btree_node *) nodeData; // If we are NOT leaf node, then this is an error if (nodeDescriptor->type != HFS_ATTR_NODE_LEAF) { error_detected(TSK_ERR_FS_CORRUPT, "hfs_load_extended_attrs: found a non-LEAF node as a successor to a LEAF node"); goto on_error; } } // END if(! done) } // END while(! done) loop over successive LEAF nodes on_exit: free(nodeData); tsk_list_free(nodeIDs_processed); close_attr_file(&attrFile); return 0; on_error: if (buffer != NULL) { free(buffer); } if (nodeData != NULL) { free(nodeData); } tsk_list_free(nodeIDs_processed); close_attr_file(&attrFile); return 1; } typedef struct RES_DESCRIPTOR { char type[5]; // type is really 4 chars, but we will null-terminate uint16_t id; uint32_t offset; uint32_t length; char *name; // NULL if a name is not defined for this resource struct RES_DESCRIPTOR *next; } RES_DESCRIPTOR; void free_res_descriptor(RES_DESCRIPTOR * rd) { RES_DESCRIPTOR *nxt; if (rd == NULL) return; nxt = rd->next; if (rd->name != NULL) free(rd->name); free(rd); free_res_descriptor(nxt); // tail recursive } /** * The purpose of this function is to parse the resource fork of a file, and to return * a data structure that is, in effect, a table of contents for the resource fork. The * data structure is a null-terminated linked list of entries. Each one describes one * resource. If the resource fork is empty, or if there is not a resource fork at all, * or an error occurs, this function returns NULL. * * A non-NULL answer should be freed by the caller, using free_res_descriptor. * */ static RES_DESCRIPTOR * hfs_parse_resource_fork(TSK_FS_FILE * fs_file) { RES_DESCRIPTOR *result = NULL; RES_DESCRIPTOR *last = NULL; TSK_FS_INFO *fs_info; hfs_fork *fork_info; hfs_fork *resForkInfo; uint64_t resSize; const TSK_FS_ATTR *rAttr; hfs_resource_fork_header rfHeader; hfs_resource_fork_header *resHead; uint32_t dataOffset; uint32_t mapOffset; uint32_t mapLength; char *map; int attrReadResult; int attrReadResult1; int attrReadResult2; hfs_resource_fork_map_header *mapHdr; uint16_t typeListOffset; uint16_t nameListOffset; unsigned char hasNameList; char *nameListBegin = NULL; hfs_resource_type_list *typeList; uint16_t numTypes; hfs_resource_type_list_item *tlItem; int mindx; // index for looping over resource types if (fs_file == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_parse_resource_fork: null fs_file"); return NULL; } if (fs_file->meta == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_parse_resource_fork: fs_file has null metadata"); return NULL; } if (fs_file->meta->content_ptr == NULL) { if (tsk_verbose) fprintf(stderr, "hfs_parse_resource_fork: fs_file has null fork data structures, so no resources.\n"); return NULL; } // Extract the fs fs_info = fs_file->fs_info; if (fs_info == NULL) { error_detected(TSK_ERR_FS_ARG, "hfs_parse_resource_fork: null fs within fs_info"); return NULL; } // Try to look at the Resource Fork for an HFS+ file // Should be able to cast this to hfs_fork * fork_info = (hfs_fork *) fs_file->meta->content_ptr; // The data fork // The resource fork is the second one. resForkInfo = &fork_info[1]; resSize = tsk_getu64(fs_info->endian, resForkInfo->logic_sz); //uint32_t numBlocks = tsk_getu32(fs_info->endian, resForkInfo->total_blk); //uint32_t clmpSize = tsk_getu32(fs_info->endian, resForkInfo->clmp_sz); // Hmm, certainly no resources here! if (resSize == 0) { return NULL; } // OK, resource size must be > 0 // find the attribute for the resource fork rAttr = tsk_fs_file_attr_get_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC, TRUE); if (rAttr == NULL) { error_returned ("hfs_parse_resource_fork: could not get the resource fork attribute"); return NULL; } // JUST read the resource fork header attrReadResult1 = tsk_fs_attr_read(rAttr, 0, (char *) &rfHeader, sizeof(hfs_resource_fork_header), TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult1 < 0 || attrReadResult1 != sizeof(hfs_resource_fork_header)) { error_returned (" hfs_parse_resource_fork: trying to read the resource fork header"); return NULL; } // Begin to parse the resource fork resHead = &rfHeader; dataOffset = tsk_getu32(fs_info->endian, resHead->dataOffset); mapOffset = tsk_getu32(fs_info->endian, resHead->mapOffset); //uint32_t dataLength = tsk_getu32(fs_info->endian, resHead->dataLength); mapLength = tsk_getu32(fs_info->endian, resHead->mapLength); // Read in the WHOLE map map = (char *) tsk_malloc(mapLength); if (map == NULL) { error_returned ("- hfs_parse_resource_fork: could not allocate space for the resource fork map"); return NULL; } attrReadResult = tsk_fs_attr_read(rAttr, (uint64_t) mapOffset, map, (size_t) mapLength, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult < 0 || attrReadResult != mapLength) { error_returned ("- hfs_parse_resource_fork: could not read the map"); free(map); return NULL; } mapHdr = (hfs_resource_fork_map_header *) map; typeListOffset = tsk_getu16(fs_info->endian, mapHdr->typeListOffset); nameListOffset = tsk_getu16(fs_info->endian, mapHdr->nameListOffset); if (nameListOffset >= mapLength || nameListOffset == 0) { hasNameList = FALSE; } else { hasNameList = TRUE; nameListBegin = map + nameListOffset; } typeList = (hfs_resource_type_list *) (map + typeListOffset); numTypes = tsk_getu16(fs_info->endian, typeList->typeCount) + 1; for (mindx = 0; mindx < numTypes; ++mindx) { uint16_t numRes; uint16_t refOff; int pindx; // index for looping over resources uint16_t rID; uint32_t rOffset; tlItem = &(typeList->type[mindx]); numRes = tsk_getu16(fs_info->endian, tlItem->count) + 1; refOff = tsk_getu16(fs_info->endian, tlItem->offset); for (pindx = 0; pindx < numRes; ++pindx) { int16_t nameOffset; char *nameBuffer; RES_DESCRIPTOR *rsrc; char lenBuff[4]; // first 4 bytes of a resource encodes its length uint32_t rLen; // Resource length hfs_resource_refListItem *item = ((hfs_resource_refListItem *) (((uint8_t *) typeList) + refOff)) + pindx; nameOffset = tsk_gets16(fs_info->endian, item->resNameOffset); nameBuffer = NULL; if (hasNameList && nameOffset != -1) { char *name = nameListBegin + nameOffset; uint8_t nameLen = (uint8_t) name[0]; nameBuffer = tsk_malloc(nameLen + 1); if (nameBuffer == NULL) { error_returned ("hfs_parse_resource_fork: allocating space for the name of a resource"); free_res_descriptor(result); return NULL; } memcpy(nameBuffer, name + 1, nameLen); nameBuffer[nameLen] = (char) 0; } else { nameBuffer = tsk_malloc(7); if (nameBuffer == NULL) { error_returned ("hfs_parse_resource_fork: allocating space for the (null) name of a resource"); free_res_descriptor(result); return NULL; } memcpy(nameBuffer, "<none>", 6); nameBuffer[6] = (char) 0; } rsrc = (RES_DESCRIPTOR *) tsk_malloc(sizeof(RES_DESCRIPTOR)); if (rsrc == NULL) { error_returned ("hfs_parse_resource_fork: space for a resource descriptor"); free_res_descriptor(result); return NULL; } // Build the linked list if (result == NULL) result = rsrc; if (last != NULL) last->next = rsrc; last = rsrc; rsrc->next = NULL; rID = tsk_getu16(fs_info->endian, item->resID); rOffset = tsk_getu24(fs_info->endian, item->resDataOffset) + dataOffset; // Just read the first four bytes of the resource to get its length. It MUST // be at least 4 bytes long attrReadResult2 = tsk_fs_attr_read(rAttr, (uint64_t) rOffset, lenBuff, (size_t) 4, TSK_FS_FILE_READ_FLAG_NONE); if (attrReadResult2 != 4) { error_returned ("- hfs_parse_resource_fork: could not read the 4-byte length at beginning of resource"); free_res_descriptor(result); return NULL; } rLen = tsk_getu32(TSK_BIG_ENDIAN, lenBuff); //TODO rsrc->id = rID; rsrc->offset = rOffset + 4; memcpy(rsrc->type, tlItem->type, 4); rsrc->type[4] = (char) 0; rsrc->length = rLen; rsrc->name = nameBuffer; } // END loop over resources of one type } // END loop over resource types return result; } static uint8_t hfs_load_attrs(TSK_FS_FILE * fs_file) { TSK_FS_INFO *fs; HFS_INFO *hfs; TSK_FS_ATTR *fs_attr; TSK_FS_ATTR_RUN *attr_run; hfs_fork *forkx; unsigned char resource_fork_has_contents = FALSE; unsigned char compression_flag = FALSE; unsigned char isCompressed = FALSE; unsigned char compDataInRSRCFork = FALSE; unsigned char cmpType = 0; uint64_t uncompressedSize; uint64_t logicalSize; // of a fork // clean up any error messages that are lying around tsk_error_reset(); if ((fs_file == NULL) || (fs_file->meta == NULL) || (fs_file->fs_info == NULL)) { error_detected(TSK_ERR_FS_ARG, "hfs_load_attrs: fs_file or meta is NULL"); return 1; } fs = (TSK_FS_INFO *) fs_file->fs_info; hfs = (HFS_INFO *) fs; if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: Processing file %" PRIuINUM "\n", fs_file->meta->addr); // see if we have already loaded the runs if (fs_file->meta->attr_state == TSK_FS_META_ATTR_STUDIED) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: Attributes already loaded\n"); return 0; } else if (fs_file->meta->attr_state == TSK_FS_META_ATTR_ERROR) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: Previous attempt to load attributes resulted in error\n"); return 1; } // Now (re)-initialize the attrlist that will hold the list of attributes if (fs_file->meta->attr != NULL) { tsk_fs_attrlist_markunused(fs_file->meta->attr); } else if (fs_file->meta->attr == NULL) { fs_file->meta->attr = tsk_fs_attrlist_alloc(); } /****************** EXTENDED ATTRIBUTES *******************************/ // We do these first, so that we can detect the mode of compression, if // any. We need to know that mode in order to handle the forks. if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: loading the HFS+ extended attributes\n"); if (hfs_load_extended_attrs(fs_file, &isCompressed, &cmpType, &uncompressedSize)) { error_returned(" - hfs_load_attrs A"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } // TODO: What about DECMPFS_TYPE_RAW_RSRC? switch (cmpType) { case DECMPFS_TYPE_ZLIB_RSRC: case DECMPFS_TYPE_LZVN_RSRC: compDataInRSRCFork = TRUE; break; default: compDataInRSRCFork = FALSE; break; } if (isCompressed) { fs_file->meta->size = uncompressedSize; } // This is the flag indicating compression, from the Catalog File record. compression_flag = (fs_file->meta->flags & TSK_FS_META_FLAG_COMP) != 0; if (compression_flag && !isCompressed) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: WARNING, HFS marks this as a" " compressed file, but no compression record was found.\n"); } if (isCompressed && !compression_flag) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: WARNING, this file has a compression" " record, but the HFS compression flag is not set.\n"); } /************* FORKS (both) ************************************/ // Process the data and resource forks. We only do this if the // fork data structures are non-null, so test that: if (fs_file->meta->content_ptr != NULL) { /************** DATA FORK STUFF ***************************/ // Get the data fork data-structure forkx = (hfs_fork *) fs_file->meta->content_ptr; // If this is a compressed file, then either this attribute is already loaded // because the data was in the compression record, OR // the compressed data is in the resource fork. We will load those runs when // we handle the resource fork. if (!isCompressed) { // We only load this attribute if this fork has non-zero length // or if this is a REG or LNK file. Otherwise, we skip logicalSize = tsk_getu64(fs->endian, forkx->logic_sz); if (logicalSize > 0 || fs_file->meta->type == TSK_FS_META_TYPE_REG || fs_file->meta->type == TSK_FS_META_TYPE_LNK) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: loading the data fork attribute\n"); // get an attribute structure to store the data in if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_load_attrs"); return 1; } /* NOTE that fs_attr is now tied to fs_file->meta->attr. * that means that we do not need to free it if we abort in the * following code (and doing so will cause double free errors). */ if (logicalSize > 0) { // Convert runs of blocks to the TSK internal form if (((attr_run = hfs_extents_to_attr(fs, forkx->extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_load_attrs"); return 1; } // add the runs to the attribute and the attribute to the file. if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "", TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, logicalSize, logicalSize, (TSK_OFF_T) tsk_getu32(fs->endian, forkx->total_blk) * fs->block_size, 0, 0)) { error_returned(" - hfs_load_attrs (DATA)"); tsk_fs_attr_run_free(attr_run); return 1; } // see if extents file has additional runs if (hfs_ext_find_extent_record_attr(hfs, (uint32_t) fs_file->meta->addr, fs_attr, TRUE)) { error_returned(" - hfs_load_attrs B"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } } else { // logicalSize == 0, but this is either a REG or LNK file // so, it should have a DATA fork attribute of zero length. if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "", TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, 0, 0, 0, 0, 0)) { error_returned(" - hfs_load_attrs (non-file)"); return 1; } } } // END logicalSize>0 or REG or LNK file type } // END if not Compressed /************** RESOURCE FORK STUFF ************************************/ // Get the resource fork. //Note that content_ptr points to an array of two // hfs_fork data structures, the second of which // describes the blocks of the resource fork. forkx = &((hfs_fork *) fs_file->meta->content_ptr)[1]; logicalSize = tsk_getu64(fs->endian, forkx->logic_sz); // Skip if the length of the resource fork is zero if (logicalSize > 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: loading the resource fork\n"); resource_fork_has_contents = TRUE; // get an attribute structure to store the resource fork data in. We will // reuse the fs_attr variable, since we are done with the data fork. if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned(" - hfs_load_attrs (RSRC)"); return 1; } /* NOTE that fs_attr is now tied to fs_file->meta->attr. * that means that we do not need to free it if we abort in the * following code (and doing so will cause double free errors). */ // convert the resource fork to the TSK format if (((attr_run = hfs_extents_to_attr(fs, forkx->extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned(" - hfs_load_attrs"); return 1; } // add the runs to the attribute and the attribute to the file. if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "RSRC", TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC, tsk_getu64(fs->endian, forkx->logic_sz), tsk_getu64(fs->endian, forkx->logic_sz), (TSK_OFF_T) tsk_getu32(fs->endian, forkx->total_blk) * fs->block_size, 0, 0)) { error_returned(" - hfs_load_attrs (RSRC)"); tsk_fs_attr_run_free(attr_run); return 1; } // see if extents file has additional runs for the resource fork. if (hfs_ext_find_extent_record_attr(hfs, (uint32_t) fs_file->meta->addr, fs_attr, FALSE)) { error_returned(" - hfs_load_attrs C"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (isCompressed && compDataInRSRCFork) { // OK, we are going to load those same resource fork blocks as the "DATA" // attribute, but will mark it as compressed. // get an attribute structure to store the resource fork data in. We will // reuse the fs_attr variable, since we are done with the data fork. if (tsk_verbose) tsk_fprintf(stderr, "File is compressed with data in the resource fork. " "Loading the default DATA attribute.\n"); if ((fs_attr = tsk_fs_attrlist_getnew(fs_file->meta->attr, TSK_FS_ATTR_NONRES)) == NULL) { error_returned (" - hfs_load_attrs (RSRC loading as DATA)"); return 1; } /* NOTE that fs_attr is now tied to fs_file->meta->attr. * that means that we do not need to free it if we abort in the * following code (and doing so will cause double free errors). */ switch (cmpType) { case DECMPFS_TYPE_ZLIB_RSRC: #ifdef HAVE_LIBZ fs_attr->w = hfs_attr_walk_zlib_rsrc; fs_attr->r = hfs_file_read_zlib_rsrc; #else // We don't have zlib, so the uncompressed data is not // available to us; however, we must have a default DATA // attribute, or icat will misbehave. if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: No zlib compression library, so setting a zero-length default DATA attribute.\n"); if (tsk_fs_attr_set_run(fs_file, fs_attr, NULL, "DATA", TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, 0, 0, 0, 0, 0)) { error_returned(" - hfs_load_attrs (non-file)"); return 1; } #endif break; case DECMPFS_TYPE_LZVN_RSRC: fs_attr->w = hfs_attr_walk_lzvn_rsrc; fs_attr->r = hfs_file_read_lzvn_rsrc; break; } // convert the resource fork to the TSK format if (((attr_run = hfs_extents_to_attr(fs, forkx->extents, 0)) == NULL) && (tsk_error_get_errno() != 0)) { error_returned (" - hfs_load_attrs, RSRC fork as DATA fork"); return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: Loading RSRC fork block runs as the default DATA attribute.\n"); // add the runs to the attribute and the attribute to the file. if (tsk_fs_attr_set_run(fs_file, fs_attr, attr_run, "DECOMP", TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, logicalSize, logicalSize, (TSK_OFF_T) tsk_getu32(fs->endian, forkx->total_blk) * fs->block_size, TSK_FS_ATTR_COMP | TSK_FS_ATTR_NONRES, 0)) { error_returned (" - hfs_load_attrs (RSRC loading as DATA)"); tsk_fs_attr_run_free(attr_run); return 1; } // see if extents file has additional runs for the resource fork. if (hfs_ext_find_extent_record_attr(hfs, (uint32_t) fs_file->meta->addr, fs_attr, FALSE)) { error_returned (" - hfs_load_attrs (RSRC loading as DATA"); fs_file->meta->attr_state = TSK_FS_META_ATTR_ERROR; return 1; } if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: setting the \"special\" function pointers to inflate compressed data.\n"); } } // END resource fork size > 0 } // END the fork data structures are non-NULL if (isCompressed && compDataInRSRCFork && !resource_fork_has_contents) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_load_attrs: WARNING, compression record claims that compressed data" " is in the Resource Fork, but that fork is empty or non-existent.\n"); } // Finish up. fs_file->meta->attr_state = TSK_FS_META_ATTR_STUDIED; return 0; } /** \internal * Get allocation status of file system block. * adapted from IsAllocationBlockUsed from: * http://developer.apple.com/technotes/tn/tn1150.html * * @param hfs File system being analyzed * @param b Block address * @returns 1 if allocated, 0 if not, -1 on error */ static int8_t hfs_block_is_alloc(HFS_INFO * hfs, TSK_DADDR_T a_addr) { TSK_FS_INFO *fs = &(hfs->fs_info); TSK_OFF_T b; size_t b2; // lazy loading if (hfs->blockmap_file == NULL) { if ((hfs->blockmap_file = tsk_fs_file_open_meta(fs, NULL, HFS_ALLOCATION_FILE_ID)) == NULL) { tsk_error_errstr2_concat(" - Loading blockmap file"); return -1; } /* cache the data attribute */ hfs->blockmap_attr = tsk_fs_attrlist_get(hfs->blockmap_file->meta->attr, TSK_FS_ATTR_TYPE_DEFAULT); if (!hfs->blockmap_attr) { tsk_error_errstr2_concat (" - Data Attribute not found in Blockmap File"); return -1; } hfs->blockmap_cache_start = -1; hfs->blockmap_cache_len = 0; } // get the byte offset b = (TSK_OFF_T) a_addr / 8; if (b > hfs->blockmap_file->meta->size) { tsk_error_set_errno(TSK_ERR_FS_CORRUPT); tsk_error_set_errstr("hfs_block_is_alloc: block %" PRIuDADDR " is too large for bitmap (%" PRIuOFF ")", a_addr, hfs->blockmap_file->meta->size); return -1; } // see if it is in the cache if ((hfs->blockmap_cache_start == -1) || (hfs->blockmap_cache_start > b) || (hfs->blockmap_cache_start + hfs->blockmap_cache_len <= b)) { size_t cnt = tsk_fs_attr_read(hfs->blockmap_attr, b, hfs->blockmap_cache, sizeof(hfs->blockmap_cache), 0); if (cnt < 1) { tsk_error_set_errstr2 ("hfs_block_is_alloc: Error reading block bitmap at offset %" PRIuOFF, b); return -1; } hfs->blockmap_cache_start = b; hfs->blockmap_cache_len = cnt; } b2 = (size_t) (b - hfs->blockmap_cache_start); return (hfs->blockmap_cache[b2] & (1 << (7 - (a_addr % 8)))) != 0; } TSK_FS_BLOCK_FLAG_ENUM hfs_block_getflags(TSK_FS_INFO * a_fs, TSK_DADDR_T a_addr) { return (hfs_block_is_alloc((HFS_INFO *) a_fs, a_addr) == 1) ? TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC; } static uint8_t hfs_block_walk(TSK_FS_INFO * fs, TSK_DADDR_T start_blk, TSK_DADDR_T end_blk, TSK_FS_BLOCK_WALK_FLAG_ENUM flags, TSK_FS_BLOCK_WALK_CB action, void *ptr) { char *myname = "hfs_block_walk"; HFS_INFO *hfs = (HFS_INFO *) fs; TSK_FS_BLOCK *fs_block; TSK_DADDR_T addr; if (tsk_verbose) tsk_fprintf(stderr, "%s: start_blk: %" PRIuDADDR " end_blk: %" PRIuDADDR " flags: %" PRIu32 "\n", myname, start_blk, end_blk, flags); // clean up any error messages that are lying around tsk_error_reset(); /* * Sanity checks. */ if (start_blk < fs->first_block || start_blk > fs->last_block) { tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("%s: invalid start block number: %" PRIuDADDR "", myname, start_blk); return 1; } if (end_blk < fs->first_block || end_blk > fs->last_block) { tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("%s: invalid last block number: %" PRIuDADDR "", myname, end_blk); return 1; } if (start_blk > end_blk) XSWAP(start_blk, end_blk); /* Sanity check on flags -- make sure at least one ALLOC is set */ if (((flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC) == 0) && ((flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC) == 0)) { flags |= (TSK_FS_BLOCK_WALK_FLAG_ALLOC | TSK_FS_BLOCK_WALK_FLAG_UNALLOC); } if (((flags & TSK_FS_BLOCK_WALK_FLAG_META) == 0) && ((flags & TSK_FS_BLOCK_WALK_FLAG_CONT) == 0)) { flags |= (TSK_FS_BLOCK_WALK_FLAG_CONT | TSK_FS_BLOCK_WALK_FLAG_META); } if ((fs_block = tsk_fs_block_alloc(fs)) == NULL) { return 1; } /* * Iterate */ for (addr = start_blk; addr <= end_blk; ++addr) { int retval; int myflags; /* identify if the block is allocated or not */ myflags = hfs_block_is_alloc(hfs, addr) ? TSK_FS_BLOCK_FLAG_ALLOC : TSK_FS_BLOCK_FLAG_UNALLOC; // test if we should call the callback with this one if ((myflags & TSK_FS_BLOCK_FLAG_ALLOC) && (!(flags & TSK_FS_BLOCK_WALK_FLAG_ALLOC))) continue; else if ((myflags & TSK_FS_BLOCK_FLAG_UNALLOC) && (!(flags & TSK_FS_BLOCK_WALK_FLAG_UNALLOC))) continue; if (flags & TSK_FS_BLOCK_WALK_FLAG_AONLY) myflags |= TSK_FS_BLOCK_FLAG_AONLY; if (tsk_fs_block_get_flag(fs, fs_block, addr, (TSK_FS_BLOCK_FLAG_ENUM) myflags) == NULL) { tsk_fs_block_free(fs_block); return 1; } retval = action(fs_block, ptr); if (TSK_WALK_STOP == retval) { break; } else if (TSK_WALK_ERROR == retval) { tsk_fs_block_free(fs_block); return 1; } } tsk_fs_block_free(fs_block); return 0; } uint8_t hfs_inode_walk(TSK_FS_INFO * fs, TSK_INUM_T start_inum, TSK_INUM_T end_inum, TSK_FS_META_FLAG_ENUM flags, TSK_FS_META_WALK_CB action, void *ptr) { TSK_INUM_T inum; TSK_FS_FILE *fs_file; if (tsk_verbose) tsk_fprintf(stderr, "hfs_inode_walk: start_inum: %" PRIuINUM " end_inum: %" PRIuINUM " flags: %" PRIu32 "\n", start_inum, end_inum, flags); /* * Sanity checks. */ if (start_inum < fs->first_inum || start_inum > fs->last_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("inode_walk: Start inode: %" PRIuINUM "", start_inum); return 1; } else if (end_inum < fs->first_inum || end_inum > fs->last_inum || end_inum < start_inum) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_WALK_RNG); tsk_error_set_errstr("inode_walk: End inode: %" PRIuINUM "", end_inum); return 1; } /* If ORPHAN is wanted, then make sure that the flags are correct */ if (flags & TSK_FS_META_FLAG_ORPHAN) { flags |= TSK_FS_META_FLAG_UNALLOC; flags &= ~TSK_FS_META_FLAG_ALLOC; flags |= TSK_FS_META_FLAG_USED; flags &= ~TSK_FS_META_FLAG_UNUSED; } else { if (((flags & TSK_FS_META_FLAG_ALLOC) == 0) && ((flags & TSK_FS_META_FLAG_UNALLOC) == 0)) { flags |= (TSK_FS_META_FLAG_ALLOC | TSK_FS_META_FLAG_UNALLOC); } /* If neither of the USED or UNUSED flags are set, then set them * both */ if (((flags & TSK_FS_META_FLAG_USED) == 0) && ((flags & TSK_FS_META_FLAG_UNUSED) == 0)) { flags |= (TSK_FS_META_FLAG_USED | TSK_FS_META_FLAG_UNUSED); } } if ((fs_file = tsk_fs_file_alloc(fs)) == NULL) return 1; if ((fs_file->meta = tsk_fs_meta_alloc(HFS_FILE_CONTENT_LEN)) == NULL) return 1; if (start_inum > end_inum) XSWAP(start_inum, end_inum); for (inum = start_inum; inum <= end_inum; ++inum) { int retval; if (hfs_inode_lookup(fs, fs_file, inum)) { // deleted files may not exist in the catalog if (tsk_error_get_errno() == TSK_ERR_FS_INODE_NUM) { tsk_error_reset(); continue; } else { return 1; } } if ((fs_file->meta->flags & flags) != fs_file->meta->flags) continue; /* call action */ retval = action(fs_file, ptr); if (retval == TSK_WALK_STOP) { tsk_fs_file_close(fs_file); return 0; } else if (retval == TSK_WALK_ERROR) { tsk_fs_file_close(fs_file); return 1; } } tsk_fs_file_close(fs_file); return 0; } /* return the name of a file at a given inode * in a newly-allocated string, or NULL on error */ char * hfs_get_inode_name(TSK_FS_INFO * fs, TSK_INUM_T inum) { HFS_INFO *hfs = (HFS_INFO *) fs; HFS_ENTRY entry; char *fn = NULL; if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE)) return NULL; fn = malloc(HFS_MAXNAMLEN + 1); if (fn == NULL) return NULL; if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode, tsk_getu16(fs->endian, entry.thread.name.length), fn, HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH)) { free(fn); return NULL; } return fn; } /* print the name of a file at a given inode * returns 0 on success, 1 on error */ static uint8_t print_inode_name(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum) { HFS_INFO *hfs = (HFS_INFO *) fs; char fn[HFS_MAXNAMLEN + 1]; HFS_ENTRY entry; if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE)) return 1; if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode, tsk_getu16(fs->endian, entry.thread.name.length), fn, HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH)) return 1; tsk_fprintf(hFile, "%s", fn); return 0; } /* tail recursive function to print a path... prints the parent path, then * appends / and the name of the given inode. prints nothing for root * returns 0 on success, 1 on failure */ static uint8_t print_parent_path(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum) { HFS_INFO *hfs = (HFS_INFO *) fs; char fn[HFS_MAXNAMLEN + 1]; HFS_ENTRY entry; if (inum == HFS_ROOT_INUM) return 0; if (inum <= HFS_ROOT_INUM) { tsk_error_set_errno(TSK_ERR_FS_INODE_NUM); tsk_error_set_errstr("print_parent_path: out-of-range inode %" PRIuINUM, inum); return 1; } if (hfs_cat_file_lookup(hfs, inum, &entry, FALSE)) return 1; if (hfs_UTF16toUTF8(fs, entry.thread.name.unicode, tsk_getu16(fs->endian, entry.thread.name.length), fn, HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL)) return 1; if (print_parent_path(hFile, fs, (TSK_INUM_T) tsk_getu32(fs->endian, entry.thread.parent_cnid))) return 1; tsk_fprintf(hFile, "/%s", fn); return 0; } /* print the file name corresponding to an inode, in brackets after a space. * uses Unix path conventions, and does not include the volume name. * returns 0 on success, 1 on failure */ static uint8_t print_inode_file(FILE * hFile, TSK_FS_INFO * fs, TSK_INUM_T inum) { tsk_fprintf(hFile, " ["); if (inum == HFS_ROOT_INUM) tsk_fprintf(hFile, "/"); else { if (print_parent_path(hFile, fs, inum)) { tsk_fprintf(hFile, "unknown]"); return 1; } } tsk_fprintf(hFile, "]"); return 0; } static uint8_t hfs_fscheck(TSK_FS_INFO * fs, FILE * hFile) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_UNSUPFUNC); tsk_error_set_errstr("fscheck not implemented for HFS yet"); return 1; } static uint8_t hfs_fsstat(TSK_FS_INFO * fs, FILE * hFile) { // char *myname = "hfs_fsstat"; HFS_INFO *hfs = (HFS_INFO *) fs; hfs_plus_vh *sb = hfs->fs; time_t mac_time; TSK_INUM_T inode; char timeBuf[128]; if (tsk_verbose) tsk_fprintf(stderr, "hfs_fstat: called\n"); tsk_fprintf(hFile, "FILE SYSTEM INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "File System Type: "); if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSPLUS) tsk_fprintf(hFile, "HFS+\n"); else if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX) tsk_fprintf(hFile, "HFSX\n"); else tsk_fprintf(hFile, "Unknown\n"); // print name and number of version tsk_fprintf(hFile, "File System Version: "); switch (tsk_getu16(fs->endian, hfs->fs->version)) { case 4: tsk_fprintf(hFile, "HFS+\n"); break; case 5: tsk_fprintf(hFile, "HFSX\n"); break; default: tsk_fprintf(hFile, "Unknown (%" PRIu16 ")\n", tsk_getu16(fs->endian, hfs->fs->version)); break; } if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFSX) { tsk_fprintf(hFile, "Case Sensitive: %s\n", hfs->is_case_sensitive ? "yes" : "no"); } if (hfs->hfs_wrapper_offset > 0) { tsk_fprintf(hFile, "File system is embedded in an HFS wrapper at offset %" PRIuOFF "\n", hfs->hfs_wrapper_offset); } tsk_fprintf(hFile, "\nVolume Name: "); if (print_inode_name(hFile, fs, HFS_ROOT_INUM)) return 1; tsk_fprintf(hFile, "\n"); tsk_fprintf(hFile, "Volume Identifier: %08" PRIx32 "%08" PRIx32 "\n", tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID1]), tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_ID2])); // print last mounted info tsk_fprintf(hFile, "\nLast Mounted By: "); if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSPLUS) tsk_fprintf(hFile, "Mac OS X\n"); else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_HFSJ) tsk_fprintf(hFile, "Mac OS X, Journaled\n"); else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSK) tsk_fprintf(hFile, "failed journal replay\n"); else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_FSCK) tsk_fprintf(hFile, "fsck_hfs\n"); else if (tsk_getu32(fs->endian, sb->last_mnt_ver) == HFS_VH_MVER_OS89) tsk_fprintf(hFile, "Mac OS 8.1 - 9.2.2\n"); else tsk_fprintf(hFile, "Unknown (%" PRIx32 "\n", tsk_getu32(fs->endian, sb->last_mnt_ver)); /* State of the file system */ if ((tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_UNMOUNTED) && (!(tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_INCONSISTENT))) tsk_fprintf(hFile, "Volume Unmounted Properly\n"); else tsk_fprintf(hFile, "Volume Unmounted Improperly\n"); tsk_fprintf(hFile, "Mount Count: %" PRIu32 "\n", tsk_getu32(fs->endian, sb->write_cnt)); // Dates // (creation date is in local time zone, not UTC, according to TN 1150) mac_time = hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->cr_date)); tsk_fprintf(hFile, "\nCreation Date: \t%s\n", tsk_fs_time_to_str(mktime(gmtime(&mac_time)), timeBuf)); mac_time = hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->m_date)); tsk_fprintf(hFile, "Last Written Date: \t%s\n", tsk_fs_time_to_str(mac_time, timeBuf)); mac_time = hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->bkup_date)); tsk_fprintf(hFile, "Last Backup Date: \t%s\n", tsk_fs_time_to_str(mac_time, timeBuf)); mac_time = hfs_convert_2_unix_time(tsk_getu32(fs->endian, hfs->fs->chk_date)); tsk_fprintf(hFile, "Last Checked Date: \t%s\n", tsk_fs_time_to_str(mac_time, timeBuf)); if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_SOFTWARE_LOCK) tsk_fprintf(hFile, "Software write protect enabled\n"); /* Print journal information */ if (tsk_getu32(fs->endian, sb->attr) & HFS_VH_ATTR_JOURNALED) { tsk_fprintf(hFile, "\nJournal Info Block: %" PRIu32 "\n", tsk_getu32(fs->endian, sb->jinfo_blk)); } tsk_fprintf(hFile, "\nMETADATA INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "Range: %" PRIuINUM " - %" PRIuINUM "\n", fs->first_inum, fs->last_inum); inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT]); tsk_fprintf(hFile, "Bootable Folder ID: %" PRIuINUM, inode); if (inode > 0) print_inode_file(hFile, fs, inode); tsk_fprintf(hFile, "\n"); inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_START]); tsk_fprintf(hFile, "Startup App ID: %" PRIuINUM, inode); if (inode > 0) print_inode_file(hFile, fs, inode); tsk_fprintf(hFile, "\n"); inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_OPEN]); tsk_fprintf(hFile, "Startup Open Folder ID: %" PRIuINUM, inode); if (inode > 0) print_inode_file(hFile, fs, inode); tsk_fprintf(hFile, "\n"); inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOT9]); tsk_fprintf(hFile, "Mac OS 8/9 Blessed System Folder ID: %" PRIuINUM, inode); if (inode > 0) print_inode_file(hFile, fs, inode); tsk_fprintf(hFile, "\n"); inode = tsk_getu32(fs->endian, sb->finder_info[HFS_VH_FI_BOOTX]); tsk_fprintf(hFile, "Mac OS X Blessed System Folder ID: %" PRIuINUM, inode); if (inode > 0) print_inode_file(hFile, fs, inode); tsk_fprintf(hFile, "\n"); tsk_fprintf(hFile, "Number of files: %" PRIu32 "\n", tsk_getu32(fs->endian, sb->file_cnt)); tsk_fprintf(hFile, "Number of folders: %" PRIu32 "\n", tsk_getu32(fs->endian, sb->fldr_cnt)); tsk_fprintf(hFile, "\nCONTENT INFORMATION\n"); tsk_fprintf(hFile, "--------------------------------------------\n"); tsk_fprintf(hFile, "Block Range: %" PRIuDADDR " - %" PRIuDADDR "\n", fs->first_block, fs->last_block); if (fs->last_block != fs->last_block_act) tsk_fprintf(hFile, "Total Range in Image: %" PRIuDADDR " - %" PRIuDADDR "\n", fs->first_block, fs->last_block_act); tsk_fprintf(hFile, "Allocation Block Size: %u\n", fs->block_size); tsk_fprintf(hFile, "Number of Free Blocks: %" PRIu32 "\n", tsk_getu32(fs->endian, sb->free_blks)); if (tsk_getu32(fs->endian, hfs->fs->attr) & HFS_VH_ATTR_BADBLOCKS) tsk_fprintf(hFile, "Volume has bad blocks\n"); return 0; } /************************* istat *******************************/ /** * Text encoding names defined in TN1150, Table 2. */ static char * text_encoding_name(uint32_t enc) { switch (enc) { case 0: return "MacRoman"; case 1: return "MacJapanese"; case 2: return "MacChineseTrad"; case 4: return "MacKorean"; case 5: return "MacArabic"; case 6: return "MacHebrew"; case 7: return "MacGreek"; case 8: return "MacCyrillic"; case 9: return "MacDevanagari"; case 10: return "MacGurmukhi"; case 11: return "MacGujarati"; case 12: return "MacOriya"; case 13: return "MacBengali"; case 14: return "MacTamil"; case 15: return "Telugu"; case 16: return "MacKannada"; case 17: return "MacMalayalam"; case 18: return "MacSinhalese"; case 19: return "MacBurmese"; case 20: return "MacKhmer"; case 21: return "MacThai"; case 22: return "MacLaotian"; case 23: return "MacGeorgian"; case 24: return "MacArmenian"; case 25: return "MacChineseSimp"; case 26: return "MacTibetan"; case 27: return "MacMongolian"; case 28: return "MacEthiopic"; case 29: return "MacCentralEurRoman"; case 30: return "MacVietnamese"; case 31: return "MacExtArabic"; case 33: return "MacSymbol"; case 34: return "MacDingbats"; case 35: return "MacTurkish"; case 36: return "MacCroatian"; case 37: return "MacIcelandic"; case 38: return "MacRomanian"; case 49: case 140: return "MacFarsi"; case 48: case 152: return "MacUkrainian"; default: return "Unknown encoding"; } } #define HFS_PRINT_WIDTH 8 typedef struct { FILE *hFile; int idx; TSK_DADDR_T startBlock; uint32_t blockCount; unsigned char accumulating; } HFS_PRINT_ADDR; static void output_print_addr(HFS_PRINT_ADDR * print) { if (!print->accumulating) return; if (print->blockCount == 1) { tsk_fprintf(print->hFile, "%" PRIuDADDR " ", print->startBlock); print->idx += 1; } else if (print->blockCount > 1) { tsk_fprintf(print->hFile, "%" PRIuDADDR "-%" PRIuDADDR " ", print->startBlock, print->startBlock + print->blockCount - 1); print->idx += 2; } if (print->idx >= HFS_PRINT_WIDTH) { tsk_fprintf(print->hFile, "\n"); print->idx = 0; } } static TSK_WALK_RET_ENUM print_addr_act(TSK_FS_FILE * fs_file, TSK_OFF_T a_off, TSK_DADDR_T addr, char *buf, size_t size, TSK_FS_BLOCK_FLAG_ENUM flags, void *ptr) { HFS_PRINT_ADDR *print = (HFS_PRINT_ADDR *) ptr; if (print->accumulating) { if (addr == print->startBlock + print->blockCount) { ++print->blockCount; } else { output_print_addr(print); print->startBlock = addr; print->blockCount = 1; } } else { print->startBlock = addr; print->blockCount = 1; print->accumulating = TRUE; } return TSK_WALK_CONT; } /** * Print details on a specific file to a file handle. * * @param fs File system file is located in * @param hFile File name to print text to * @param inum Address of file in file system * @param numblock The number of blocks in file to force print (can go beyond file size) * @param sec_skew Clock skew in seconds to also print times in * * @returns 1 on error and 0 on success */ static uint8_t hfs_istat(TSK_FS_INFO * fs, TSK_FS_ISTAT_FLAG_ENUM istat_flags, FILE * hFile, TSK_INUM_T inum, TSK_DADDR_T numblock, int32_t sec_skew) { HFS_INFO *hfs = (HFS_INFO *) fs; TSK_FS_FILE *fs_file; char hfs_mode[12]; HFS_PRINT_ADDR print; HFS_ENTRY entry; char timeBuf[128]; // Compression ATTR, if there is one: const TSK_FS_ATTR *compressionAttr = NULL; RES_DESCRIPTOR *rd; // descriptor of a resource tsk_error_reset(); if (tsk_verbose) tsk_fprintf(stderr, "hfs_istat: inum: %" PRIuINUM " numblock: %" PRIu32 "\n", inum, numblock); if ((fs_file = tsk_fs_file_open_meta(fs, NULL, inum)) == NULL) { error_returned("hfs_istat: getting metadata for the file"); return 1; } if (inum >= HFS_FIRST_USER_CNID) { int rslt; tsk_fprintf(hFile, "File Path: "); rslt = print_parent_path(hFile, fs, inum); if (rslt != 0) tsk_fprintf(hFile, " Error in printing path\n"); else tsk_fprintf(hFile, "\n"); } else { // All of the files in this inum range have names without nulls, // slashes or control characters. So, it is OK to print this UTF8 // string this way. if (fs_file->meta->name2 != NULL) tsk_fprintf(hFile, "File Name: %s\n", fs_file->meta->name2->name); } tsk_fprintf(hFile, "Catalog Record: %" PRIuINUM "\n", inum); tsk_fprintf(hFile, "%sAllocated\n", (fs_file->meta->flags & TSK_FS_META_FLAG_UNALLOC) ? "Not " : ""); tsk_fprintf(hFile, "Type:\t"); if (fs_file->meta->type == TSK_FS_META_TYPE_REG) tsk_fprintf(hFile, "File\n"); else if (TSK_FS_IS_DIR_META(fs_file->meta->type)) tsk_fprintf(hFile, "Folder\n"); else tsk_fprintf(hFile, "\n"); tsk_fs_meta_make_ls(fs_file->meta, hfs_mode, sizeof(hfs_mode)); tsk_fprintf(hFile, "Mode:\t%s\n", hfs_mode); tsk_fprintf(hFile, "Size:\t%" PRIuOFF "\n", fs_file->meta->size); if (fs_file->meta->link) tsk_fprintf(hFile, "Symbolic link to:\t%s\n", fs_file->meta->link); tsk_fprintf(hFile, "uid / gid: %" PRIuUID " / %" PRIuGID "\n", fs_file->meta->uid, fs_file->meta->gid); tsk_fprintf(hFile, "Link count:\t%d\n", fs_file->meta->nlink); if (hfs_cat_file_lookup(hfs, inum, &entry, TRUE) == 0) { hfs_uni_str *nm = &entry.thread.name; char name_buf[HFS_MAXNAMLEN + 1]; TSK_INUM_T par_cnid; // parent CNID tsk_fprintf(hFile, "\n"); hfs_UTF16toUTF8(fs, nm->unicode, (int) tsk_getu16(fs->endian, nm->length), &name_buf[0], HFS_MAXNAMLEN + 1, HFS_U16U8_FLAG_REPLACE_SLASH | HFS_U16U8_FLAG_REPLACE_CONTROL); tsk_fprintf(hFile, "File Name: %s\n", name_buf); // Test here to see if this is a hard link. par_cnid = tsk_getu32(fs->endian, &(entry.thread.parent_cnid)); if ((hfs->has_meta_dir_crtime && par_cnid == hfs->meta_dir_inum) || (hfs->has_meta_crtime && par_cnid == hfs->meta_inum)) { int instr = strncmp(name_buf, "iNode", 5); int drstr = strncmp(name_buf, "dir_", 4); if (instr == 0 && hfs->has_meta_crtime && par_cnid == hfs->meta_inum) { tsk_fprintf(hFile, "This is a hard link to a file\n"); } else if (drstr == 0 && hfs->has_meta_dir_crtime && par_cnid == hfs->meta_dir_inum) { tsk_fprintf(hFile, "This is a hard link to a folder.\n"); } } /* The cat.perm union contains file-type specific values. * Print them if they are relevant. */ if ((fs_file->meta->type == TSK_FS_META_TYPE_CHR) || (fs_file->meta->type == TSK_FS_META_TYPE_BLK)) { tsk_fprintf(hFile, "Device ID:\t%" PRIu32 "\n", tsk_getu32(fs->endian, entry.cat.std.perm.special.raw)); } else if ((tsk_getu32(fs->endian, entry.cat.std.u_info.file_type) == HFS_HARDLINK_FILE_TYPE) && (tsk_getu32(fs->endian, entry.cat.std.u_info.file_cr) == HFS_HARDLINK_FILE_CREATOR)) { // technically, the creation date of this item should be the same as either the // creation date of the "HFS+ Private Data" folder or the creation date of the root folder tsk_fprintf(hFile, "Hard link inode number\t %" PRIu32 "\n", tsk_getu32(fs->endian, entry.cat.std.perm.special.inum)); } tsk_fprintf(hFile, "Admin flags: %" PRIu8, entry.cat.std.perm.a_flags); if (entry.cat.std.perm.a_flags != 0) { tsk_fprintf(hFile, " - "); if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_ARCHIVED) tsk_fprintf(hFile, "archived "); if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_IMMUTABLE) tsk_fprintf(hFile, "immutable "); if (entry.cat.std.perm.a_flags & HFS_PERM_AFLAG_APPEND) tsk_fprintf(hFile, "append-only "); } tsk_fprintf(hFile, "\n"); tsk_fprintf(hFile, "Owner flags: %" PRIu8, entry.cat.std.perm.o_flags); if (entry.cat.std.perm.o_flags != 0) { tsk_fprintf(hFile, " - "); if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_NODUMP) tsk_fprintf(hFile, "no-dump "); if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_IMMUTABLE) tsk_fprintf(hFile, "immutable "); if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_APPEND) tsk_fprintf(hFile, "append-only "); if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_OPAQUE) tsk_fprintf(hFile, "opaque "); if (entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) tsk_fprintf(hFile, "compressed "); } tsk_fprintf(hFile, "\n"); if (tsk_getu16(fs->endian, entry.cat.std.flags) & HFS_FILE_FLAG_LOCKED) tsk_fprintf(hFile, "Locked\n"); if (tsk_getu16(fs->endian, entry.cat.std.flags) & HFS_FILE_FLAG_ATTR) tsk_fprintf(hFile, "Has extended attributes\n"); if (tsk_getu16(fs->endian, entry.cat.std.flags) & HFS_FILE_FLAG_ACL) tsk_fprintf(hFile, "Has security data (ACLs)\n"); // File_type and file_cr are not relevant for Folders if ( !TSK_FS_IS_DIR_META(fs_file->meta->type)){ int windx; // loop index tsk_fprintf(hFile, "File type:\t%04" PRIx32 " ", tsk_getu32(fs->endian, entry.cat.std.u_info.file_type)); for (windx = 0; windx < 4; ++windx) { uint8_t cu = entry.cat.std.u_info.file_type[windx]; if (cu >= 32 && cu <= 126) tsk_fprintf(hFile, "%c", (char) cu); else tsk_fprintf(hFile, " "); } tsk_fprintf(hFile, "\n"); tsk_fprintf(hFile, "File creator:\t%04" PRIx32 " ", tsk_getu32(fs->endian, entry.cat.std.u_info.file_cr)); for (windx = 0; windx < 4; ++windx) { uint8_t cu = entry.cat.std.u_info.file_cr[windx]; if (cu >= 32 && cu <= 126) tsk_fprintf(hFile, "%c", (char) cu); else tsk_fprintf(hFile, " "); } tsk_fprintf(hFile, "\n"); } // END if(not folder) if (tsk_getu16(fs->endian, entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_NAME_LOCKED) tsk_fprintf(hFile, "Name locked\n"); if (tsk_getu16(fs->endian, entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_HAS_BUNDLE) tsk_fprintf(hFile, "Has bundle\n"); if (tsk_getu16(fs->endian, entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_INVISIBLE) tsk_fprintf(hFile, "Is invisible\n"); if (tsk_getu16(fs->endian, entry.cat.std.u_info.flags) & HFS_FINDER_FLAG_IS_ALIAS) tsk_fprintf(hFile, "Is alias\n"); tsk_fprintf(hFile, "Text encoding:\t%" PRIx32 " = %s\n", tsk_getu32(fs->endian, entry.cat.std.text_enc), text_encoding_name(tsk_getu32(fs->endian, entry.cat.std.text_enc))); if (tsk_getu16(fs->endian, entry.cat.std.rec_type) == HFS_FILE_RECORD) { tsk_fprintf(hFile, "Resource fork size:\t%" PRIu64 "\n", tsk_getu64(fs->endian, entry.cat.resource.logic_sz)); } } if (sec_skew != 0) { tsk_fprintf(hFile, "\nAdjusted times:\n"); if (fs_file->meta->mtime) fs_file->meta->mtime -= sec_skew; if (fs_file->meta->atime) fs_file->meta->atime -= sec_skew; if (fs_file->meta->ctime) fs_file->meta->ctime -= sec_skew; if (fs_file->meta->crtime) fs_file->meta->crtime -= sec_skew; if (fs_file->meta->time2.hfs.bkup_time) fs_file->meta->time2.hfs.bkup_time -= sec_skew; tsk_fprintf(hFile, "Created:\t%s\n", tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf)); tsk_fprintf(hFile, "Content Modified:\t%s\n", tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf)); tsk_fprintf(hFile, "Attributes Modified:\t%s\n", tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf)); tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_file->meta->atime, timeBuf)); tsk_fprintf(hFile, "Backed Up:\t%s\n", tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time, timeBuf)); if (fs_file->meta->mtime) fs_file->meta->mtime += sec_skew; if (fs_file->meta->atime) fs_file->meta->atime += sec_skew; if (fs_file->meta->ctime) fs_file->meta->ctime += sec_skew; if (fs_file->meta->crtime) fs_file->meta->crtime += sec_skew; if (fs_file->meta->time2.hfs.bkup_time) fs_file->meta->time2.hfs.bkup_time += sec_skew; tsk_fprintf(hFile, "\nOriginal times:\n"); } else { tsk_fprintf(hFile, "\nTimes:\n"); } tsk_fprintf(hFile, "Created:\t%s\n", tsk_fs_time_to_str(fs_file->meta->crtime, timeBuf)); tsk_fprintf(hFile, "Content Modified:\t%s\n", tsk_fs_time_to_str(fs_file->meta->mtime, timeBuf)); tsk_fprintf(hFile, "Attributes Modified:\t%s\n", tsk_fs_time_to_str(fs_file->meta->ctime, timeBuf)); tsk_fprintf(hFile, "Accessed:\t%s\n", tsk_fs_time_to_str(fs_file->meta->atime, timeBuf)); tsk_fprintf(hFile, "Backed Up:\t%s\n", tsk_fs_time_to_str(fs_file->meta->time2.hfs.bkup_time, timeBuf)); // IF this is a regular file, then print out the blocks of the DATA and RSRC forks. if (tsk_getu16(fs->endian, entry.cat.std.rec_type) == HFS_FILE_RECORD) { // Only print DATA fork blocks if this file is NOT compressed // N.B., a compressed file has no data fork, and tsk_fs_file_walk() will // do the wrong thing! if (!(entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED)) { if (!(istat_flags & TSK_FS_ISTAT_RUNLIST)) { tsk_fprintf(hFile, "\nData Fork Blocks:\n"); print.idx = 0; print.hFile = hFile; print.accumulating = FALSE; print.startBlock = 0; print.blockCount = 0; if (tsk_fs_file_walk_type(fs_file, TSK_FS_ATTR_TYPE_HFS_DATA, HFS_FS_ATTR_ID_DATA, (TSK_FS_FILE_WALK_FLAG_AONLY | TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file data fork\n"); tsk_error_print(hFile); tsk_error_reset(); } else { output_print_addr(&print); if (print.idx != 0) tsk_fprintf(hFile, "\n"); } } } // Only print out the blocks of the Resource fork if it has nonzero size if (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) > 0) { if (! (istat_flags & TSK_FS_ISTAT_RUNLIST)) { tsk_fprintf(hFile, "\nResource Fork Blocks:\n"); print.idx = 0; print.hFile = hFile; print.accumulating = FALSE; print.startBlock = 0; print.blockCount = 0; if (tsk_fs_file_walk_type(fs_file, TSK_FS_ATTR_TYPE_HFS_RSRC, HFS_FS_ATTR_ID_RSRC, (TSK_FS_FILE_WALK_FLAG_AONLY | TSK_FS_FILE_WALK_FLAG_SLACK), print_addr_act, (void *)&print)) { tsk_fprintf(hFile, "\nError reading file resource fork\n"); tsk_error_print(hFile); tsk_error_reset(); } else { output_print_addr(&print); if (print.idx != 0) tsk_fprintf(hFile, "\n"); } } } } // Force the loading of all attributes. (void) tsk_fs_file_attr_get(fs_file); /* Print all of the attributes */ tsk_fprintf(hFile, "\nAttributes: \n"); if (fs_file->meta->attr) { int cnt, i; // cycle through the attributes cnt = tsk_fs_file_attr_getsize(fs_file); for (i = 0; i < cnt; ++i) { const char *type; // type of the attribute as a string const TSK_FS_ATTR *fs_attr = tsk_fs_file_attr_get_idx(fs_file, i); if (!fs_attr) continue; type = hfs_attrTypeName((uint32_t) fs_attr->type); // We will need to do something better than this, in the end. //type = "Data"; /* print the layout if it is non-resident and not "special" */ if (fs_attr->flags & TSK_FS_ATTR_NONRES) { //NTFS_PRINT_ADDR print_addr; tsk_fprintf(hFile, "Type: %s (%" PRIu32 "-%" PRIu16 ") Name: %s Non-Resident%s%s%s size: %" PRIuOFF " init_size: %" PRIuOFF "\n", type, fs_attr->type, fs_attr->id, (fs_attr->name) ? fs_attr->name : "N/A", (fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" : "", (fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" : "", (fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" : "", fs_attr->size, fs_attr->nrd.initsize); if (istat_flags & TSK_FS_ISTAT_RUNLIST) { if (tsk_fs_attr_print(fs_attr, hFile)) { tsk_fprintf(hFile, "\nError creating run lists\n"); tsk_error_print(hFile); tsk_error_reset(); } } } // END: non-resident attribute case else { tsk_fprintf(hFile, "Type: %s (%" PRIu32 "-%" PRIu16 ") Name: %s Resident%s%s%s size: %" PRIuOFF "\n", type, fs_attr->type, fs_attr->id, (fs_attr->name) ? fs_attr->name : "N/A", (fs_attr->flags & TSK_FS_ATTR_ENC) ? ", Encrypted" : "", (fs_attr->flags & TSK_FS_ATTR_COMP) ? ", Compressed" : "", (fs_attr->flags & TSK_FS_ATTR_SPARSE) ? ", Sparse" : "", fs_attr->size); if (fs_attr->type == TSK_FS_ATTR_TYPE_HFS_COMP_REC) { if (compressionAttr == NULL) { compressionAttr = fs_attr; } else { // Problem: there is more than one compression attribute error_detected(TSK_ERR_FS_CORRUPT, "hfs_istat: more than one compression attribute"); return 1; } } } // END: else (RESIDENT attribute case) } // END: for(;;) loop over attributes } // END: if(fs_file->meta->attr is non-NULL) if ((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) && (compressionAttr == NULL)) tsk_fprintf(hFile, "WARNING: Compression Flag is set, but there" " is no compression record for this file.\n"); if (((entry.cat.std.perm.o_flags & HFS_PERM_OFLAG_COMPRESSED) == 0) && (compressionAttr != NULL)) tsk_fprintf(hFile, "WARNING: Compression Flag is NOT set, but there" " is a compression record for this file.\n"); // IF this is a compressed file if (compressionAttr != NULL) { const TSK_FS_ATTR *fs_attr = compressionAttr; int attrReadResult; DECMPFS_DISK_HEADER *cmph; uint32_t cmpType; uint64_t uncSize; uint64_t cmpSize = 0; // Read the attribute. It cannot be too large because it is stored in // a btree node char *aBuf = (char *) tsk_malloc((size_t) fs_attr->size); if (aBuf == NULL) { error_returned("hfs_istat: space for a compression attribute"); return 1; } attrReadResult = tsk_fs_attr_read(fs_attr, (TSK_OFF_T) 0, aBuf, (size_t) fs_attr->size, (TSK_FS_FILE_READ_FLAG_ENUM) 0x00); if (attrReadResult == -1) { error_returned("hfs_istat: reading the compression attribute"); free(aBuf); return 1; } else if (attrReadResult < fs_attr->size) { error_detected(TSK_ERR_FS_READ, "hfs_istat: could not read the whole compression attribute"); free(aBuf); return 1; } // Now, cast the attr into a compression header cmph = (DECMPFS_DISK_HEADER *) aBuf; cmpType = tsk_getu32(TSK_LIT_ENDIAN, cmph->compression_type); uncSize = tsk_getu64(TSK_LIT_ENDIAN, cmph->uncompressed_size); tsk_fprintf(hFile, "\nCompressed File:\n"); tsk_fprintf(hFile, " Uncompressed size: %llu\n", uncSize); switch (cmpType) { case DECMPFS_TYPE_ZLIB_ATTR: // Data is inline { // size of header, with indicator byte if uncompressed uint32_t off = (cmph->attr_bytes[0] & 0x0F) == 0x0F ? 17 : 16; cmpSize = fs_attr->size - off; tsk_fprintf(hFile, " Data follows compression record in the CMPF attribute\n" " %" PRIu64 " bytes of data at offset %u, %s compressed\n", cmpSize, off, off == 16 ? "zlib" : "not"); } break; case DECMPFS_TYPE_LZVN_ATTR: // Data is inline { // size of header, with indicator byte if uncompressed uint32_t off = cmph->attr_bytes[0] == 0x06 ? 17 : 16; cmpSize = fs_attr->size - off; tsk_fprintf(hFile, " Data follows compression record in the CMPF attribute\n" " %" PRIu64 " bytes of data at offset %u, %s compressed\n", cmpSize, off, off == 16 ? "lzvn" : "not"); } break; case DECMPFS_TYPE_ZLIB_RSRC: // Data is zlib compressed in the resource fork tsk_fprintf(hFile, " Data is zlib compressed in the resource fork\n"); break; case DECMPFS_TYPE_LZVN_RSRC: // Data is lzvn compressed in the resource fork tsk_fprintf(hFile, " Data is lzvn compressed in the resource fork\n"); break; default: tsk_fprintf(hFile, " Compression type is %u: UNKNOWN\n", cmpType); } free(aBuf); if ((cmpType == DECMPFS_TYPE_ZLIB_RSRC || cmpType == DECMPFS_TYPE_LZVN_RSRC) && (tsk_getu64(fs->endian, entry.cat.resource.logic_sz) == 0)) tsk_fprintf(hFile, "WARNING: Compression record indicates compressed data" " in the RSRC Fork, but that fork is empty.\n"); } // This will return NULL if there is an error, or if there are no resources rd = hfs_parse_resource_fork(fs_file); // TODO: Should check the errnum here to see if there was an error if (rd != NULL) { tsk_fprintf(hFile, "\nResources:\n"); while (rd) { tsk_fprintf(hFile, " Type: %s \tID: %-5u \tOffset: %-5u \tSize: %-5u \tName: %s\n", rd->type, rd->id, rd->offset, rd->length, rd->name); rd = rd->next; } } // This is OK to call with NULL free_res_descriptor(rd); tsk_fs_file_close(fs_file); return 0; } static TSK_FS_ATTR_TYPE_ENUM hfs_get_default_attr_type(const TSK_FS_FILE * a_file) { // The HFS+ special files have a default attr type of "Default" TSK_INUM_T inum = a_file->meta->addr; if (inum == 3 || // Extents File inum == 4 || // Catalog File inum == 5 || // Bad Blocks File inum == 6 || // Block Map (Allocation File) inum == 7 || // Startup File inum == 8 || // Attributes File inum == 14 || // Not sure if these two will actually work. I don't see inum == 15) // any code to load the attrs of these files, if they exist. return TSK_FS_ATTR_TYPE_DEFAULT; // The "regular" files and symbolic links have a DATA fork with type "DATA" if (a_file->meta->type == TSK_FS_META_TYPE_REG || a_file->meta->type == TSK_FS_META_TYPE_LNK) // This should be an HFS-specific type. return TSK_FS_ATTR_TYPE_HFS_DATA; // We've got to return *something* for every file, so we return this. return TSK_FS_ATTR_TYPE_DEFAULT; } static void hfs_close(TSK_FS_INFO * fs) { HFS_INFO *hfs = (HFS_INFO *) fs; // We'll grab this lock a bit early. tsk_take_lock(&(hfs->metadata_dir_cache_lock)); fs->tag = 0; free(hfs->fs); if (hfs->catalog_file) { tsk_fs_file_close(hfs->catalog_file); hfs->catalog_attr = NULL; } if (hfs->blockmap_file) { tsk_fs_file_close(hfs->blockmap_file); hfs->blockmap_attr = NULL; } if (hfs->meta_dir) { tsk_fs_dir_close(hfs->meta_dir); hfs->meta_dir = NULL; } if (hfs->dir_meta_dir) { tsk_fs_dir_close(hfs->dir_meta_dir); hfs->dir_meta_dir = NULL; } if (hfs->extents_file) { tsk_fs_file_close(hfs->extents_file); hfs->extents_file = NULL; } tsk_release_lock(&(hfs->metadata_dir_cache_lock)); tsk_deinit_lock(&(hfs->metadata_dir_cache_lock)); tsk_fs_free((TSK_FS_INFO *)hfs); } /* hfs_open - open an hfs file system * * Return NULL on error (or not an HFS or HFS+ file system) * */ TSK_FS_INFO * hfs_open(TSK_IMG_INFO * img_info, TSK_OFF_T offset, TSK_FS_TYPE_ENUM ftype, uint8_t test) { HFS_INFO *hfs; unsigned int len; TSK_FS_INFO *fs; ssize_t cnt; TSK_FS_FILE *file; // The root directory, or the metadata directories TSK_INUM_T inum; // The inum (or CNID) of the metadata directories int8_t result; // of tsk_fs_path2inum() tsk_error_reset(); if (TSK_FS_TYPE_ISHFS(ftype) == 0) { tsk_error_set_errno(TSK_ERR_FS_ARG); tsk_error_set_errstr("Invalid FS Type in hfs_open"); return NULL; } if ((hfs = (HFS_INFO *) tsk_fs_malloc(sizeof(HFS_INFO))) == NULL) return NULL; fs = &(hfs->fs_info); fs->ftype = TSK_FS_TYPE_HFS; fs->duname = "Allocation Block"; fs->tag = TSK_FS_INFO_TAG; fs->flags = 0; fs->img_info = img_info; fs->offset = offset; /* * Read the superblock. */ len = sizeof(hfs_plus_vh); if ((hfs->fs = (hfs_plus_vh *) tsk_malloc(len)) == NULL) { fs->tag = 0; tsk_fs_free((TSK_FS_INFO *)hfs); return NULL; } if (hfs_checked_read_random(fs, (char *) hfs->fs, len, (TSK_OFF_T) HFS_VH_OFF)) { tsk_error_set_errstr2("hfs_open: superblock"); fs->tag = 0; free(hfs->fs); tsk_fs_free((TSK_FS_INFO *)hfs); return NULL; } /* * Verify we are looking at an HFS+ image */ if (tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSPLUS) && tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFSX) && tsk_fs_guessu16(fs, hfs->fs->signature, HFS_VH_SIG_HFS)) { fs->tag = 0; free(hfs->fs); tsk_fs_free((TSK_FS_INFO *)hfs); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr("not an HFS+ file system (magic)"); return NULL; } /* * Handle an HFS-wrapped HFS+ image, which is a HFS volume that contains * the HFS+ volume inside of it. */ if (tsk_getu16(fs->endian, hfs->fs->signature) == HFS_VH_SIG_HFS) { hfs_mdb *wrapper_sb = (hfs_mdb *) hfs->fs; // Verify that we are setting a wrapper and not a normal HFS volume if ((tsk_getu16(fs->endian, wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSPLUS) || (tsk_getu16(fs->endian, wrapper_sb->drEmbedSigWord) == HFS_VH_SIG_HFSX)) { TSK_FS_INFO *fs_info2; // offset in sectors to start of first HFS block uint16_t drAlBlSt = tsk_getu16(fs->endian, wrapper_sb->drAlBlSt); // size of each HFS block uint32_t drAlBlkSiz = tsk_getu32(fs->endian, wrapper_sb->drAlBlkSiz); // start of embedded FS uint16_t startBlock = tsk_getu16(fs->endian, wrapper_sb->drEmbedExtent_startBlock); // calculate the offset; 512 here is intentional. // TN1150 says "The drAlBlSt field contains the offset, in // 512-byte blocks, of the wrapper's allocation block 0 relative // to the start of the volume" TSK_OFF_T hfsplus_offset = (drAlBlSt * (TSK_OFF_T) 512) + (drAlBlkSiz * (TSK_OFF_T) startBlock); if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: HFS+/HFSX within HFS wrapper at byte offset %" PRIuOFF "\n", hfsplus_offset); fs->tag = 0; free(hfs->fs); tsk_fs_free((TSK_FS_INFO *)hfs); /* just re-open with the new offset, then record the offset */ if (hfsplus_offset == 0) { tsk_error_set_errno(TSK_ERR_FS_CORRUPT); tsk_error_set_errstr("HFS+ offset is zero"); return NULL; } fs_info2 = hfs_open(img_info, offset + hfsplus_offset, ftype, test); if (fs_info2) ((HFS_INFO *) fs_info2)->hfs_wrapper_offset = hfsplus_offset; return fs_info2; } else { fs->tag = 0; free(hfs->fs); tsk_fs_free((TSK_FS_INFO *)hfs); tsk_error_set_errno(TSK_ERR_FS_MAGIC); tsk_error_set_errstr ("HFS file systems (other than wrappers HFS+/HFSX file systems) are not supported"); return NULL; } } fs->block_count = tsk_getu32(fs->endian, hfs->fs->blk_cnt); fs->first_block = 0; fs->last_block = fs->last_block_act = fs->block_count - 1; /* this isn't really accurate; fs->block_size reports only the size of the allocation block; the size of the device block has to be found from the device (allocation block size should always be larger than device block size and an even multiple of the device block size) */ fs->dev_bsize = fs->block_size = tsk_getu32(fs->endian, hfs->fs->blk_sz); // determine the last block we have in this image if (fs->block_size <= 1) { fs->tag = 0; free(hfs->fs); tsk_fs_free((TSK_FS_INFO *)hfs); tsk_error_set_errno(TSK_ERR_FS_CORRUPT); tsk_error_set_errstr("HFS+ allocation block size too small"); return NULL; } if ((TSK_DADDR_T) ((img_info->size - offset) / fs->block_size) < fs->block_count) fs->last_block_act = (img_info->size - offset) / fs->block_size - 1; // Initialize the lock tsk_init_lock(&(hfs->metadata_dir_cache_lock)); /* * Set function pointers */ fs->inode_walk = hfs_inode_walk; fs->block_walk = hfs_block_walk; fs->block_getflags = hfs_block_getflags; fs->load_attrs = hfs_load_attrs; fs->get_default_attr_type = hfs_get_default_attr_type; fs->file_add_meta = hfs_inode_lookup; fs->dir_open_meta = hfs_dir_open_meta; fs->fsstat = hfs_fsstat; fs->fscheck = hfs_fscheck; fs->istat = hfs_istat; fs->close = hfs_close; // lazy loading of block map hfs->blockmap_file = NULL; hfs->blockmap_attr = NULL; hfs->blockmap_cache_start = -1; hfs->blockmap_cache_len = 0; fs->first_inum = HFS_ROOT_INUM; fs->root_inum = HFS_ROOT_INUM; fs->last_inum = HFS_FIRST_USER_CNID - 1; // we will later increase this fs->inum_count = fs->last_inum - fs->first_inum + 1; /* We will load the extents file data when we need it */ hfs->extents_file = NULL; hfs->extents_attr = NULL; if (tsk_getu32(fs->endian, hfs->fs->start_file.extents[0].blk_cnt) == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Optional Startup File is not present.\n"); hfs->has_startup_file = FALSE; } else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Startup File is present.\n"); hfs->has_startup_file = TRUE; } if (tsk_getu32(fs->endian, hfs->fs->ext_file.extents[0].blk_cnt) == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Optional Extents File (and Badblocks File) is not present.\n"); hfs->has_extents_file = FALSE; } else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Extents File (and BadBlocks File) is present.\n"); hfs->has_extents_file = TRUE; } if (tsk_getu32(fs->endian, hfs->fs->attr_file.extents[0].blk_cnt) == 0) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Optional Attributes File is not present.\n"); hfs->has_attributes_file = FALSE; } else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Attributes File is present.\n"); hfs->has_attributes_file = TRUE; } /* Load the catalog file though */ if ((hfs->catalog_file = tsk_fs_file_open_meta(fs, NULL, HFS_CATALOG_FILE_ID)) == NULL) { hfs_close(fs); return NULL; } /* cache the data attribute */ hfs->catalog_attr = tsk_fs_attrlist_get(hfs->catalog_file->meta->attr, TSK_FS_ATTR_TYPE_DEFAULT); if (!hfs->catalog_attr) { hfs_close(fs); tsk_error_errstr2_concat (" - Data Attribute not found in Catalog File"); return NULL; } // cache the catalog file header cnt = tsk_fs_attr_read(hfs->catalog_attr, 14, (char *) &(hfs->catalog_header), sizeof(hfs_btree_header_record), 0); if (cnt != sizeof(hfs_btree_header_record)) { if (cnt >= 0) { tsk_error_reset(); tsk_error_set_errno(TSK_ERR_FS_READ); } hfs_close(fs); tsk_error_set_errstr2("hfs_open: Error reading catalog header"); return NULL; } if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSPLUS) hfs->is_case_sensitive = 0; else if (tsk_getu16(fs->endian, hfs->fs->version) == HFS_VH_VER_HFSX) { if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_SENS) hfs->is_case_sensitive = 1; else if (hfs->catalog_header.compType == HFS_BT_HEAD_COMP_INSENS) hfs->is_case_sensitive = 0; else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: invalid value (0x%02" PRIx8 ") for key compare type; using case-insensitive\n", hfs->catalog_header.compType); hfs->is_case_sensitive = 0; } } else { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: unknown HFS+/HFSX version (%" PRIu16 "\n", tsk_getu16(fs->endian, hfs->fs->version)); hfs->is_case_sensitive = 0; } // update the numbers. fs->last_inum = hfs_find_highest_inum(hfs); fs->inum_count = fs->last_inum + 1; snprintf((char *) fs->fs_id, 17, "%08" PRIx32 "%08" PRIx32, tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID1]), tsk_getu32(fs->endian, hfs->fs->finder_info[HFS_VH_FI_ID2])); fs->fs_id_used = 16; /* journal */ fs->jblk_walk = hfs_jblk_walk; fs->jentry_walk = hfs_jentry_walk; fs->jopen = hfs_jopen; fs->name_cmp = hfs_name_cmp; fs->journ_inum = 0; /* Creation Times */ // First, the root file = tsk_fs_file_open_meta(fs, NULL, 2); if (file != NULL) { hfs->root_crtime = file->meta->crtime; hfs->has_root_crtime = TRUE; tsk_fs_file_close(file); } else { hfs->has_root_crtime = FALSE; } file = NULL; // disable hard link traversal while finding the hard // link directories themselves (to prevent problems if // there are hard links in the root directory) hfs->meta_inum = 0; hfs->meta_dir_inum = 0; // Now the (file) metadata directory // The metadata directory is a sub-directory of the root. Its name begins with four nulls, followed // by "HFS+ Private Data". The file system parsing code replaces nulls in filenames with UTF8_NULL_REPLACE. // In the released version of TSK, this replacement is the character '^'. // NOTE: There is a standard Unicode replacement which is 0xfffd in UTF16 and 0xEF 0xBF 0xBD in UTF8. // Systems that require the standard definition can redefine UTF8_NULL_REPLACE and UTF16_NULL_REPLACE // in tsk_hfs.h hfs->has_meta_crtime = FALSE; result = tsk_fs_path2inum(fs, "/" UTF8_NULL_REPLACE UTF8_NULL_REPLACE UTF8_NULL_REPLACE UTF8_NULL_REPLACE "HFS+ Private Data", &inum, NULL); if (result == 0) { TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum); if (file_tmp != NULL) { hfs->meta_crtime = file_tmp->meta->crtime; hfs->has_meta_crtime = TRUE; hfs->meta_inum = inum; tsk_fs_file_close(file_tmp); } } // Now, the directory metadata directory // The "directory" metadata directory, where hardlinked directories actually live, is a subdirectory // of the root. The beginning of the name of this directory is ".HFS+ Private Directory Data" which // is followed by a carriage return (ASCII 13). hfs->has_meta_dir_crtime = FALSE; result = tsk_fs_path2inum(fs, "/.HFS+ Private Directory Data\r", &inum, NULL); if (result == 0) { TSK_FS_FILE *file_tmp = tsk_fs_file_open_meta(fs, NULL, inum); if (file_tmp != NULL) { hfs->metadir_crtime = file_tmp->meta->crtime; hfs->has_meta_dir_crtime = TRUE; hfs->meta_dir_inum = inum; tsk_fs_file_close(file_tmp); } } if (hfs->has_root_crtime && hfs->has_meta_crtime && hfs->has_meta_dir_crtime) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Creation times for key folders have been read and cached.\n"); } if (!hfs->has_root_crtime) { if (tsk_verbose) tsk_fprintf(stderr, "hfs_open: Warning: Could not open the root directory. " "Hard link detection and some other functions will be impaired\n"); } else if (tsk_verbose) { tsk_fprintf(stderr, "hfs_open: The root directory is accessible.\n"); } if (tsk_verbose) { if (hfs->has_meta_crtime) tsk_fprintf(stderr, "hfs_open: \"/^^^^HFS+ Private Data\" metadata folder is accessible.\n"); else tsk_fprintf(stderr, "hfs_open: Optional \"^^^^HFS+ Private Data\" metadata folder is not accessible, or does not exist.\n"); if (hfs->has_meta_dir_crtime) tsk_fprintf(stderr, "hfs_open: \"/HFS+ Private Directory Data^\" metadata folder is accessible.\n"); else tsk_fprintf(stderr, "hfs_open: Optional \"/HFS+ Private Directory Data^\" metadata folder is not accessible, or does not exist.\n"); } // These caches will be set, if they are needed. hfs->meta_dir = NULL; hfs->dir_meta_dir = NULL; return fs; } /* * Error Handling */ /** * Call this when an error is first detected. It sets the error code and it also * sets the primary error string, describing the lowest level of error. (Actually, * it appends to the error string.) * * If the error code is already set, then this appends to the primary error * string an hex representation of the new error code, plus the new error message. * * @param errnum The desired error code * @param errstr The format string for the error message */ void error_detected(uint32_t errnum, char *errstr, ...) { va_list args; va_start(args, errstr); { TSK_ERROR_INFO *errInfo = tsk_error_get_info(); char *loc_errstr = errInfo->errstr; if (errInfo->t_errno == 0) errInfo->t_errno = errnum; else { //This should not happen! We don't want to wipe out the existing error //code, so we write the new code into the error string, in hex. int sl = strlen(errstr); snprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl, " Next errnum: 0x%x ", errnum); } if (errstr != NULL) { int sl = strlen(loc_errstr); vsnprintf(loc_errstr + sl, TSK_ERROR_STRING_MAX_LENGTH - sl, errstr, args); } } va_end(args); } /** * Call this when a called TSK function returns an error. Presumably, that * function will have set the error code and the primary error string. This * *appends* to the secondary error string. It should be called to describe * the context of the call. If no error code has been set, then this sets a * default code so that it is not zero. * * @param errstr The format string for the error message */ void error_returned(char *errstr, ...) { va_list args; va_start(args, errstr); { TSK_ERROR_INFO *errInfo = tsk_error_get_info(); char *loc_errstr2 = errInfo->errstr2; if (errInfo->t_errno == 0) errInfo->t_errno = TSK_ERR_AUX_GENERIC; if (errstr != NULL) { int sl = strlen(loc_errstr2); vsnprintf(loc_errstr2 + sl, TSK_ERROR_STRING_MAX_LENGTH - sl, errstr, args); } } va_end(args); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_711_0
crossvul-cpp_data_bad_3153_1
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef AMIGA # include <time.h> /* for time() */ #endif /* * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred) * It has been changed beyond recognition since then. * * Differences between version 7.4 and 8.x can be found with ":help version8". * Differences between version 6.4 and 7.x can be found with ":help version7". * Differences between version 5.8 and 6.x can be found with ":help version6". * Differences between version 4.x and 5.x can be found with ":help version5". * Differences between version 3.0 and 4.x can be found with ":help version4". * All the remarks about older versions have been removed, they are not very * interesting. */ #include "version.h" char *Version = VIM_VERSION_SHORT; static char *mediumVersion = VIM_VERSION_MEDIUM; #if defined(HAVE_DATE_TIME) || defined(PROTO) # if (defined(VMS) && defined(VAXC)) || defined(PROTO) char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__) + sizeof(__TIME__) + 3]; void make_version(void) { /* * Construct the long version string. Necessary because * VAX C can't catenate strings in the preprocessor. */ strcpy(longVersion, VIM_VERSION_LONG_DATE); strcat(longVersion, __DATE__); strcat(longVersion, " "); strcat(longVersion, __TIME__); strcat(longVersion, ")"); } # else char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")"; # endif #else char *longVersion = VIM_VERSION_LONG; #endif static void list_features(void); static void version_msg(char *s); static char *(features[]) = { #ifdef HAVE_ACL "+acl", #else "-acl", #endif #ifdef AMIGA /* only for Amiga systems */ # ifdef FEAT_ARP "+ARP", # else "-ARP", # endif #endif #ifdef FEAT_ARABIC "+arabic", #else "-arabic", #endif #ifdef FEAT_AUTOCMD "+autocmd", #else "-autocmd", #endif #ifdef FEAT_BEVAL "+balloon_eval", #else "-balloon_eval", #endif #ifdef FEAT_BROWSE "+browse", #else "-browse", #endif #ifdef NO_BUILTIN_TCAPS "-builtin_terms", #endif #ifdef SOME_BUILTIN_TCAPS "+builtin_terms", #endif #ifdef ALL_BUILTIN_TCAPS "++builtin_terms", #endif #ifdef FEAT_BYTEOFF "+byte_offset", #else "-byte_offset", #endif #ifdef FEAT_JOB_CHANNEL "+channel", #else "-channel", #endif #ifdef FEAT_CINDENT "+cindent", #else "-cindent", #endif #ifdef FEAT_CLIENTSERVER "+clientserver", #else "-clientserver", #endif #ifdef FEAT_CLIPBOARD "+clipboard", #else "-clipboard", #endif #ifdef FEAT_CMDL_COMPL "+cmdline_compl", #else "-cmdline_compl", #endif #ifdef FEAT_CMDHIST "+cmdline_hist", #else "-cmdline_hist", #endif #ifdef FEAT_CMDL_INFO "+cmdline_info", #else "-cmdline_info", #endif #ifdef FEAT_COMMENTS "+comments", #else "-comments", #endif #ifdef FEAT_CONCEAL "+conceal", #else "-conceal", #endif #ifdef FEAT_CRYPT "+cryptv", #else "-cryptv", #endif #ifdef FEAT_CSCOPE "+cscope", #else "-cscope", #endif #ifdef FEAT_CURSORBIND "+cursorbind", #else "-cursorbind", #endif #ifdef CURSOR_SHAPE "+cursorshape", #else "-cursorshape", #endif #if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG) "+dialog_con_gui", #else # if defined(FEAT_CON_DIALOG) "+dialog_con", # else # if defined(FEAT_GUI_DIALOG) "+dialog_gui", # else "-dialog", # endif # endif #endif #ifdef FEAT_DIFF "+diff", #else "-diff", #endif #ifdef FEAT_DIGRAPHS "+digraphs", #else "-digraphs", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_DIRECTX "+directx", # else "-directx", # endif #endif #ifdef FEAT_DND "+dnd", #else "-dnd", #endif #ifdef EBCDIC "+ebcdic", #else "-ebcdic", #endif #ifdef FEAT_EMACS_TAGS "+emacs_tags", #else "-emacs_tags", #endif #ifdef FEAT_EVAL "+eval", #else "-eval", #endif "+ex_extra", #ifdef FEAT_SEARCH_EXTRA "+extra_search", #else "-extra_search", #endif #ifdef FEAT_FKMAP "+farsi", #else "-farsi", #endif #ifdef FEAT_SEARCHPATH "+file_in_path", #else "-file_in_path", #endif #ifdef FEAT_FIND_ID "+find_in_path", #else "-find_in_path", #endif #ifdef FEAT_FLOAT "+float", #else "-float", #endif #ifdef FEAT_FOLDING "+folding", #else "-folding", #endif #ifdef FEAT_FOOTER "+footer", #else "-footer", #endif /* only interesting on Unix systems */ #if !defined(USE_SYSTEM) && defined(UNIX) "+fork()", #endif #ifdef FEAT_GETTEXT # ifdef DYNAMIC_GETTEXT "+gettext/dyn", # else "+gettext", # endif #else "-gettext", #endif #ifdef FEAT_HANGULIN "+hangul_input", #else "-hangul_input", #endif #if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV) # ifdef DYNAMIC_ICONV "+iconv/dyn", # else "+iconv", # endif #else "-iconv", #endif #ifdef FEAT_INS_EXPAND "+insert_expand", #else "-insert_expand", #endif #ifdef FEAT_JOB_CHANNEL "+job", #else "-job", #endif #ifdef FEAT_JUMPLIST "+jumplist", #else "-jumplist", #endif #ifdef FEAT_KEYMAP "+keymap", #else "-keymap", #endif #ifdef FEAT_EVAL "+lambda", #else "-lambda", #endif #ifdef FEAT_LANGMAP "+langmap", #else "-langmap", #endif #ifdef FEAT_LIBCALL "+libcall", #else "-libcall", #endif #ifdef FEAT_LINEBREAK "+linebreak", #else "-linebreak", #endif #ifdef FEAT_LISP "+lispindent", #else "-lispindent", #endif #ifdef FEAT_LISTCMDS "+listcmds", #else "-listcmds", #endif #ifdef FEAT_LOCALMAP "+localmap", #else "-localmap", #endif #ifdef FEAT_LUA # ifdef DYNAMIC_LUA "+lua/dyn", # else "+lua", # endif #else "-lua", #endif #ifdef FEAT_MENU "+menu", #else "-menu", #endif #ifdef FEAT_SESSION "+mksession", #else "-mksession", #endif #ifdef FEAT_MODIFY_FNAME "+modify_fname", #else "-modify_fname", #endif #ifdef FEAT_MOUSE "+mouse", # ifdef FEAT_MOUSESHAPE "+mouseshape", # else "-mouseshape", # endif # else "-mouse", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "+mouse_dec", # else "-mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "+mouse_gpm", # else "-mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "+mouse_jsbterm", # else "-mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "+mouse_netterm", # else "-mouse_netterm", # endif #endif #ifdef __QNX__ # ifdef FEAT_MOUSE_PTERM "+mouse_pterm", # else "-mouse_pterm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_SGR "+mouse_sgr", # else "-mouse_sgr", # endif # ifdef FEAT_SYSMOUSE "+mouse_sysmouse", # else "-mouse_sysmouse", # endif # ifdef FEAT_MOUSE_URXVT "+mouse_urxvt", # else "-mouse_urxvt", # endif # ifdef FEAT_MOUSE_XTERM "+mouse_xterm", # else "-mouse_xterm", # endif #endif #ifdef FEAT_MBYTE_IME # ifdef DYNAMIC_IME "+multi_byte_ime/dyn", # else "+multi_byte_ime", # endif #else # ifdef FEAT_MBYTE "+multi_byte", # else "-multi_byte", # endif #endif #ifdef FEAT_MULTI_LANG "+multi_lang", #else "-multi_lang", #endif #ifdef FEAT_MZSCHEME # ifdef DYNAMIC_MZSCHEME "+mzscheme/dyn", # else "+mzscheme", # endif #else "-mzscheme", #endif #ifdef FEAT_NETBEANS_INTG "+netbeans_intg", #else "-netbeans_intg", #endif #ifdef FEAT_NUM64 "+num64", #else "-num64", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_OLE "+ole", # else "-ole", # endif #endif "+packages", #ifdef FEAT_PATH_EXTRA "+path_extra", #else "-path_extra", #endif #ifdef FEAT_PERL # ifdef DYNAMIC_PERL "+perl/dyn", # else "+perl", # endif #else "-perl", #endif #ifdef FEAT_PERSISTENT_UNDO "+persistent_undo", #else "-persistent_undo", #endif #ifdef FEAT_PRINTER # ifdef FEAT_POSTSCRIPT "+postscript", # else "-postscript", # endif "+printer", #else "-printer", #endif #ifdef FEAT_PROFILE "+profile", #else "-profile", #endif #ifdef FEAT_PYTHON # ifdef DYNAMIC_PYTHON "+python/dyn", # else "+python", # endif #else "-python", #endif #ifdef FEAT_PYTHON3 # ifdef DYNAMIC_PYTHON3 "+python3/dyn", # else "+python3", # endif #else "-python3", #endif #ifdef FEAT_QUICKFIX "+quickfix", #else "-quickfix", #endif #ifdef FEAT_RELTIME "+reltime", #else "-reltime", #endif #ifdef FEAT_RIGHTLEFT "+rightleft", #else "-rightleft", #endif #ifdef FEAT_RUBY # ifdef DYNAMIC_RUBY "+ruby/dyn", # else "+ruby", # endif #else "-ruby", #endif #ifdef FEAT_SCROLLBIND "+scrollbind", #else "-scrollbind", #endif #ifdef FEAT_SIGNS "+signs", #else "-signs", #endif #ifdef FEAT_SMARTINDENT "+smartindent", #else "-smartindent", #endif #ifdef STARTUPTIME "+startuptime", #else "-startuptime", #endif #ifdef FEAT_STL_OPT "+statusline", #else "-statusline", #endif #ifdef FEAT_SUN_WORKSHOP "+sun_workshop", #else "-sun_workshop", #endif #ifdef FEAT_SYN_HL "+syntax", #else "-syntax", #endif /* only interesting on Unix systems */ #if defined(USE_SYSTEM) && defined(UNIX) "+system()", #endif #ifdef FEAT_TAG_BINS "+tag_binary", #else "-tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "+tag_old_static", #else "-tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "+tag_any_white", #else "-tag_any_white", #endif #ifdef FEAT_TCL # ifdef DYNAMIC_TCL "+tcl/dyn", # else "+tcl", # endif #else "-tcl", #endif #ifdef FEAT_TERMGUICOLORS "+termguicolors", #else "-termguicolors", #endif #if defined(UNIX) /* only Unix can have terminfo instead of termcap */ # ifdef TERMINFO "+terminfo", # else "-terminfo", # endif #else /* unix always includes termcap support */ # ifdef HAVE_TGETENT "+tgetent", # else "-tgetent", # endif #endif #ifdef FEAT_TERMRESPONSE "+termresponse", #else "-termresponse", #endif #ifdef FEAT_TEXTOBJ "+textobjects", #else "-textobjects", #endif #ifdef FEAT_TIMERS "+timers", #else "-timers", #endif #ifdef FEAT_TITLE "+title", #else "-title", #endif #ifdef FEAT_TOOLBAR "+toolbar", #else "-toolbar", #endif #ifdef FEAT_USR_CMDS "+user_commands", #else "-user_commands", #endif #ifdef FEAT_WINDOWS "+vertsplit", #else "-vertsplit", #endif #ifdef FEAT_VIRTUALEDIT "+virtualedit", #else "-virtualedit", #endif "+visual", #ifdef FEAT_VISUALEXTRA "+visualextra", #else "-visualextra", #endif #ifdef FEAT_VIMINFO "+viminfo", #else "-viminfo", #endif #ifdef FEAT_VREPLACE "+vreplace", #else "-vreplace", #endif #ifdef FEAT_WILDIGN "+wildignore", #else "-wildignore", #endif #ifdef FEAT_WILDMENU "+wildmenu", #else "-wildmenu", #endif #ifdef FEAT_WINDOWS "+windows", #else "-windows", #endif #ifdef FEAT_WRITEBACKUP "+writebackup", #else "-writebackup", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_X11 "+X11", # else "-X11", # endif #endif #ifdef FEAT_XFONTSET "+xfontset", #else "-xfontset", #endif #ifdef FEAT_XIM "+xim", #else "-xim", #endif #ifdef WIN3264 # ifdef FEAT_XPM_W32 "+xpm_w32", # else "-xpm_w32", # endif #else # ifdef HAVE_XPM "+xpm", # else "-xpm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef USE_XSMP_INTERACT "+xsmp_interact", # else # ifdef USE_XSMP "+xsmp", # else "-xsmp", # endif # endif # ifdef FEAT_XCLIPBOARD "+xterm_clipboard", # else "-xterm_clipboard", # endif #endif #ifdef FEAT_XTERM_SAVE "+xterm_save", #else "-xterm_save", #endif NULL }; static int included_patches[] = { /* Add new patch number below this line */ /**/ 321, /**/ 320, /**/ 319, /**/ 318, /**/ 317, /**/ 316, /**/ 315, /**/ 314, /**/ 313, /**/ 312, /**/ 311, /**/ 310, /**/ 309, /**/ 308, /**/ 307, /**/ 306, /**/ 305, /**/ 304, /**/ 303, /**/ 302, /**/ 301, /**/ 300, /**/ 299, /**/ 298, /**/ 297, /**/ 296, /**/ 295, /**/ 294, /**/ 293, /**/ 292, /**/ 291, /**/ 290, /**/ 289, /**/ 288, /**/ 287, /**/ 286, /**/ 285, /**/ 284, /**/ 283, /**/ 282, /**/ 281, /**/ 280, /**/ 279, /**/ 278, /**/ 277, /**/ 276, /**/ 275, /**/ 274, /**/ 273, /**/ 272, /**/ 271, /**/ 270, /**/ 269, /**/ 268, /**/ 267, /**/ 266, /**/ 265, /**/ 264, /**/ 263, /**/ 262, /**/ 261, /**/ 260, /**/ 259, /**/ 258, /**/ 257, /**/ 256, /**/ 255, /**/ 254, /**/ 253, /**/ 252, /**/ 251, /**/ 250, /**/ 249, /**/ 248, /**/ 247, /**/ 246, /**/ 245, /**/ 244, /**/ 243, /**/ 242, /**/ 241, /**/ 240, /**/ 239, /**/ 238, /**/ 237, /**/ 236, /**/ 235, /**/ 234, /**/ 233, /**/ 232, /**/ 231, /**/ 230, /**/ 229, /**/ 228, /**/ 227, /**/ 226, /**/ 225, /**/ 224, /**/ 223, /**/ 222, /**/ 221, /**/ 220, /**/ 219, /**/ 218, /**/ 217, /**/ 216, /**/ 215, /**/ 214, /**/ 213, /**/ 212, /**/ 211, /**/ 210, /**/ 209, /**/ 208, /**/ 207, /**/ 206, /**/ 205, /**/ 204, /**/ 203, /**/ 202, /**/ 201, /**/ 200, /**/ 199, /**/ 198, /**/ 197, /**/ 196, /**/ 195, /**/ 194, /**/ 193, /**/ 192, /**/ 191, /**/ 190, /**/ 189, /**/ 188, /**/ 187, /**/ 186, /**/ 185, /**/ 184, /**/ 183, /**/ 182, /**/ 181, /**/ 180, /**/ 179, /**/ 178, /**/ 177, /**/ 176, /**/ 175, /**/ 174, /**/ 173, /**/ 172, /**/ 171, /**/ 170, /**/ 169, /**/ 168, /**/ 167, /**/ 166, /**/ 165, /**/ 164, /**/ 163, /**/ 162, /**/ 161, /**/ 160, /**/ 159, /**/ 158, /**/ 157, /**/ 156, /**/ 155, /**/ 154, /**/ 153, /**/ 152, /**/ 151, /**/ 150, /**/ 149, /**/ 148, /**/ 147, /**/ 146, /**/ 145, /**/ 144, /**/ 143, /**/ 142, /**/ 141, /**/ 140, /**/ 139, /**/ 138, /**/ 137, /**/ 136, /**/ 135, /**/ 134, /**/ 133, /**/ 132, /**/ 131, /**/ 130, /**/ 129, /**/ 128, /**/ 127, /**/ 126, /**/ 125, /**/ 124, /**/ 123, /**/ 122, /**/ 121, /**/ 120, /**/ 119, /**/ 118, /**/ 117, /**/ 116, /**/ 115, /**/ 114, /**/ 113, /**/ 112, /**/ 111, /**/ 110, /**/ 109, /**/ 108, /**/ 107, /**/ 106, /**/ 105, /**/ 104, /**/ 103, /**/ 102, /**/ 101, /**/ 100, /**/ 99, /**/ 98, /**/ 97, /**/ 96, /**/ 95, /**/ 94, /**/ 93, /**/ 92, /**/ 91, /**/ 90, /**/ 89, /**/ 88, /**/ 87, /**/ 86, /**/ 85, /**/ 84, /**/ 83, /**/ 82, /**/ 81, /**/ 80, /**/ 79, /**/ 78, /**/ 77, /**/ 76, /**/ 75, /**/ 74, /**/ 73, /**/ 72, /**/ 71, /**/ 70, /**/ 69, /**/ 68, /**/ 67, /**/ 66, /**/ 65, /**/ 64, /**/ 63, /**/ 62, /**/ 61, /**/ 60, /**/ 59, /**/ 58, /**/ 57, /**/ 56, /**/ 55, /**/ 54, /**/ 53, /**/ 52, /**/ 51, /**/ 50, /**/ 49, /**/ 48, /**/ 47, /**/ 46, /**/ 45, /**/ 44, /**/ 43, /**/ 42, /**/ 41, /**/ 40, /**/ 39, /**/ 38, /**/ 37, /**/ 36, /**/ 35, /**/ 34, /**/ 33, /**/ 32, /**/ 31, /**/ 30, /**/ 29, /**/ 28, /**/ 27, /**/ 26, /**/ 25, /**/ 24, /**/ 23, /**/ 22, /**/ 21, /**/ 20, /**/ 19, /**/ 18, /**/ 17, /**/ 16, /**/ 15, /**/ 14, /**/ 13, /**/ 12, /**/ 11, /**/ 10, /**/ 9, /**/ 8, /**/ 7, /**/ 6, /**/ 5, /**/ 4, /**/ 3, /**/ 2, /**/ 1, /**/ 0 }; /* * Place to put a short description when adding a feature with a patch. * Keep it short, e.g.,: "relative numbers", "persistent undo". * Also add a comment marker to separate the lines. * See the official Vim patches for the diff format: It must use a context of * one line only. Create it by hand or use "diff -C2" and edit the patch. */ static char *(extra_patches[]) = { /* Add your patch description below this line */ /**/ NULL }; int highest_patch(void) { int i; int h = 0; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] > h) h = included_patches[i]; return h; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if patch "n" has been included. */ int has_patch(int n) { int i; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] == n) return TRUE; return FALSE; } #endif void ex_version(exarg_T *eap) { /* * Ignore a ":version 9.99" command. */ if (*eap->arg == NUL) { msg_putchar('\n'); list_version(); } } /* * List all features aligned in columns, dictionary style. */ static void list_features(void) { int i; int ncol; int nrow; int nfeat = 0; int width = 0; /* Find the length of the longest feature name, use that + 1 as the column * width */ for (i = 0; features[i] != NULL; ++i) { int l = (int)STRLEN(features[i]); if (l > width) width = l; ++nfeat; } width += 1; if (Columns < width) { /* Not enough screen columns - show one per line */ for (i = 0; features[i] != NULL; ++i) { version_msg(features[i]); if (msg_col > 0) msg_putchar('\n'); } return; } /* The rightmost column doesn't need a separator. * Sacrifice it to fit in one more column if possible. */ ncol = (int) (Columns + 1) / width; nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0); /* i counts columns then rows. idx counts rows then columns. */ for (i = 0; !got_int && i < nrow * ncol; ++i) { int idx = (i / ncol) + (i % ncol) * nrow; if (idx < nfeat) { int last_col = (i + 1) % ncol == 0; msg_puts((char_u *)features[idx]); if (last_col) { if (msg_col > 0) msg_putchar('\n'); } else { while (msg_col % width) msg_putchar(' '); } } else { if (msg_col > 0) msg_putchar('\n'); } } } void list_version(void) { int i; int first; char *s = ""; /* * When adding features here, don't forget to update the list of * internal variables in eval.c! */ MSG(longVersion); #ifdef WIN3264 # ifdef FEAT_GUI_W32 # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit GUI version")); # else MSG_PUTS(_("\nMS-Windows 32-bit GUI version")); # endif # ifdef FEAT_OLE MSG_PUTS(_(" with OLE support")); # endif # else # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit console version")); # else MSG_PUTS(_("\nMS-Windows 32-bit console version")); # endif # endif #endif #ifdef MACOS # ifdef MACOS_X # ifdef MACOS_X_UNIX MSG_PUTS(_("\nMacOS X (unix) version")); # else MSG_PUTS(_("\nMacOS X version")); # endif #else MSG_PUTS(_("\nMacOS version")); # endif #endif #ifdef VMS MSG_PUTS(_("\nOpenVMS version")); # ifdef HAVE_PATHDEF if (*compiled_arch != NUL) { MSG_PUTS(" - "); MSG_PUTS(compiled_arch); } # endif #endif /* Print the list of patch numbers if there is at least one. */ /* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */ if (included_patches[0] != 0) { MSG_PUTS(_("\nIncluded patches: ")); first = -1; /* find last one */ for (i = 0; included_patches[i] != 0; ++i) ; while (--i >= 0) { if (first < 0) first = included_patches[i]; if (i == 0 || included_patches[i - 1] != included_patches[i] + 1) { MSG_PUTS(s); s = ", "; msg_outnum((long)first); if (first != included_patches[i]) { MSG_PUTS("-"); msg_outnum((long)included_patches[i]); } first = -1; } } } /* Print the list of extra patch descriptions if there is at least one. */ if (extra_patches[0] != NULL) { MSG_PUTS(_("\nExtra patches: ")); s = ""; for (i = 0; extra_patches[i] != NULL; ++i) { MSG_PUTS(s); s = ", "; MSG_PUTS(extra_patches[i]); } } #ifdef MODIFIED_BY MSG_PUTS("\n"); MSG_PUTS(_("Modified by ")); MSG_PUTS(MODIFIED_BY); #endif #ifdef HAVE_PATHDEF if (*compiled_user != NUL || *compiled_sys != NUL) { MSG_PUTS(_("\nCompiled ")); if (*compiled_user != NUL) { MSG_PUTS(_("by ")); MSG_PUTS(compiled_user); } if (*compiled_sys != NUL) { MSG_PUTS("@"); MSG_PUTS(compiled_sys); } } #endif #ifdef FEAT_HUGE MSG_PUTS(_("\nHuge version ")); #else # ifdef FEAT_BIG MSG_PUTS(_("\nBig version ")); # else # ifdef FEAT_NORMAL MSG_PUTS(_("\nNormal version ")); # else # ifdef FEAT_SMALL MSG_PUTS(_("\nSmall version ")); # else MSG_PUTS(_("\nTiny version ")); # endif # endif # endif #endif #ifndef FEAT_GUI MSG_PUTS(_("without GUI.")); #else # ifdef FEAT_GUI_GTK # ifdef USE_GTK3 MSG_PUTS(_("with GTK3 GUI.")); # else # ifdef FEAT_GUI_GNOME MSG_PUTS(_("with GTK2-GNOME GUI.")); # else MSG_PUTS(_("with GTK2 GUI.")); # endif # endif # else # ifdef FEAT_GUI_MOTIF MSG_PUTS(_("with X11-Motif GUI.")); # else # ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW MSG_PUTS(_("with X11-neXtaw GUI.")); # else MSG_PUTS(_("with X11-Athena GUI.")); # endif # else # ifdef FEAT_GUI_PHOTON MSG_PUTS(_("with Photon GUI.")); # else # if defined(MSWIN) MSG_PUTS(_("with GUI.")); # else # if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON MSG_PUTS(_("with Carbon GUI.")); # else # if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX MSG_PUTS(_("with Cocoa GUI.")); # else # if defined(MACOS) MSG_PUTS(_("with (classic) GUI.")); # endif # endif # endif # endif # endif # endif # endif # endif #endif version_msg(_(" Features included (+) or not (-):\n")); list_features(); #ifdef SYS_VIMRC_FILE version_msg(_(" system vimrc file: \"")); version_msg(SYS_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE version_msg(_(" user vimrc file: \"")); version_msg(USR_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE2 version_msg(_(" 2nd user vimrc file: \"")); version_msg(USR_VIMRC_FILE2); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE3 version_msg(_(" 3rd user vimrc file: \"")); version_msg(USR_VIMRC_FILE3); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE version_msg(_(" user exrc file: \"")); version_msg(USR_EXRC_FILE); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE2 version_msg(_(" 2nd user exrc file: \"")); version_msg(USR_EXRC_FILE2); version_msg("\"\n"); #endif #ifdef FEAT_GUI # ifdef SYS_GVIMRC_FILE version_msg(_(" system gvimrc file: \"")); version_msg(SYS_GVIMRC_FILE); version_msg("\"\n"); # endif version_msg(_(" user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE); version_msg("\"\n"); # ifdef USR_GVIMRC_FILE2 version_msg(_("2nd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE2); version_msg("\"\n"); # endif # ifdef USR_GVIMRC_FILE3 version_msg(_("3rd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE3); version_msg("\"\n"); # endif #endif version_msg(_(" defaults file: \"")); version_msg(VIM_DEFAULTS_FILE); version_msg("\"\n"); #ifdef FEAT_GUI # ifdef SYS_MENU_FILE version_msg(_(" system menu file: \"")); version_msg(SYS_MENU_FILE); version_msg("\"\n"); # endif #endif #ifdef HAVE_PATHDEF if (*default_vim_dir != NUL) { version_msg(_(" fall-back for $VIM: \"")); version_msg((char *)default_vim_dir); version_msg("\"\n"); } if (*default_vimruntime_dir != NUL) { version_msg(_(" f-b for $VIMRUNTIME: \"")); version_msg((char *)default_vimruntime_dir); version_msg("\"\n"); } version_msg(_("Compilation: ")); version_msg((char *)all_cflags); version_msg("\n"); #ifdef VMS if (*compiler_version != NUL) { version_msg(_("Compiler: ")); version_msg((char *)compiler_version); version_msg("\n"); } #endif version_msg(_("Linking: ")); version_msg((char *)all_lflags); #endif #ifdef DEBUG version_msg("\n"); version_msg(_(" DEBUG BUILD")); #endif } /* * Output a string for the version message. If it's going to wrap, output a * newline, unless the message is too long to fit on the screen anyway. */ static void version_msg(char *s) { int len = (int)STRLEN(s); if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns && *s != '\n') msg_putchar('\n'); if (!got_int) MSG_PUTS(s); } static void do_intro_line(int row, char_u *mesg, int add_version, int attr); /* * Show the intro message when not editing a file. */ void maybe_intro_message(void) { if (bufempty() && curbuf->b_fname == NULL #ifdef FEAT_WINDOWS && firstwin->w_next == NULL #endif && vim_strchr(p_shm, SHM_INTRO) == NULL) intro_message(FALSE); } /* * Give an introductory message about Vim. * Only used when starting Vim on an empty file, without a file name. * Or with the ":intro" command (for Sven :-). */ void intro_message( int colon) /* TRUE for ":intro" */ { int i; int row; int blanklines; int sponsor; char *p; static char *(lines[]) = { N_("VIM - Vi IMproved"), "", N_("version "), N_("by Bram Moolenaar et al."), #ifdef MODIFIED_BY " ", #endif N_("Vim is open source and freely distributable"), "", N_("Help poor children in Uganda!"), N_("type :help iccf<Enter> for information "), "", N_("type :q<Enter> to exit "), N_("type :help<Enter> or <F1> for on-line help"), N_("type :help version8<Enter> for version info"), NULL, "", N_("Running in Vi compatible mode"), N_("type :set nocp<Enter> for Vim defaults"), N_("type :help cp-default<Enter> for info on this"), }; #ifdef FEAT_GUI static char *(gui_lines[]) = { NULL, NULL, NULL, NULL, #ifdef MODIFIED_BY NULL, #endif NULL, NULL, NULL, N_("menu Help->Orphans for information "), NULL, N_("Running modeless, typed text is inserted"), N_("menu Edit->Global Settings->Toggle Insert Mode "), N_(" for two modes "), NULL, NULL, NULL, N_("menu Edit->Global Settings->Toggle Vi Compatible"), N_(" for Vim defaults "), }; #endif /* blanklines = screen height - # message lines */ blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1); if (!p_cp) blanklines += 4; /* add 4 for not showing "Vi compatible" message */ #ifdef FEAT_WINDOWS /* Don't overwrite a statusline. Depends on 'cmdheight'. */ if (p_ls > 1) blanklines -= Rows - topframe->fr_height; #endif if (blanklines < 0) blanklines = 0; /* Show the sponsor and register message one out of four times, the Uganda * message two out of four times. */ sponsor = (int)time(NULL); sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0); /* start displaying the message lines after half of the blank lines */ row = blanklines / 2; if ((row >= 2 && Columns >= 50) || colon) { for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i) { p = lines[i]; #ifdef FEAT_GUI if (p_im && gui.in_use && gui_lines[i] != NULL) p = gui_lines[i]; #endif if (p == NULL) { if (!p_cp) break; continue; } if (sponsor != 0) { if (strstr(p, "children") != NULL) p = sponsor < 0 ? N_("Sponsor Vim development!") : N_("Become a registered Vim user!"); else if (strstr(p, "iccf") != NULL) p = sponsor < 0 ? N_("type :help sponsor<Enter> for information ") : N_("type :help register<Enter> for information "); else if (strstr(p, "Orphans") != NULL) p = N_("menu Help->Sponsor/Register for information "); } if (*p != NUL) do_intro_line(row, (char_u *)_(p), i == 2, 0); ++row; } } /* Make the wait-return message appear just below the text. */ if (colon) msg_row = row; } static void do_intro_line( int row, char_u *mesg, int add_version, int attr) { char_u vers[20]; int col; char_u *p; int l; int clen; #ifdef MODIFIED_BY # define MODBY_LEN 150 char_u modby[MODBY_LEN]; if (*mesg == ' ') { vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1); l = (int)STRLEN(modby); vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1); mesg = modby; } #endif /* Center the message horizontally. */ col = vim_strsize(mesg); if (add_version) { STRCPY(vers, mediumVersion); if (highest_patch()) { /* Check for 9.9x or 9.9xx, alpha/beta version */ if (isalpha((int)vers[3])) { int len = (isalpha((int)vers[4])) ? 5 : 4; sprintf((char *)vers + len, ".%d%s", highest_patch(), mediumVersion + len); } else sprintf((char *)vers + 3, ".%d", highest_patch()); } col += (int)STRLEN(vers); } col = (Columns - col) / 2; if (col < 0) col = 0; /* Split up in parts to highlight <> items differently. */ for (p = mesg; *p != NUL; p += l) { clen = 0; for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l) { #ifdef FEAT_MBYTE if (has_mbyte) { clen += ptr2cells(p + l); l += (*mb_ptr2len)(p + l) - 1; } else #endif clen += byte2cells(p[l]); } screen_puts_len(p, l, row, col, *p == '<' ? hl_attr(HLF_8) : attr); col += clen; } /* Add the version number to the version line. */ if (add_version) screen_puts(vers, row, col, 0); } /* * ":intro": clear screen, display intro screen and wait for return. */ void ex_intro(exarg_T *eap UNUSED) { screenclear(); intro_message(TRUE); wait_return(TRUE); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3153_1
crossvul-cpp_data_good_5498_0
/* * Generic ring buffer * * Copyright (C) 2008 Steven Rostedt <srostedt@redhat.com> */ #include <linux/trace_events.h> #include <linux/ring_buffer.h> #include <linux/trace_clock.h> #include <linux/trace_seq.h> #include <linux/spinlock.h> #include <linux/irq_work.h> #include <linux/uaccess.h> #include <linux/hardirq.h> #include <linux/kthread.h> /* for self test */ #include <linux/kmemcheck.h> #include <linux/module.h> #include <linux/percpu.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/slab.h> #include <linux/init.h> #include <linux/hash.h> #include <linux/list.h> #include <linux/cpu.h> #include <asm/local.h> static void update_pages_handler(struct work_struct *work); /* * The ring buffer header is special. We must manually up keep it. */ int ring_buffer_print_entry_header(struct trace_seq *s) { trace_seq_puts(s, "# compressed entry header\n"); trace_seq_puts(s, "\ttype_len : 5 bits\n"); trace_seq_puts(s, "\ttime_delta : 27 bits\n"); trace_seq_puts(s, "\tarray : 32 bits\n"); trace_seq_putc(s, '\n'); trace_seq_printf(s, "\tpadding : type == %d\n", RINGBUF_TYPE_PADDING); trace_seq_printf(s, "\ttime_extend : type == %d\n", RINGBUF_TYPE_TIME_EXTEND); trace_seq_printf(s, "\tdata max type_len == %d\n", RINGBUF_TYPE_DATA_TYPE_LEN_MAX); return !trace_seq_has_overflowed(s); } /* * The ring buffer is made up of a list of pages. A separate list of pages is * allocated for each CPU. A writer may only write to a buffer that is * associated with the CPU it is currently executing on. A reader may read * from any per cpu buffer. * * The reader is special. For each per cpu buffer, the reader has its own * reader page. When a reader has read the entire reader page, this reader * page is swapped with another page in the ring buffer. * * Now, as long as the writer is off the reader page, the reader can do what * ever it wants with that page. The writer will never write to that page * again (as long as it is out of the ring buffer). * * Here's some silly ASCII art. * * +------+ * |reader| RING BUFFER * |page | * +------+ +---+ +---+ +---+ * | |-->| |-->| | * +---+ +---+ +---+ * ^ | * | | * +---------------+ * * * +------+ * |reader| RING BUFFER * |page |------------------v * +------+ +---+ +---+ +---+ * | |-->| |-->| | * +---+ +---+ +---+ * ^ | * | | * +---------------+ * * * +------+ * |reader| RING BUFFER * |page |------------------v * +------+ +---+ +---+ +---+ * ^ | |-->| |-->| | * | +---+ +---+ +---+ * | | * | | * +------------------------------+ * * * +------+ * |buffer| RING BUFFER * |page |------------------v * +------+ +---+ +---+ +---+ * ^ | | | |-->| | * | New +---+ +---+ +---+ * | Reader------^ | * | page | * +------------------------------+ * * * After we make this swap, the reader can hand this page off to the splice * code and be done with it. It can even allocate a new page if it needs to * and swap that into the ring buffer. * * We will be using cmpxchg soon to make all this lockless. * */ /* Used for individual buffers (after the counter) */ #define RB_BUFFER_OFF (1 << 20) #define BUF_PAGE_HDR_SIZE offsetof(struct buffer_data_page, data) #define RB_EVNT_HDR_SIZE (offsetof(struct ring_buffer_event, array)) #define RB_ALIGNMENT 4U #define RB_MAX_SMALL_DATA (RB_ALIGNMENT * RINGBUF_TYPE_DATA_TYPE_LEN_MAX) #define RB_EVNT_MIN_SIZE 8U /* two 32bit words */ #ifndef CONFIG_HAVE_64BIT_ALIGNED_ACCESS # define RB_FORCE_8BYTE_ALIGNMENT 0 # define RB_ARCH_ALIGNMENT RB_ALIGNMENT #else # define RB_FORCE_8BYTE_ALIGNMENT 1 # define RB_ARCH_ALIGNMENT 8U #endif #define RB_ALIGN_DATA __aligned(RB_ARCH_ALIGNMENT) /* define RINGBUF_TYPE_DATA for 'case RINGBUF_TYPE_DATA:' */ #define RINGBUF_TYPE_DATA 0 ... RINGBUF_TYPE_DATA_TYPE_LEN_MAX enum { RB_LEN_TIME_EXTEND = 8, RB_LEN_TIME_STAMP = 16, }; #define skip_time_extend(event) \ ((struct ring_buffer_event *)((char *)event + RB_LEN_TIME_EXTEND)) static inline int rb_null_event(struct ring_buffer_event *event) { return event->type_len == RINGBUF_TYPE_PADDING && !event->time_delta; } static void rb_event_set_padding(struct ring_buffer_event *event) { /* padding has a NULL time_delta */ event->type_len = RINGBUF_TYPE_PADDING; event->time_delta = 0; } static unsigned rb_event_data_length(struct ring_buffer_event *event) { unsigned length; if (event->type_len) length = event->type_len * RB_ALIGNMENT; else length = event->array[0]; return length + RB_EVNT_HDR_SIZE; } /* * Return the length of the given event. Will return * the length of the time extend if the event is a * time extend. */ static inline unsigned rb_event_length(struct ring_buffer_event *event) { switch (event->type_len) { case RINGBUF_TYPE_PADDING: if (rb_null_event(event)) /* undefined */ return -1; return event->array[0] + RB_EVNT_HDR_SIZE; case RINGBUF_TYPE_TIME_EXTEND: return RB_LEN_TIME_EXTEND; case RINGBUF_TYPE_TIME_STAMP: return RB_LEN_TIME_STAMP; case RINGBUF_TYPE_DATA: return rb_event_data_length(event); default: BUG(); } /* not hit */ return 0; } /* * Return total length of time extend and data, * or just the event length for all other events. */ static inline unsigned rb_event_ts_length(struct ring_buffer_event *event) { unsigned len = 0; if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) { /* time extends include the data event after it */ len = RB_LEN_TIME_EXTEND; event = skip_time_extend(event); } return len + rb_event_length(event); } /** * ring_buffer_event_length - return the length of the event * @event: the event to get the length of * * Returns the size of the data load of a data event. * If the event is something other than a data event, it * returns the size of the event itself. With the exception * of a TIME EXTEND, where it still returns the size of the * data load of the data event after it. */ unsigned ring_buffer_event_length(struct ring_buffer_event *event) { unsigned length; if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) event = skip_time_extend(event); length = rb_event_length(event); if (event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX) return length; length -= RB_EVNT_HDR_SIZE; if (length > RB_MAX_SMALL_DATA + sizeof(event->array[0])) length -= sizeof(event->array[0]); return length; } EXPORT_SYMBOL_GPL(ring_buffer_event_length); /* inline for ring buffer fast paths */ static void * rb_event_data(struct ring_buffer_event *event) { if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) event = skip_time_extend(event); BUG_ON(event->type_len > RINGBUF_TYPE_DATA_TYPE_LEN_MAX); /* If length is in len field, then array[0] has the data */ if (event->type_len) return (void *)&event->array[0]; /* Otherwise length is in array[0] and array[1] has the data */ return (void *)&event->array[1]; } /** * ring_buffer_event_data - return the data of the event * @event: the event to get the data from */ void *ring_buffer_event_data(struct ring_buffer_event *event) { return rb_event_data(event); } EXPORT_SYMBOL_GPL(ring_buffer_event_data); #define for_each_buffer_cpu(buffer, cpu) \ for_each_cpu(cpu, buffer->cpumask) #define TS_SHIFT 27 #define TS_MASK ((1ULL << TS_SHIFT) - 1) #define TS_DELTA_TEST (~TS_MASK) /* Flag when events were overwritten */ #define RB_MISSED_EVENTS (1 << 31) /* Missed count stored at end */ #define RB_MISSED_STORED (1 << 30) struct buffer_data_page { u64 time_stamp; /* page time stamp */ local_t commit; /* write committed index */ unsigned char data[] RB_ALIGN_DATA; /* data of buffer page */ }; /* * Note, the buffer_page list must be first. The buffer pages * are allocated in cache lines, which means that each buffer * page will be at the beginning of a cache line, and thus * the least significant bits will be zero. We use this to * add flags in the list struct pointers, to make the ring buffer * lockless. */ struct buffer_page { struct list_head list; /* list of buffer pages */ local_t write; /* index for next write */ unsigned read; /* index for next read */ local_t entries; /* entries on this page */ unsigned long real_end; /* real end of data */ struct buffer_data_page *page; /* Actual data page */ }; /* * The buffer page counters, write and entries, must be reset * atomically when crossing page boundaries. To synchronize this * update, two counters are inserted into the number. One is * the actual counter for the write position or count on the page. * * The other is a counter of updaters. Before an update happens * the update partition of the counter is incremented. This will * allow the updater to update the counter atomically. * * The counter is 20 bits, and the state data is 12. */ #define RB_WRITE_MASK 0xfffff #define RB_WRITE_INTCNT (1 << 20) static void rb_init_page(struct buffer_data_page *bpage) { local_set(&bpage->commit, 0); } /** * ring_buffer_page_len - the size of data on the page. * @page: The page to read * * Returns the amount of data on the page, including buffer page header. */ size_t ring_buffer_page_len(void *page) { return local_read(&((struct buffer_data_page *)page)->commit) + BUF_PAGE_HDR_SIZE; } /* * Also stolen from mm/slob.c. Thanks to Mathieu Desnoyers for pointing * this issue out. */ static void free_buffer_page(struct buffer_page *bpage) { free_page((unsigned long)bpage->page); kfree(bpage); } /* * We need to fit the time_stamp delta into 27 bits. */ static inline int test_time_stamp(u64 delta) { if (delta & TS_DELTA_TEST) return 1; return 0; } #define BUF_PAGE_SIZE (PAGE_SIZE - BUF_PAGE_HDR_SIZE) /* Max payload is BUF_PAGE_SIZE - header (8bytes) */ #define BUF_MAX_DATA_SIZE (BUF_PAGE_SIZE - (sizeof(u32) * 2)) int ring_buffer_print_page_header(struct trace_seq *s) { struct buffer_data_page field; trace_seq_printf(s, "\tfield: u64 timestamp;\t" "offset:0;\tsize:%u;\tsigned:%u;\n", (unsigned int)sizeof(field.time_stamp), (unsigned int)is_signed_type(u64)); trace_seq_printf(s, "\tfield: local_t commit;\t" "offset:%u;\tsize:%u;\tsigned:%u;\n", (unsigned int)offsetof(typeof(field), commit), (unsigned int)sizeof(field.commit), (unsigned int)is_signed_type(long)); trace_seq_printf(s, "\tfield: int overwrite;\t" "offset:%u;\tsize:%u;\tsigned:%u;\n", (unsigned int)offsetof(typeof(field), commit), 1, (unsigned int)is_signed_type(long)); trace_seq_printf(s, "\tfield: char data;\t" "offset:%u;\tsize:%u;\tsigned:%u;\n", (unsigned int)offsetof(typeof(field), data), (unsigned int)BUF_PAGE_SIZE, (unsigned int)is_signed_type(char)); return !trace_seq_has_overflowed(s); } struct rb_irq_work { struct irq_work work; wait_queue_head_t waiters; wait_queue_head_t full_waiters; bool waiters_pending; bool full_waiters_pending; bool wakeup_full; }; /* * Structure to hold event state and handle nested events. */ struct rb_event_info { u64 ts; u64 delta; unsigned long length; struct buffer_page *tail_page; int add_timestamp; }; /* * Used for which event context the event is in. * NMI = 0 * IRQ = 1 * SOFTIRQ = 2 * NORMAL = 3 * * See trace_recursive_lock() comment below for more details. */ enum { RB_CTX_NMI, RB_CTX_IRQ, RB_CTX_SOFTIRQ, RB_CTX_NORMAL, RB_CTX_MAX }; /* * head_page == tail_page && head == tail then buffer is empty. */ struct ring_buffer_per_cpu { int cpu; atomic_t record_disabled; struct ring_buffer *buffer; raw_spinlock_t reader_lock; /* serialize readers */ arch_spinlock_t lock; struct lock_class_key lock_key; unsigned long nr_pages; unsigned int current_context; struct list_head *pages; struct buffer_page *head_page; /* read from head */ struct buffer_page *tail_page; /* write to tail */ struct buffer_page *commit_page; /* committed pages */ struct buffer_page *reader_page; unsigned long lost_events; unsigned long last_overrun; local_t entries_bytes; local_t entries; local_t overrun; local_t commit_overrun; local_t dropped_events; local_t committing; local_t commits; unsigned long read; unsigned long read_bytes; u64 write_stamp; u64 read_stamp; /* ring buffer pages to update, > 0 to add, < 0 to remove */ long nr_pages_to_update; struct list_head new_pages; /* new pages to add */ struct work_struct update_pages_work; struct completion update_done; struct rb_irq_work irq_work; }; struct ring_buffer { unsigned flags; int cpus; atomic_t record_disabled; atomic_t resize_disabled; cpumask_var_t cpumask; struct lock_class_key *reader_lock_key; struct mutex mutex; struct ring_buffer_per_cpu **buffers; #ifdef CONFIG_HOTPLUG_CPU struct notifier_block cpu_notify; #endif u64 (*clock)(void); struct rb_irq_work irq_work; }; struct ring_buffer_iter { struct ring_buffer_per_cpu *cpu_buffer; unsigned long head; struct buffer_page *head_page; struct buffer_page *cache_reader_page; unsigned long cache_read; u64 read_stamp; }; /* * rb_wake_up_waiters - wake up tasks waiting for ring buffer input * * Schedules a delayed work to wake up any task that is blocked on the * ring buffer waiters queue. */ static void rb_wake_up_waiters(struct irq_work *work) { struct rb_irq_work *rbwork = container_of(work, struct rb_irq_work, work); wake_up_all(&rbwork->waiters); if (rbwork->wakeup_full) { rbwork->wakeup_full = false; wake_up_all(&rbwork->full_waiters); } } /** * ring_buffer_wait - wait for input to the ring buffer * @buffer: buffer to wait on * @cpu: the cpu buffer to wait on * @full: wait until a full page is available, if @cpu != RING_BUFFER_ALL_CPUS * * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon * as data is added to any of the @buffer's cpu buffers. Otherwise * it will wait for data to be added to a specific cpu buffer. */ int ring_buffer_wait(struct ring_buffer *buffer, int cpu, bool full) { struct ring_buffer_per_cpu *uninitialized_var(cpu_buffer); DEFINE_WAIT(wait); struct rb_irq_work *work; int ret = 0; /* * Depending on what the caller is waiting for, either any * data in any cpu buffer, or a specific buffer, put the * caller on the appropriate wait queue. */ if (cpu == RING_BUFFER_ALL_CPUS) { work = &buffer->irq_work; /* Full only makes sense on per cpu reads */ full = false; } else { if (!cpumask_test_cpu(cpu, buffer->cpumask)) return -ENODEV; cpu_buffer = buffer->buffers[cpu]; work = &cpu_buffer->irq_work; } while (true) { if (full) prepare_to_wait(&work->full_waiters, &wait, TASK_INTERRUPTIBLE); else prepare_to_wait(&work->waiters, &wait, TASK_INTERRUPTIBLE); /* * The events can happen in critical sections where * checking a work queue can cause deadlocks. * After adding a task to the queue, this flag is set * only to notify events to try to wake up the queue * using irq_work. * * We don't clear it even if the buffer is no longer * empty. The flag only causes the next event to run * irq_work to do the work queue wake up. The worse * that can happen if we race with !trace_empty() is that * an event will cause an irq_work to try to wake up * an empty queue. * * There's no reason to protect this flag either, as * the work queue and irq_work logic will do the necessary * synchronization for the wake ups. The only thing * that is necessary is that the wake up happens after * a task has been queued. It's OK for spurious wake ups. */ if (full) work->full_waiters_pending = true; else work->waiters_pending = true; if (signal_pending(current)) { ret = -EINTR; break; } if (cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) break; if (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu)) { unsigned long flags; bool pagebusy; if (!full) break; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page; raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); if (!pagebusy) break; } schedule(); } if (full) finish_wait(&work->full_waiters, &wait); else finish_wait(&work->waiters, &wait); return ret; } /** * ring_buffer_poll_wait - poll on buffer input * @buffer: buffer to wait on * @cpu: the cpu buffer to wait on * @filp: the file descriptor * @poll_table: The poll descriptor * * If @cpu == RING_BUFFER_ALL_CPUS then the task will wake up as soon * as data is added to any of the @buffer's cpu buffers. Otherwise * it will wait for data to be added to a specific cpu buffer. * * Returns POLLIN | POLLRDNORM if data exists in the buffers, * zero otherwise. */ int ring_buffer_poll_wait(struct ring_buffer *buffer, int cpu, struct file *filp, poll_table *poll_table) { struct ring_buffer_per_cpu *cpu_buffer; struct rb_irq_work *work; if (cpu == RING_BUFFER_ALL_CPUS) work = &buffer->irq_work; else { if (!cpumask_test_cpu(cpu, buffer->cpumask)) return -EINVAL; cpu_buffer = buffer->buffers[cpu]; work = &cpu_buffer->irq_work; } poll_wait(filp, &work->waiters, poll_table); work->waiters_pending = true; /* * There's a tight race between setting the waiters_pending and * checking if the ring buffer is empty. Once the waiters_pending bit * is set, the next event will wake the task up, but we can get stuck * if there's only a single event in. * * FIXME: Ideally, we need a memory barrier on the writer side as well, * but adding a memory barrier to all events will cause too much of a * performance hit in the fast path. We only need a memory barrier when * the buffer goes from empty to having content. But as this race is * extremely small, and it's not a problem if another event comes in, we * will fix it later. */ smp_mb(); if ((cpu == RING_BUFFER_ALL_CPUS && !ring_buffer_empty(buffer)) || (cpu != RING_BUFFER_ALL_CPUS && !ring_buffer_empty_cpu(buffer, cpu))) return POLLIN | POLLRDNORM; return 0; } /* buffer may be either ring_buffer or ring_buffer_per_cpu */ #define RB_WARN_ON(b, cond) \ ({ \ int _____ret = unlikely(cond); \ if (_____ret) { \ if (__same_type(*(b), struct ring_buffer_per_cpu)) { \ struct ring_buffer_per_cpu *__b = \ (void *)b; \ atomic_inc(&__b->buffer->record_disabled); \ } else \ atomic_inc(&b->record_disabled); \ WARN_ON(1); \ } \ _____ret; \ }) /* Up this if you want to test the TIME_EXTENTS and normalization */ #define DEBUG_SHIFT 0 static inline u64 rb_time_stamp(struct ring_buffer *buffer) { /* shift to debug/test normalization and TIME_EXTENTS */ return buffer->clock() << DEBUG_SHIFT; } u64 ring_buffer_time_stamp(struct ring_buffer *buffer, int cpu) { u64 time; preempt_disable_notrace(); time = rb_time_stamp(buffer); preempt_enable_no_resched_notrace(); return time; } EXPORT_SYMBOL_GPL(ring_buffer_time_stamp); void ring_buffer_normalize_time_stamp(struct ring_buffer *buffer, int cpu, u64 *ts) { /* Just stupid testing the normalize function and deltas */ *ts >>= DEBUG_SHIFT; } EXPORT_SYMBOL_GPL(ring_buffer_normalize_time_stamp); /* * Making the ring buffer lockless makes things tricky. * Although writes only happen on the CPU that they are on, * and they only need to worry about interrupts. Reads can * happen on any CPU. * * The reader page is always off the ring buffer, but when the * reader finishes with a page, it needs to swap its page with * a new one from the buffer. The reader needs to take from * the head (writes go to the tail). But if a writer is in overwrite * mode and wraps, it must push the head page forward. * * Here lies the problem. * * The reader must be careful to replace only the head page, and * not another one. As described at the top of the file in the * ASCII art, the reader sets its old page to point to the next * page after head. It then sets the page after head to point to * the old reader page. But if the writer moves the head page * during this operation, the reader could end up with the tail. * * We use cmpxchg to help prevent this race. We also do something * special with the page before head. We set the LSB to 1. * * When the writer must push the page forward, it will clear the * bit that points to the head page, move the head, and then set * the bit that points to the new head page. * * We also don't want an interrupt coming in and moving the head * page on another writer. Thus we use the second LSB to catch * that too. Thus: * * head->list->prev->next bit 1 bit 0 * ------- ------- * Normal page 0 0 * Points to head page 0 1 * New head page 1 0 * * Note we can not trust the prev pointer of the head page, because: * * +----+ +-----+ +-----+ * | |------>| T |---X--->| N | * | |<------| | | | * +----+ +-----+ +-----+ * ^ ^ | * | +-----+ | | * +----------| R |----------+ | * | |<-----------+ * +-----+ * * Key: ---X--> HEAD flag set in pointer * T Tail page * R Reader page * N Next page * * (see __rb_reserve_next() to see where this happens) * * What the above shows is that the reader just swapped out * the reader page with a page in the buffer, but before it * could make the new header point back to the new page added * it was preempted by a writer. The writer moved forward onto * the new page added by the reader and is about to move forward * again. * * You can see, it is legitimate for the previous pointer of * the head (or any page) not to point back to itself. But only * temporarially. */ #define RB_PAGE_NORMAL 0UL #define RB_PAGE_HEAD 1UL #define RB_PAGE_UPDATE 2UL #define RB_FLAG_MASK 3UL /* PAGE_MOVED is not part of the mask */ #define RB_PAGE_MOVED 4UL /* * rb_list_head - remove any bit */ static struct list_head *rb_list_head(struct list_head *list) { unsigned long val = (unsigned long)list; return (struct list_head *)(val & ~RB_FLAG_MASK); } /* * rb_is_head_page - test if the given page is the head page * * Because the reader may move the head_page pointer, we can * not trust what the head page is (it may be pointing to * the reader page). But if the next page is a header page, * its flags will be non zero. */ static inline int rb_is_head_page(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *page, struct list_head *list) { unsigned long val; val = (unsigned long)list->next; if ((val & ~RB_FLAG_MASK) != (unsigned long)&page->list) return RB_PAGE_MOVED; return val & RB_FLAG_MASK; } /* * rb_is_reader_page * * The unique thing about the reader page, is that, if the * writer is ever on it, the previous pointer never points * back to the reader page. */ static bool rb_is_reader_page(struct buffer_page *page) { struct list_head *list = page->list.prev; return rb_list_head(list->next) != &page->list; } /* * rb_set_list_to_head - set a list_head to be pointing to head. */ static void rb_set_list_to_head(struct ring_buffer_per_cpu *cpu_buffer, struct list_head *list) { unsigned long *ptr; ptr = (unsigned long *)&list->next; *ptr |= RB_PAGE_HEAD; *ptr &= ~RB_PAGE_UPDATE; } /* * rb_head_page_activate - sets up head page */ static void rb_head_page_activate(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *head; head = cpu_buffer->head_page; if (!head) return; /* * Set the previous list pointer to have the HEAD flag. */ rb_set_list_to_head(cpu_buffer, head->list.prev); } static void rb_list_head_clear(struct list_head *list) { unsigned long *ptr = (unsigned long *)&list->next; *ptr &= ~RB_FLAG_MASK; } /* * rb_head_page_dactivate - clears head page ptr (for free list) */ static void rb_head_page_deactivate(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *hd; /* Go through the whole list and clear any pointers found. */ rb_list_head_clear(cpu_buffer->pages); list_for_each(hd, cpu_buffer->pages) rb_list_head_clear(hd); } static int rb_head_page_set(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *head, struct buffer_page *prev, int old_flag, int new_flag) { struct list_head *list; unsigned long val = (unsigned long)&head->list; unsigned long ret; list = &prev->list; val &= ~RB_FLAG_MASK; ret = cmpxchg((unsigned long *)&list->next, val | old_flag, val | new_flag); /* check if the reader took the page */ if ((ret & ~RB_FLAG_MASK) != val) return RB_PAGE_MOVED; return ret & RB_FLAG_MASK; } static int rb_head_page_set_update(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *head, struct buffer_page *prev, int old_flag) { return rb_head_page_set(cpu_buffer, head, prev, old_flag, RB_PAGE_UPDATE); } static int rb_head_page_set_head(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *head, struct buffer_page *prev, int old_flag) { return rb_head_page_set(cpu_buffer, head, prev, old_flag, RB_PAGE_HEAD); } static int rb_head_page_set_normal(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *head, struct buffer_page *prev, int old_flag) { return rb_head_page_set(cpu_buffer, head, prev, old_flag, RB_PAGE_NORMAL); } static inline void rb_inc_page(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page **bpage) { struct list_head *p = rb_list_head((*bpage)->list.next); *bpage = list_entry(p, struct buffer_page, list); } static struct buffer_page * rb_set_head_page(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *head; struct buffer_page *page; struct list_head *list; int i; if (RB_WARN_ON(cpu_buffer, !cpu_buffer->head_page)) return NULL; /* sanity check */ list = cpu_buffer->pages; if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev->next) != list)) return NULL; page = head = cpu_buffer->head_page; /* * It is possible that the writer moves the header behind * where we started, and we miss in one loop. * A second loop should grab the header, but we'll do * three loops just because I'm paranoid. */ for (i = 0; i < 3; i++) { do { if (rb_is_head_page(cpu_buffer, page, page->list.prev)) { cpu_buffer->head_page = page; return page; } rb_inc_page(cpu_buffer, &page); } while (page != head); } RB_WARN_ON(cpu_buffer, 1); return NULL; } static int rb_head_page_replace(struct buffer_page *old, struct buffer_page *new) { unsigned long *ptr = (unsigned long *)&old->list.prev->next; unsigned long val; unsigned long ret; val = *ptr & ~RB_FLAG_MASK; val |= RB_PAGE_HEAD; ret = cmpxchg(ptr, val, (unsigned long)&new->list); return ret == val; } /* * rb_tail_page_update - move the tail page forward */ static void rb_tail_page_update(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *tail_page, struct buffer_page *next_page) { unsigned long old_entries; unsigned long old_write; /* * The tail page now needs to be moved forward. * * We need to reset the tail page, but without messing * with possible erasing of data brought in by interrupts * that have moved the tail page and are currently on it. * * We add a counter to the write field to denote this. */ old_write = local_add_return(RB_WRITE_INTCNT, &next_page->write); old_entries = local_add_return(RB_WRITE_INTCNT, &next_page->entries); /* * Just make sure we have seen our old_write and synchronize * with any interrupts that come in. */ barrier(); /* * If the tail page is still the same as what we think * it is, then it is up to us to update the tail * pointer. */ if (tail_page == READ_ONCE(cpu_buffer->tail_page)) { /* Zero the write counter */ unsigned long val = old_write & ~RB_WRITE_MASK; unsigned long eval = old_entries & ~RB_WRITE_MASK; /* * This will only succeed if an interrupt did * not come in and change it. In which case, we * do not want to modify it. * * We add (void) to let the compiler know that we do not care * about the return value of these functions. We use the * cmpxchg to only update if an interrupt did not already * do it for us. If the cmpxchg fails, we don't care. */ (void)local_cmpxchg(&next_page->write, old_write, val); (void)local_cmpxchg(&next_page->entries, old_entries, eval); /* * No need to worry about races with clearing out the commit. * it only can increment when a commit takes place. But that * only happens in the outer most nested commit. */ local_set(&next_page->page->commit, 0); /* Again, either we update tail_page or an interrupt does */ (void)cmpxchg(&cpu_buffer->tail_page, tail_page, next_page); } } static int rb_check_bpage(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *bpage) { unsigned long val = (unsigned long)bpage; if (RB_WARN_ON(cpu_buffer, val & RB_FLAG_MASK)) return 1; return 0; } /** * rb_check_list - make sure a pointer to a list has the last bits zero */ static int rb_check_list(struct ring_buffer_per_cpu *cpu_buffer, struct list_head *list) { if (RB_WARN_ON(cpu_buffer, rb_list_head(list->prev) != list->prev)) return 1; if (RB_WARN_ON(cpu_buffer, rb_list_head(list->next) != list->next)) return 1; return 0; } /** * rb_check_pages - integrity check of buffer pages * @cpu_buffer: CPU buffer with pages to test * * As a safety measure we check to make sure the data pages have not * been corrupted. */ static int rb_check_pages(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *head = cpu_buffer->pages; struct buffer_page *bpage, *tmp; /* Reset the head page if it exists */ if (cpu_buffer->head_page) rb_set_head_page(cpu_buffer); rb_head_page_deactivate(cpu_buffer); if (RB_WARN_ON(cpu_buffer, head->next->prev != head)) return -1; if (RB_WARN_ON(cpu_buffer, head->prev->next != head)) return -1; if (rb_check_list(cpu_buffer, head)) return -1; list_for_each_entry_safe(bpage, tmp, head, list) { if (RB_WARN_ON(cpu_buffer, bpage->list.next->prev != &bpage->list)) return -1; if (RB_WARN_ON(cpu_buffer, bpage->list.prev->next != &bpage->list)) return -1; if (rb_check_list(cpu_buffer, &bpage->list)) return -1; } rb_head_page_activate(cpu_buffer); return 0; } static int __rb_allocate_pages(long nr_pages, struct list_head *pages, int cpu) { struct buffer_page *bpage, *tmp; long i; for (i = 0; i < nr_pages; i++) { struct page *page; /* * __GFP_NORETRY flag makes sure that the allocation fails * gracefully without invoking oom-killer and the system is * not destabilized. */ bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()), GFP_KERNEL | __GFP_NORETRY, cpu_to_node(cpu)); if (!bpage) goto free_pages; list_add(&bpage->list, pages); page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL | __GFP_NORETRY, 0); if (!page) goto free_pages; bpage->page = page_address(page); rb_init_page(bpage->page); } return 0; free_pages: list_for_each_entry_safe(bpage, tmp, pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } return -ENOMEM; } static int rb_allocate_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages) { LIST_HEAD(pages); WARN_ON(!nr_pages); if (__rb_allocate_pages(nr_pages, &pages, cpu_buffer->cpu)) return -ENOMEM; /* * The ring buffer page list is a circular list that does not * start and end with a list head. All page list items point to * other pages. */ cpu_buffer->pages = pages.next; list_del(&pages); cpu_buffer->nr_pages = nr_pages; rb_check_pages(cpu_buffer); return 0; } static struct ring_buffer_per_cpu * rb_allocate_cpu_buffer(struct ring_buffer *buffer, long nr_pages, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; struct buffer_page *bpage; struct page *page; int ret; cpu_buffer = kzalloc_node(ALIGN(sizeof(*cpu_buffer), cache_line_size()), GFP_KERNEL, cpu_to_node(cpu)); if (!cpu_buffer) return NULL; cpu_buffer->cpu = cpu; cpu_buffer->buffer = buffer; raw_spin_lock_init(&cpu_buffer->reader_lock); lockdep_set_class(&cpu_buffer->reader_lock, buffer->reader_lock_key); cpu_buffer->lock = (arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED; INIT_WORK(&cpu_buffer->update_pages_work, update_pages_handler); init_completion(&cpu_buffer->update_done); init_irq_work(&cpu_buffer->irq_work.work, rb_wake_up_waiters); init_waitqueue_head(&cpu_buffer->irq_work.waiters); init_waitqueue_head(&cpu_buffer->irq_work.full_waiters); bpage = kzalloc_node(ALIGN(sizeof(*bpage), cache_line_size()), GFP_KERNEL, cpu_to_node(cpu)); if (!bpage) goto fail_free_buffer; rb_check_bpage(cpu_buffer, bpage); cpu_buffer->reader_page = bpage; page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL, 0); if (!page) goto fail_free_reader; bpage->page = page_address(page); rb_init_page(bpage->page); INIT_LIST_HEAD(&cpu_buffer->reader_page->list); INIT_LIST_HEAD(&cpu_buffer->new_pages); ret = rb_allocate_pages(cpu_buffer, nr_pages); if (ret < 0) goto fail_free_reader; cpu_buffer->head_page = list_entry(cpu_buffer->pages, struct buffer_page, list); cpu_buffer->tail_page = cpu_buffer->commit_page = cpu_buffer->head_page; rb_head_page_activate(cpu_buffer); return cpu_buffer; fail_free_reader: free_buffer_page(cpu_buffer->reader_page); fail_free_buffer: kfree(cpu_buffer); return NULL; } static void rb_free_cpu_buffer(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *head = cpu_buffer->pages; struct buffer_page *bpage, *tmp; free_buffer_page(cpu_buffer->reader_page); rb_head_page_deactivate(cpu_buffer); if (head) { list_for_each_entry_safe(bpage, tmp, head, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } bpage = list_entry(head, struct buffer_page, list); free_buffer_page(bpage); } kfree(cpu_buffer); } #ifdef CONFIG_HOTPLUG_CPU static int rb_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu); #endif /** * __ring_buffer_alloc - allocate a new ring_buffer * @size: the size in bytes per cpu that is needed. * @flags: attributes to set for the ring buffer. * * Currently the only flag that is available is the RB_FL_OVERWRITE * flag. This flag means that the buffer will overwrite old data * when the buffer wraps. If this flag is not set, the buffer will * drop data when the tail hits the head. */ struct ring_buffer *__ring_buffer_alloc(unsigned long size, unsigned flags, struct lock_class_key *key) { struct ring_buffer *buffer; long nr_pages; int bsize; int cpu; /* keep it in its own cache line */ buffer = kzalloc(ALIGN(sizeof(*buffer), cache_line_size()), GFP_KERNEL); if (!buffer) return NULL; if (!alloc_cpumask_var(&buffer->cpumask, GFP_KERNEL)) goto fail_free_buffer; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); buffer->flags = flags; buffer->clock = trace_clock_local; buffer->reader_lock_key = key; init_irq_work(&buffer->irq_work.work, rb_wake_up_waiters); init_waitqueue_head(&buffer->irq_work.waiters); /* need at least two pages */ if (nr_pages < 2) nr_pages = 2; /* * In case of non-hotplug cpu, if the ring-buffer is allocated * in early initcall, it will not be notified of secondary cpus. * In that off case, we need to allocate for all possible cpus. */ #ifdef CONFIG_HOTPLUG_CPU cpu_notifier_register_begin(); cpumask_copy(buffer->cpumask, cpu_online_mask); #else cpumask_copy(buffer->cpumask, cpu_possible_mask); #endif buffer->cpus = nr_cpu_ids; bsize = sizeof(void *) * nr_cpu_ids; buffer->buffers = kzalloc(ALIGN(bsize, cache_line_size()), GFP_KERNEL); if (!buffer->buffers) goto fail_free_cpumask; for_each_buffer_cpu(buffer, cpu) { buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu); if (!buffer->buffers[cpu]) goto fail_free_buffers; } #ifdef CONFIG_HOTPLUG_CPU buffer->cpu_notify.notifier_call = rb_cpu_notify; buffer->cpu_notify.priority = 0; __register_cpu_notifier(&buffer->cpu_notify); cpu_notifier_register_done(); #endif mutex_init(&buffer->mutex); return buffer; fail_free_buffers: for_each_buffer_cpu(buffer, cpu) { if (buffer->buffers[cpu]) rb_free_cpu_buffer(buffer->buffers[cpu]); } kfree(buffer->buffers); fail_free_cpumask: free_cpumask_var(buffer->cpumask); #ifdef CONFIG_HOTPLUG_CPU cpu_notifier_register_done(); #endif fail_free_buffer: kfree(buffer); return NULL; } EXPORT_SYMBOL_GPL(__ring_buffer_alloc); /** * ring_buffer_free - free a ring buffer. * @buffer: the buffer to free. */ void ring_buffer_free(struct ring_buffer *buffer) { int cpu; #ifdef CONFIG_HOTPLUG_CPU cpu_notifier_register_begin(); __unregister_cpu_notifier(&buffer->cpu_notify); #endif for_each_buffer_cpu(buffer, cpu) rb_free_cpu_buffer(buffer->buffers[cpu]); #ifdef CONFIG_HOTPLUG_CPU cpu_notifier_register_done(); #endif kfree(buffer->buffers); free_cpumask_var(buffer->cpumask); kfree(buffer); } EXPORT_SYMBOL_GPL(ring_buffer_free); void ring_buffer_set_clock(struct ring_buffer *buffer, u64 (*clock)(void)) { buffer->clock = clock; } static void rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer); static inline unsigned long rb_page_entries(struct buffer_page *bpage) { return local_read(&bpage->entries) & RB_WRITE_MASK; } static inline unsigned long rb_page_write(struct buffer_page *bpage) { return local_read(&bpage->write) & RB_WRITE_MASK; } static int rb_remove_pages(struct ring_buffer_per_cpu *cpu_buffer, unsigned long nr_pages) { struct list_head *tail_page, *to_remove, *next_page; struct buffer_page *to_remove_page, *tmp_iter_page; struct buffer_page *last_page, *first_page; unsigned long nr_removed; unsigned long head_bit; int page_entries; head_bit = 0; raw_spin_lock_irq(&cpu_buffer->reader_lock); atomic_inc(&cpu_buffer->record_disabled); /* * We don't race with the readers since we have acquired the reader * lock. We also don't race with writers after disabling recording. * This makes it easy to figure out the first and the last page to be * removed from the list. We unlink all the pages in between including * the first and last pages. This is done in a busy loop so that we * lose the least number of traces. * The pages are freed after we restart recording and unlock readers. */ tail_page = &cpu_buffer->tail_page->list; /* * tail page might be on reader page, we remove the next page * from the ring buffer */ if (cpu_buffer->tail_page == cpu_buffer->reader_page) tail_page = rb_list_head(tail_page->next); to_remove = tail_page; /* start of pages to remove */ first_page = list_entry(rb_list_head(to_remove->next), struct buffer_page, list); for (nr_removed = 0; nr_removed < nr_pages; nr_removed++) { to_remove = rb_list_head(to_remove)->next; head_bit |= (unsigned long)to_remove & RB_PAGE_HEAD; } next_page = rb_list_head(to_remove)->next; /* * Now we remove all pages between tail_page and next_page. * Make sure that we have head_bit value preserved for the * next page */ tail_page->next = (struct list_head *)((unsigned long)next_page | head_bit); next_page = rb_list_head(next_page); next_page->prev = tail_page; /* make sure pages points to a valid page in the ring buffer */ cpu_buffer->pages = next_page; /* update head page */ if (head_bit) cpu_buffer->head_page = list_entry(next_page, struct buffer_page, list); /* * change read pointer to make sure any read iterators reset * themselves */ cpu_buffer->read = 0; /* pages are removed, resume tracing and then free the pages */ atomic_dec(&cpu_buffer->record_disabled); raw_spin_unlock_irq(&cpu_buffer->reader_lock); RB_WARN_ON(cpu_buffer, list_empty(cpu_buffer->pages)); /* last buffer page to remove */ last_page = list_entry(rb_list_head(to_remove), struct buffer_page, list); tmp_iter_page = first_page; do { to_remove_page = tmp_iter_page; rb_inc_page(cpu_buffer, &tmp_iter_page); /* update the counters */ page_entries = rb_page_entries(to_remove_page); if (page_entries) { /* * If something was added to this page, it was full * since it is not the tail page. So we deduct the * bytes consumed in ring buffer from here. * Increment overrun to account for the lost events. */ local_add(page_entries, &cpu_buffer->overrun); local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes); } /* * We have already removed references to this list item, just * free up the buffer_page and its page */ free_buffer_page(to_remove_page); nr_removed--; } while (to_remove_page != last_page); RB_WARN_ON(cpu_buffer, nr_removed); return nr_removed == 0; } static int rb_insert_pages(struct ring_buffer_per_cpu *cpu_buffer) { struct list_head *pages = &cpu_buffer->new_pages; int retries, success; raw_spin_lock_irq(&cpu_buffer->reader_lock); /* * We are holding the reader lock, so the reader page won't be swapped * in the ring buffer. Now we are racing with the writer trying to * move head page and the tail page. * We are going to adapt the reader page update process where: * 1. We first splice the start and end of list of new pages between * the head page and its previous page. * 2. We cmpxchg the prev_page->next to point from head page to the * start of new pages list. * 3. Finally, we update the head->prev to the end of new list. * * We will try this process 10 times, to make sure that we don't keep * spinning. */ retries = 10; success = 0; while (retries--) { struct list_head *head_page, *prev_page, *r; struct list_head *last_page, *first_page; struct list_head *head_page_with_bit; head_page = &rb_set_head_page(cpu_buffer)->list; if (!head_page) break; prev_page = head_page->prev; first_page = pages->next; last_page = pages->prev; head_page_with_bit = (struct list_head *) ((unsigned long)head_page | RB_PAGE_HEAD); last_page->next = head_page_with_bit; first_page->prev = prev_page; r = cmpxchg(&prev_page->next, head_page_with_bit, first_page); if (r == head_page_with_bit) { /* * yay, we replaced the page pointer to our new list, * now, we just have to update to head page's prev * pointer to point to end of list */ head_page->prev = last_page; success = 1; break; } } if (success) INIT_LIST_HEAD(pages); /* * If we weren't successful in adding in new pages, warn and stop * tracing */ RB_WARN_ON(cpu_buffer, !success); raw_spin_unlock_irq(&cpu_buffer->reader_lock); /* free pages if they weren't inserted */ if (!success) { struct buffer_page *bpage, *tmp; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } return success; } static void rb_update_pages(struct ring_buffer_per_cpu *cpu_buffer) { int success; if (cpu_buffer->nr_pages_to_update > 0) success = rb_insert_pages(cpu_buffer); else success = rb_remove_pages(cpu_buffer, -cpu_buffer->nr_pages_to_update); if (success) cpu_buffer->nr_pages += cpu_buffer->nr_pages_to_update; } static void update_pages_handler(struct work_struct *work) { struct ring_buffer_per_cpu *cpu_buffer = container_of(work, struct ring_buffer_per_cpu, update_pages_work); rb_update_pages(cpu_buffer); complete(&cpu_buffer->update_done); } /** * ring_buffer_resize - resize the ring buffer * @buffer: the buffer to resize. * @size: the new size. * @cpu_id: the cpu buffer to resize * * Minimum size is 2 * BUF_PAGE_SIZE. * * Returns 0 on success and < 0 on failure. */ int ring_buffer_resize(struct ring_buffer *buffer, unsigned long size, int cpu_id) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long nr_pages; int cpu, err = 0; /* * Always succeed at resizing a non-existent buffer: */ if (!buffer) return size; /* Make sure the requested buffer exists */ if (cpu_id != RING_BUFFER_ALL_CPUS && !cpumask_test_cpu(cpu_id, buffer->cpumask)) return size; nr_pages = DIV_ROUND_UP(size, BUF_PAGE_SIZE); /* we need a minimum of two pages */ if (nr_pages < 2) nr_pages = 2; size = nr_pages * BUF_PAGE_SIZE; /* * Don't succeed if resizing is disabled, as a reader might be * manipulating the ring buffer and is expecting a sane state while * this is true. */ if (atomic_read(&buffer->resize_disabled)) return -EBUSY; /* prevent another thread from changing buffer sizes */ mutex_lock(&buffer->mutex); if (cpu_id == RING_BUFFER_ALL_CPUS) { /* calculate the pages to update */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; /* * nothing more to do for removing pages or no update */ if (cpu_buffer->nr_pages_to_update <= 0) continue; /* * to add pages, make sure all new pages can be * allocated without receiving ENOMEM */ INIT_LIST_HEAD(&cpu_buffer->new_pages); if (__rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu)) { /* not enough memory for new pages */ err = -ENOMEM; goto out_err; } } get_online_cpus(); /* * Fire off all the required work handlers * We can't schedule on offline CPUs, but it's not necessary * since we can change their buffer sizes without any race. */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; /* Can't run something on an offline CPU. */ if (!cpu_online(cpu)) { rb_update_pages(cpu_buffer); cpu_buffer->nr_pages_to_update = 0; } else { schedule_work_on(cpu, &cpu_buffer->update_pages_work); } } /* wait for all the updates to complete */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; if (!cpu_buffer->nr_pages_to_update) continue; if (cpu_online(cpu)) wait_for_completion(&cpu_buffer->update_done); cpu_buffer->nr_pages_to_update = 0; } put_online_cpus(); } else { /* Make sure this CPU has been intitialized */ if (!cpumask_test_cpu(cpu_id, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu_id]; if (nr_pages == cpu_buffer->nr_pages) goto out; cpu_buffer->nr_pages_to_update = nr_pages - cpu_buffer->nr_pages; INIT_LIST_HEAD(&cpu_buffer->new_pages); if (cpu_buffer->nr_pages_to_update > 0 && __rb_allocate_pages(cpu_buffer->nr_pages_to_update, &cpu_buffer->new_pages, cpu_id)) { err = -ENOMEM; goto out_err; } get_online_cpus(); /* Can't run something on an offline CPU. */ if (!cpu_online(cpu_id)) rb_update_pages(cpu_buffer); else { schedule_work_on(cpu_id, &cpu_buffer->update_pages_work); wait_for_completion(&cpu_buffer->update_done); } cpu_buffer->nr_pages_to_update = 0; put_online_cpus(); } out: /* * The ring buffer resize can happen with the ring buffer * enabled, so that the update disturbs the tracing as little * as possible. But if the buffer is disabled, we do not need * to worry about that, and we can take the time to verify * that the buffer is not corrupt. */ if (atomic_read(&buffer->record_disabled)) { atomic_inc(&buffer->record_disabled); /* * Even though the buffer was disabled, we must make sure * that it is truly disabled before calling rb_check_pages. * There could have been a race between checking * record_disable and incrementing it. */ synchronize_sched(); for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; rb_check_pages(cpu_buffer); } atomic_dec(&buffer->record_disabled); } mutex_unlock(&buffer->mutex); return size; out_err: for_each_buffer_cpu(buffer, cpu) { struct buffer_page *bpage, *tmp; cpu_buffer = buffer->buffers[cpu]; cpu_buffer->nr_pages_to_update = 0; if (list_empty(&cpu_buffer->new_pages)) continue; list_for_each_entry_safe(bpage, tmp, &cpu_buffer->new_pages, list) { list_del_init(&bpage->list); free_buffer_page(bpage); } } mutex_unlock(&buffer->mutex); return err; } EXPORT_SYMBOL_GPL(ring_buffer_resize); void ring_buffer_change_overwrite(struct ring_buffer *buffer, int val) { mutex_lock(&buffer->mutex); if (val) buffer->flags |= RB_FL_OVERWRITE; else buffer->flags &= ~RB_FL_OVERWRITE; mutex_unlock(&buffer->mutex); } EXPORT_SYMBOL_GPL(ring_buffer_change_overwrite); static inline void * __rb_data_page_index(struct buffer_data_page *bpage, unsigned index) { return bpage->data + index; } static inline void *__rb_page_index(struct buffer_page *bpage, unsigned index) { return bpage->page->data + index; } static inline struct ring_buffer_event * rb_reader_event(struct ring_buffer_per_cpu *cpu_buffer) { return __rb_page_index(cpu_buffer->reader_page, cpu_buffer->reader_page->read); } static inline struct ring_buffer_event * rb_iter_head_event(struct ring_buffer_iter *iter) { return __rb_page_index(iter->head_page, iter->head); } static inline unsigned rb_page_commit(struct buffer_page *bpage) { return local_read(&bpage->page->commit); } /* Size is determined by what has been committed */ static inline unsigned rb_page_size(struct buffer_page *bpage) { return rb_page_commit(bpage); } static inline unsigned rb_commit_index(struct ring_buffer_per_cpu *cpu_buffer) { return rb_page_commit(cpu_buffer->commit_page); } static inline unsigned rb_event_index(struct ring_buffer_event *event) { unsigned long addr = (unsigned long)event; return (addr & ~PAGE_MASK) - BUF_PAGE_HDR_SIZE; } static void rb_inc_iter(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer; /* * The iterator could be on the reader page (it starts there). * But the head could have moved, since the reader was * found. Check for this case and assign the iterator * to the head page instead of next. */ if (iter->head_page == cpu_buffer->reader_page) iter->head_page = rb_set_head_page(cpu_buffer); else rb_inc_page(cpu_buffer, &iter->head_page); iter->read_stamp = iter->head_page->page->time_stamp; iter->head = 0; } /* * rb_handle_head_page - writer hit the head page * * Returns: +1 to retry page * 0 to continue * -1 on error */ static int rb_handle_head_page(struct ring_buffer_per_cpu *cpu_buffer, struct buffer_page *tail_page, struct buffer_page *next_page) { struct buffer_page *new_head; int entries; int type; int ret; entries = rb_page_entries(next_page); /* * The hard part is here. We need to move the head * forward, and protect against both readers on * other CPUs and writers coming in via interrupts. */ type = rb_head_page_set_update(cpu_buffer, next_page, tail_page, RB_PAGE_HEAD); /* * type can be one of four: * NORMAL - an interrupt already moved it for us * HEAD - we are the first to get here. * UPDATE - we are the interrupt interrupting * a current move. * MOVED - a reader on another CPU moved the next * pointer to its reader page. Give up * and try again. */ switch (type) { case RB_PAGE_HEAD: /* * We changed the head to UPDATE, thus * it is our responsibility to update * the counters. */ local_add(entries, &cpu_buffer->overrun); local_sub(BUF_PAGE_SIZE, &cpu_buffer->entries_bytes); /* * The entries will be zeroed out when we move the * tail page. */ /* still more to do */ break; case RB_PAGE_UPDATE: /* * This is an interrupt that interrupt the * previous update. Still more to do. */ break; case RB_PAGE_NORMAL: /* * An interrupt came in before the update * and processed this for us. * Nothing left to do. */ return 1; case RB_PAGE_MOVED: /* * The reader is on another CPU and just did * a swap with our next_page. * Try again. */ return 1; default: RB_WARN_ON(cpu_buffer, 1); /* WTF??? */ return -1; } /* * Now that we are here, the old head pointer is * set to UPDATE. This will keep the reader from * swapping the head page with the reader page. * The reader (on another CPU) will spin till * we are finished. * * We just need to protect against interrupts * doing the job. We will set the next pointer * to HEAD. After that, we set the old pointer * to NORMAL, but only if it was HEAD before. * otherwise we are an interrupt, and only * want the outer most commit to reset it. */ new_head = next_page; rb_inc_page(cpu_buffer, &new_head); ret = rb_head_page_set_head(cpu_buffer, new_head, next_page, RB_PAGE_NORMAL); /* * Valid returns are: * HEAD - an interrupt came in and already set it. * NORMAL - One of two things: * 1) We really set it. * 2) A bunch of interrupts came in and moved * the page forward again. */ switch (ret) { case RB_PAGE_HEAD: case RB_PAGE_NORMAL: /* OK */ break; default: RB_WARN_ON(cpu_buffer, 1); return -1; } /* * It is possible that an interrupt came in, * set the head up, then more interrupts came in * and moved it again. When we get back here, * the page would have been set to NORMAL but we * just set it back to HEAD. * * How do you detect this? Well, if that happened * the tail page would have moved. */ if (ret == RB_PAGE_NORMAL) { struct buffer_page *buffer_tail_page; buffer_tail_page = READ_ONCE(cpu_buffer->tail_page); /* * If the tail had moved passed next, then we need * to reset the pointer. */ if (buffer_tail_page != tail_page && buffer_tail_page != next_page) rb_head_page_set_normal(cpu_buffer, new_head, next_page, RB_PAGE_HEAD); } /* * If this was the outer most commit (the one that * changed the original pointer from HEAD to UPDATE), * then it is up to us to reset it to NORMAL. */ if (type == RB_PAGE_HEAD) { ret = rb_head_page_set_normal(cpu_buffer, next_page, tail_page, RB_PAGE_UPDATE); if (RB_WARN_ON(cpu_buffer, ret != RB_PAGE_UPDATE)) return -1; } return 0; } static inline void rb_reset_tail(struct ring_buffer_per_cpu *cpu_buffer, unsigned long tail, struct rb_event_info *info) { struct buffer_page *tail_page = info->tail_page; struct ring_buffer_event *event; unsigned long length = info->length; /* * Only the event that crossed the page boundary * must fill the old tail_page with padding. */ if (tail >= BUF_PAGE_SIZE) { /* * If the page was filled, then we still need * to update the real_end. Reset it to zero * and the reader will ignore it. */ if (tail == BUF_PAGE_SIZE) tail_page->real_end = 0; local_sub(length, &tail_page->write); return; } event = __rb_page_index(tail_page, tail); kmemcheck_annotate_bitfield(event, bitfield); /* account for padding bytes */ local_add(BUF_PAGE_SIZE - tail, &cpu_buffer->entries_bytes); /* * Save the original length to the meta data. * This will be used by the reader to add lost event * counter. */ tail_page->real_end = tail; /* * If this event is bigger than the minimum size, then * we need to be careful that we don't subtract the * write counter enough to allow another writer to slip * in on this page. * We put in a discarded commit instead, to make sure * that this space is not used again. * * If we are less than the minimum size, we don't need to * worry about it. */ if (tail > (BUF_PAGE_SIZE - RB_EVNT_MIN_SIZE)) { /* No room for any events */ /* Mark the rest of the page with padding */ rb_event_set_padding(event); /* Set the write back to the previous setting */ local_sub(length, &tail_page->write); return; } /* Put in a discarded event */ event->array[0] = (BUF_PAGE_SIZE - tail) - RB_EVNT_HDR_SIZE; event->type_len = RINGBUF_TYPE_PADDING; /* time delta must be non zero */ event->time_delta = 1; /* Set write to end of buffer */ length = (tail + length) - BUF_PAGE_SIZE; local_sub(length, &tail_page->write); } static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer); /* * This is the slow path, force gcc not to inline it. */ static noinline struct ring_buffer_event * rb_move_tail(struct ring_buffer_per_cpu *cpu_buffer, unsigned long tail, struct rb_event_info *info) { struct buffer_page *tail_page = info->tail_page; struct buffer_page *commit_page = cpu_buffer->commit_page; struct ring_buffer *buffer = cpu_buffer->buffer; struct buffer_page *next_page; int ret; next_page = tail_page; rb_inc_page(cpu_buffer, &next_page); /* * If for some reason, we had an interrupt storm that made * it all the way around the buffer, bail, and warn * about it. */ if (unlikely(next_page == commit_page)) { local_inc(&cpu_buffer->commit_overrun); goto out_reset; } /* * This is where the fun begins! * * We are fighting against races between a reader that * could be on another CPU trying to swap its reader * page with the buffer head. * * We are also fighting against interrupts coming in and * moving the head or tail on us as well. * * If the next page is the head page then we have filled * the buffer, unless the commit page is still on the * reader page. */ if (rb_is_head_page(cpu_buffer, next_page, &tail_page->list)) { /* * If the commit is not on the reader page, then * move the header page. */ if (!rb_is_reader_page(cpu_buffer->commit_page)) { /* * If we are not in overwrite mode, * this is easy, just stop here. */ if (!(buffer->flags & RB_FL_OVERWRITE)) { local_inc(&cpu_buffer->dropped_events); goto out_reset; } ret = rb_handle_head_page(cpu_buffer, tail_page, next_page); if (ret < 0) goto out_reset; if (ret) goto out_again; } else { /* * We need to be careful here too. The * commit page could still be on the reader * page. We could have a small buffer, and * have filled up the buffer with events * from interrupts and such, and wrapped. * * Note, if the tail page is also the on the * reader_page, we let it move out. */ if (unlikely((cpu_buffer->commit_page != cpu_buffer->tail_page) && (cpu_buffer->commit_page == cpu_buffer->reader_page))) { local_inc(&cpu_buffer->commit_overrun); goto out_reset; } } } rb_tail_page_update(cpu_buffer, tail_page, next_page); out_again: rb_reset_tail(cpu_buffer, tail, info); /* Commit what we have for now. */ rb_end_commit(cpu_buffer); /* rb_end_commit() decs committing */ local_inc(&cpu_buffer->committing); /* fail and let the caller try again */ return ERR_PTR(-EAGAIN); out_reset: /* reset write */ rb_reset_tail(cpu_buffer, tail, info); return NULL; } /* Slow path, do not inline */ static noinline struct ring_buffer_event * rb_add_time_stamp(struct ring_buffer_event *event, u64 delta) { event->type_len = RINGBUF_TYPE_TIME_EXTEND; /* Not the first event on the page? */ if (rb_event_index(event)) { event->time_delta = delta & TS_MASK; event->array[0] = delta >> TS_SHIFT; } else { /* nope, just zero it */ event->time_delta = 0; event->array[0] = 0; } return skip_time_extend(event); } static inline bool rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event); /** * rb_update_event - update event type and data * @event: the event to update * @type: the type of event * @length: the size of the event field in the ring buffer * * Update the type and data fields of the event. The length * is the actual size that is written to the ring buffer, * and with this, we can determine what to place into the * data field. */ static void rb_update_event(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event, struct rb_event_info *info) { unsigned length = info->length; u64 delta = info->delta; /* Only a commit updates the timestamp */ if (unlikely(!rb_event_is_commit(cpu_buffer, event))) delta = 0; /* * If we need to add a timestamp, then we * add it to the start of the resevered space. */ if (unlikely(info->add_timestamp)) { event = rb_add_time_stamp(event, delta); length -= RB_LEN_TIME_EXTEND; delta = 0; } event->time_delta = delta; length -= RB_EVNT_HDR_SIZE; if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) { event->type_len = 0; event->array[0] = length; } else event->type_len = DIV_ROUND_UP(length, RB_ALIGNMENT); } static unsigned rb_calculate_event_length(unsigned length) { struct ring_buffer_event event; /* Used only for sizeof array */ /* zero length can cause confusions */ if (!length) length++; if (length > RB_MAX_SMALL_DATA || RB_FORCE_8BYTE_ALIGNMENT) length += sizeof(event.array[0]); length += RB_EVNT_HDR_SIZE; length = ALIGN(length, RB_ARCH_ALIGNMENT); /* * In case the time delta is larger than the 27 bits for it * in the header, we need to add a timestamp. If another * event comes in when trying to discard this one to increase * the length, then the timestamp will be added in the allocated * space of this event. If length is bigger than the size needed * for the TIME_EXTEND, then padding has to be used. The events * length must be either RB_LEN_TIME_EXTEND, or greater than or equal * to RB_LEN_TIME_EXTEND + 8, as 8 is the minimum size for padding. * As length is a multiple of 4, we only need to worry if it * is 12 (RB_LEN_TIME_EXTEND + 4). */ if (length == RB_LEN_TIME_EXTEND + RB_ALIGNMENT) length += RB_ALIGNMENT; return length; } #ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK static inline bool sched_clock_stable(void) { return true; } #endif static inline int rb_try_to_discard(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { unsigned long new_index, old_index; struct buffer_page *bpage; unsigned long index; unsigned long addr; new_index = rb_event_index(event); old_index = new_index + rb_event_ts_length(event); addr = (unsigned long)event; addr &= PAGE_MASK; bpage = READ_ONCE(cpu_buffer->tail_page); if (bpage->page == (void *)addr && rb_page_write(bpage) == old_index) { unsigned long write_mask = local_read(&bpage->write) & ~RB_WRITE_MASK; unsigned long event_length = rb_event_length(event); /* * This is on the tail page. It is possible that * a write could come in and move the tail page * and write to the next page. That is fine * because we just shorten what is on this page. */ old_index += write_mask; new_index += write_mask; index = local_cmpxchg(&bpage->write, old_index, new_index); if (index == old_index) { /* update counters */ local_sub(event_length, &cpu_buffer->entries_bytes); return 1; } } /* could not discard */ return 0; } static void rb_start_commit(struct ring_buffer_per_cpu *cpu_buffer) { local_inc(&cpu_buffer->committing); local_inc(&cpu_buffer->commits); } static void rb_set_commit_to_write(struct ring_buffer_per_cpu *cpu_buffer) { unsigned long max_count; /* * We only race with interrupts and NMIs on this CPU. * If we own the commit event, then we can commit * all others that interrupted us, since the interruptions * are in stack format (they finish before they come * back to us). This allows us to do a simple loop to * assign the commit to the tail. */ again: max_count = cpu_buffer->nr_pages * 100; while (cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page)) { if (RB_WARN_ON(cpu_buffer, !(--max_count))) return; if (RB_WARN_ON(cpu_buffer, rb_is_reader_page(cpu_buffer->tail_page))) return; local_set(&cpu_buffer->commit_page->page->commit, rb_page_write(cpu_buffer->commit_page)); rb_inc_page(cpu_buffer, &cpu_buffer->commit_page); /* Only update the write stamp if the page has an event */ if (rb_page_write(cpu_buffer->commit_page)) cpu_buffer->write_stamp = cpu_buffer->commit_page->page->time_stamp; /* add barrier to keep gcc from optimizing too much */ barrier(); } while (rb_commit_index(cpu_buffer) != rb_page_write(cpu_buffer->commit_page)) { local_set(&cpu_buffer->commit_page->page->commit, rb_page_write(cpu_buffer->commit_page)); RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->commit_page->page->commit) & ~RB_WRITE_MASK); barrier(); } /* again, keep gcc from optimizing */ barrier(); /* * If an interrupt came in just after the first while loop * and pushed the tail page forward, we will be left with * a dangling commit that will never go forward. */ if (unlikely(cpu_buffer->commit_page != READ_ONCE(cpu_buffer->tail_page))) goto again; } static inline void rb_end_commit(struct ring_buffer_per_cpu *cpu_buffer) { unsigned long commits; if (RB_WARN_ON(cpu_buffer, !local_read(&cpu_buffer->committing))) return; again: commits = local_read(&cpu_buffer->commits); /* synchronize with interrupts */ barrier(); if (local_read(&cpu_buffer->committing) == 1) rb_set_commit_to_write(cpu_buffer); local_dec(&cpu_buffer->committing); /* synchronize with interrupts */ barrier(); /* * Need to account for interrupts coming in between the * updating of the commit page and the clearing of the * committing counter. */ if (unlikely(local_read(&cpu_buffer->commits) != commits) && !local_read(&cpu_buffer->committing)) { local_inc(&cpu_buffer->committing); goto again; } } static inline void rb_event_discard(struct ring_buffer_event *event) { if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) event = skip_time_extend(event); /* array[0] holds the actual length for the discarded event */ event->array[0] = rb_event_data_length(event) - RB_EVNT_HDR_SIZE; event->type_len = RINGBUF_TYPE_PADDING; /* time delta must be non zero */ if (!event->time_delta) event->time_delta = 1; } static inline bool rb_event_is_commit(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { unsigned long addr = (unsigned long)event; unsigned long index; index = rb_event_index(event); addr &= PAGE_MASK; return cpu_buffer->commit_page->page == (void *)addr && rb_commit_index(cpu_buffer) == index; } static void rb_update_write_stamp(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { u64 delta; /* * The event first in the commit queue updates the * time stamp. */ if (rb_event_is_commit(cpu_buffer, event)) { /* * A commit event that is first on a page * updates the write timestamp with the page stamp */ if (!rb_event_index(event)) cpu_buffer->write_stamp = cpu_buffer->commit_page->page->time_stamp; else if (event->type_len == RINGBUF_TYPE_TIME_EXTEND) { delta = event->array[0]; delta <<= TS_SHIFT; delta += event->time_delta; cpu_buffer->write_stamp += delta; } else cpu_buffer->write_stamp += event->time_delta; } } static void rb_commit(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { local_inc(&cpu_buffer->entries); rb_update_write_stamp(cpu_buffer, event); rb_end_commit(cpu_buffer); } static __always_inline void rb_wakeups(struct ring_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer) { bool pagebusy; if (buffer->irq_work.waiters_pending) { buffer->irq_work.waiters_pending = false; /* irq_work_queue() supplies it's own memory barriers */ irq_work_queue(&buffer->irq_work.work); } if (cpu_buffer->irq_work.waiters_pending) { cpu_buffer->irq_work.waiters_pending = false; /* irq_work_queue() supplies it's own memory barriers */ irq_work_queue(&cpu_buffer->irq_work.work); } pagebusy = cpu_buffer->reader_page == cpu_buffer->commit_page; if (!pagebusy && cpu_buffer->irq_work.full_waiters_pending) { cpu_buffer->irq_work.wakeup_full = true; cpu_buffer->irq_work.full_waiters_pending = false; /* irq_work_queue() supplies it's own memory barriers */ irq_work_queue(&cpu_buffer->irq_work.work); } } /* * The lock and unlock are done within a preempt disable section. * The current_context per_cpu variable can only be modified * by the current task between lock and unlock. But it can * be modified more than once via an interrupt. To pass this * information from the lock to the unlock without having to * access the 'in_interrupt()' functions again (which do show * a bit of overhead in something as critical as function tracing, * we use a bitmask trick. * * bit 0 = NMI context * bit 1 = IRQ context * bit 2 = SoftIRQ context * bit 3 = normal context. * * This works because this is the order of contexts that can * preempt other contexts. A SoftIRQ never preempts an IRQ * context. * * When the context is determined, the corresponding bit is * checked and set (if it was set, then a recursion of that context * happened). * * On unlock, we need to clear this bit. To do so, just subtract * 1 from the current_context and AND it to itself. * * (binary) * 101 - 1 = 100 * 101 & 100 = 100 (clearing bit zero) * * 1010 - 1 = 1001 * 1010 & 1001 = 1000 (clearing bit 1) * * The least significant bit can be cleared this way, and it * just so happens that it is the same bit corresponding to * the current context. */ static __always_inline int trace_recursive_lock(struct ring_buffer_per_cpu *cpu_buffer) { unsigned int val = cpu_buffer->current_context; int bit; if (in_interrupt()) { if (in_nmi()) bit = RB_CTX_NMI; else if (in_irq()) bit = RB_CTX_IRQ; else bit = RB_CTX_SOFTIRQ; } else bit = RB_CTX_NORMAL; if (unlikely(val & (1 << bit))) return 1; val |= (1 << bit); cpu_buffer->current_context = val; return 0; } static __always_inline void trace_recursive_unlock(struct ring_buffer_per_cpu *cpu_buffer) { cpu_buffer->current_context &= cpu_buffer->current_context - 1; } /** * ring_buffer_unlock_commit - commit a reserved * @buffer: The buffer to commit to * @event: The event pointer to commit. * * This commits the data to the ring buffer, and releases any locks held. * * Must be paired with ring_buffer_lock_reserve. */ int ring_buffer_unlock_commit(struct ring_buffer *buffer, struct ring_buffer_event *event) { struct ring_buffer_per_cpu *cpu_buffer; int cpu = raw_smp_processor_id(); cpu_buffer = buffer->buffers[cpu]; rb_commit(cpu_buffer, event); rb_wakeups(buffer, cpu_buffer); trace_recursive_unlock(cpu_buffer); preempt_enable_notrace(); return 0; } EXPORT_SYMBOL_GPL(ring_buffer_unlock_commit); static noinline void rb_handle_timestamp(struct ring_buffer_per_cpu *cpu_buffer, struct rb_event_info *info) { WARN_ONCE(info->delta > (1ULL << 59), KERN_WARNING "Delta way too big! %llu ts=%llu write stamp = %llu\n%s", (unsigned long long)info->delta, (unsigned long long)info->ts, (unsigned long long)cpu_buffer->write_stamp, sched_clock_stable() ? "" : "If you just came from a suspend/resume,\n" "please switch to the trace global clock:\n" " echo global > /sys/kernel/debug/tracing/trace_clock\n"); info->add_timestamp = 1; } static struct ring_buffer_event * __rb_reserve_next(struct ring_buffer_per_cpu *cpu_buffer, struct rb_event_info *info) { struct ring_buffer_event *event; struct buffer_page *tail_page; unsigned long tail, write; /* * If the time delta since the last event is too big to * hold in the time field of the event, then we append a * TIME EXTEND event ahead of the data event. */ if (unlikely(info->add_timestamp)) info->length += RB_LEN_TIME_EXTEND; /* Don't let the compiler play games with cpu_buffer->tail_page */ tail_page = info->tail_page = READ_ONCE(cpu_buffer->tail_page); write = local_add_return(info->length, &tail_page->write); /* set write to only the index of the write */ write &= RB_WRITE_MASK; tail = write - info->length; /* * If this is the first commit on the page, then it has the same * timestamp as the page itself. */ if (!tail) info->delta = 0; /* See if we shot pass the end of this buffer page */ if (unlikely(write > BUF_PAGE_SIZE)) return rb_move_tail(cpu_buffer, tail, info); /* We reserved something on the buffer */ event = __rb_page_index(tail_page, tail); kmemcheck_annotate_bitfield(event, bitfield); rb_update_event(cpu_buffer, event, info); local_inc(&tail_page->entries); /* * If this is the first commit on the page, then update * its timestamp. */ if (!tail) tail_page->page->time_stamp = info->ts; /* account for these added bytes */ local_add(info->length, &cpu_buffer->entries_bytes); return event; } static struct ring_buffer_event * rb_reserve_next_event(struct ring_buffer *buffer, struct ring_buffer_per_cpu *cpu_buffer, unsigned long length) { struct ring_buffer_event *event; struct rb_event_info info; int nr_loops = 0; u64 diff; rb_start_commit(cpu_buffer); #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP /* * Due to the ability to swap a cpu buffer from a buffer * it is possible it was swapped before we committed. * (committing stops a swap). We check for it here and * if it happened, we have to fail the write. */ barrier(); if (unlikely(ACCESS_ONCE(cpu_buffer->buffer) != buffer)) { local_dec(&cpu_buffer->committing); local_dec(&cpu_buffer->commits); return NULL; } #endif info.length = rb_calculate_event_length(length); again: info.add_timestamp = 0; info.delta = 0; /* * We allow for interrupts to reenter here and do a trace. * If one does, it will cause this original code to loop * back here. Even with heavy interrupts happening, this * should only happen a few times in a row. If this happens * 1000 times in a row, there must be either an interrupt * storm or we have something buggy. * Bail! */ if (RB_WARN_ON(cpu_buffer, ++nr_loops > 1000)) goto out_fail; info.ts = rb_time_stamp(cpu_buffer->buffer); diff = info.ts - cpu_buffer->write_stamp; /* make sure this diff is calculated here */ barrier(); /* Did the write stamp get updated already? */ if (likely(info.ts >= cpu_buffer->write_stamp)) { info.delta = diff; if (unlikely(test_time_stamp(info.delta))) rb_handle_timestamp(cpu_buffer, &info); } event = __rb_reserve_next(cpu_buffer, &info); if (unlikely(PTR_ERR(event) == -EAGAIN)) { if (info.add_timestamp) info.length -= RB_LEN_TIME_EXTEND; goto again; } if (!event) goto out_fail; return event; out_fail: rb_end_commit(cpu_buffer); return NULL; } /** * ring_buffer_lock_reserve - reserve a part of the buffer * @buffer: the ring buffer to reserve from * @length: the length of the data to reserve (excluding event header) * * Returns a reseverd event on the ring buffer to copy directly to. * The user of this interface will need to get the body to write into * and can use the ring_buffer_event_data() interface. * * The length is the length of the data needed, not the event length * which also includes the event header. * * Must be paired with ring_buffer_unlock_commit, unless NULL is returned. * If NULL is returned, then nothing has been allocated or locked. */ struct ring_buffer_event * ring_buffer_lock_reserve(struct ring_buffer *buffer, unsigned long length) { struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_event *event; int cpu; /* If we are tracing schedule, we don't want to recurse */ preempt_disable_notrace(); if (unlikely(atomic_read(&buffer->record_disabled))) goto out; cpu = raw_smp_processor_id(); if (unlikely(!cpumask_test_cpu(cpu, buffer->cpumask))) goto out; cpu_buffer = buffer->buffers[cpu]; if (unlikely(atomic_read(&cpu_buffer->record_disabled))) goto out; if (unlikely(length > BUF_MAX_DATA_SIZE)) goto out; if (unlikely(trace_recursive_lock(cpu_buffer))) goto out; event = rb_reserve_next_event(buffer, cpu_buffer, length); if (!event) goto out_unlock; return event; out_unlock: trace_recursive_unlock(cpu_buffer); out: preempt_enable_notrace(); return NULL; } EXPORT_SYMBOL_GPL(ring_buffer_lock_reserve); /* * Decrement the entries to the page that an event is on. * The event does not even need to exist, only the pointer * to the page it is on. This may only be called before the commit * takes place. */ static inline void rb_decrement_entry(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { unsigned long addr = (unsigned long)event; struct buffer_page *bpage = cpu_buffer->commit_page; struct buffer_page *start; addr &= PAGE_MASK; /* Do the likely case first */ if (likely(bpage->page == (void *)addr)) { local_dec(&bpage->entries); return; } /* * Because the commit page may be on the reader page we * start with the next page and check the end loop there. */ rb_inc_page(cpu_buffer, &bpage); start = bpage; do { if (bpage->page == (void *)addr) { local_dec(&bpage->entries); return; } rb_inc_page(cpu_buffer, &bpage); } while (bpage != start); /* commit not part of this buffer?? */ RB_WARN_ON(cpu_buffer, 1); } /** * ring_buffer_commit_discard - discard an event that has not been committed * @buffer: the ring buffer * @event: non committed event to discard * * Sometimes an event that is in the ring buffer needs to be ignored. * This function lets the user discard an event in the ring buffer * and then that event will not be read later. * * This function only works if it is called before the the item has been * committed. It will try to free the event from the ring buffer * if another event has not been added behind it. * * If another event has been added behind it, it will set the event * up as discarded, and perform the commit. * * If this function is called, do not call ring_buffer_unlock_commit on * the event. */ void ring_buffer_discard_commit(struct ring_buffer *buffer, struct ring_buffer_event *event) { struct ring_buffer_per_cpu *cpu_buffer; int cpu; /* The event is discarded regardless */ rb_event_discard(event); cpu = smp_processor_id(); cpu_buffer = buffer->buffers[cpu]; /* * This must only be called if the event has not been * committed yet. Thus we can assume that preemption * is still disabled. */ RB_WARN_ON(buffer, !local_read(&cpu_buffer->committing)); rb_decrement_entry(cpu_buffer, event); if (rb_try_to_discard(cpu_buffer, event)) goto out; /* * The commit is still visible by the reader, so we * must still update the timestamp. */ rb_update_write_stamp(cpu_buffer, event); out: rb_end_commit(cpu_buffer); trace_recursive_unlock(cpu_buffer); preempt_enable_notrace(); } EXPORT_SYMBOL_GPL(ring_buffer_discard_commit); /** * ring_buffer_write - write data to the buffer without reserving * @buffer: The ring buffer to write to. * @length: The length of the data being written (excluding the event header) * @data: The data to write to the buffer. * * This is like ring_buffer_lock_reserve and ring_buffer_unlock_commit as * one function. If you already have the data to write to the buffer, it * may be easier to simply call this function. * * Note, like ring_buffer_lock_reserve, the length is the length of the data * and not the length of the event which would hold the header. */ int ring_buffer_write(struct ring_buffer *buffer, unsigned long length, void *data) { struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_event *event; void *body; int ret = -EBUSY; int cpu; preempt_disable_notrace(); if (atomic_read(&buffer->record_disabled)) goto out; cpu = raw_smp_processor_id(); if (!cpumask_test_cpu(cpu, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu]; if (atomic_read(&cpu_buffer->record_disabled)) goto out; if (length > BUF_MAX_DATA_SIZE) goto out; if (unlikely(trace_recursive_lock(cpu_buffer))) goto out; event = rb_reserve_next_event(buffer, cpu_buffer, length); if (!event) goto out_unlock; body = rb_event_data(event); memcpy(body, data, length); rb_commit(cpu_buffer, event); rb_wakeups(buffer, cpu_buffer); ret = 0; out_unlock: trace_recursive_unlock(cpu_buffer); out: preempt_enable_notrace(); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_write); static bool rb_per_cpu_empty(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *reader = cpu_buffer->reader_page; struct buffer_page *head = rb_set_head_page(cpu_buffer); struct buffer_page *commit = cpu_buffer->commit_page; /* In case of error, head will be NULL */ if (unlikely(!head)) return true; return reader->read == rb_page_commit(reader) && (commit == reader || (commit == head && head->read == rb_page_commit(commit))); } /** * ring_buffer_record_disable - stop all writes into the buffer * @buffer: The ring buffer to stop writes to. * * This prevents all writes to the buffer. Any attempt to write * to the buffer after this will fail and return NULL. * * The caller should call synchronize_sched() after this. */ void ring_buffer_record_disable(struct ring_buffer *buffer) { atomic_inc(&buffer->record_disabled); } EXPORT_SYMBOL_GPL(ring_buffer_record_disable); /** * ring_buffer_record_enable - enable writes to the buffer * @buffer: The ring buffer to enable writes * * Note, multiple disables will need the same number of enables * to truly enable the writing (much like preempt_disable). */ void ring_buffer_record_enable(struct ring_buffer *buffer) { atomic_dec(&buffer->record_disabled); } EXPORT_SYMBOL_GPL(ring_buffer_record_enable); /** * ring_buffer_record_off - stop all writes into the buffer * @buffer: The ring buffer to stop writes to. * * This prevents all writes to the buffer. Any attempt to write * to the buffer after this will fail and return NULL. * * This is different than ring_buffer_record_disable() as * it works like an on/off switch, where as the disable() version * must be paired with a enable(). */ void ring_buffer_record_off(struct ring_buffer *buffer) { unsigned int rd; unsigned int new_rd; do { rd = atomic_read(&buffer->record_disabled); new_rd = rd | RB_BUFFER_OFF; } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd); } EXPORT_SYMBOL_GPL(ring_buffer_record_off); /** * ring_buffer_record_on - restart writes into the buffer * @buffer: The ring buffer to start writes to. * * This enables all writes to the buffer that was disabled by * ring_buffer_record_off(). * * This is different than ring_buffer_record_enable() as * it works like an on/off switch, where as the enable() version * must be paired with a disable(). */ void ring_buffer_record_on(struct ring_buffer *buffer) { unsigned int rd; unsigned int new_rd; do { rd = atomic_read(&buffer->record_disabled); new_rd = rd & ~RB_BUFFER_OFF; } while (atomic_cmpxchg(&buffer->record_disabled, rd, new_rd) != rd); } EXPORT_SYMBOL_GPL(ring_buffer_record_on); /** * ring_buffer_record_is_on - return true if the ring buffer can write * @buffer: The ring buffer to see if write is enabled * * Returns true if the ring buffer is in a state that it accepts writes. */ int ring_buffer_record_is_on(struct ring_buffer *buffer) { return !atomic_read(&buffer->record_disabled); } /** * ring_buffer_record_disable_cpu - stop all writes into the cpu_buffer * @buffer: The ring buffer to stop writes to. * @cpu: The CPU buffer to stop * * This prevents all writes to the buffer. Any attempt to write * to the buffer after this will fail and return NULL. * * The caller should call synchronize_sched() after this. */ void ring_buffer_record_disable_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return; cpu_buffer = buffer->buffers[cpu]; atomic_inc(&cpu_buffer->record_disabled); } EXPORT_SYMBOL_GPL(ring_buffer_record_disable_cpu); /** * ring_buffer_record_enable_cpu - enable writes to the buffer * @buffer: The ring buffer to enable writes * @cpu: The CPU to enable. * * Note, multiple disables will need the same number of enables * to truly enable the writing (much like preempt_disable). */ void ring_buffer_record_enable_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return; cpu_buffer = buffer->buffers[cpu]; atomic_dec(&cpu_buffer->record_disabled); } EXPORT_SYMBOL_GPL(ring_buffer_record_enable_cpu); /* * The total entries in the ring buffer is the running counter * of entries entered into the ring buffer, minus the sum of * the entries read from the ring buffer and the number of * entries that were overwritten. */ static inline unsigned long rb_num_of_entries(struct ring_buffer_per_cpu *cpu_buffer) { return local_read(&cpu_buffer->entries) - (local_read(&cpu_buffer->overrun) + cpu_buffer->read); } /** * ring_buffer_oldest_event_ts - get the oldest event timestamp from the buffer * @buffer: The ring buffer * @cpu: The per CPU buffer to read from. */ u64 ring_buffer_oldest_event_ts(struct ring_buffer *buffer, int cpu) { unsigned long flags; struct ring_buffer_per_cpu *cpu_buffer; struct buffer_page *bpage; u64 ret = 0; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); /* * if the tail is on reader_page, oldest time stamp is on the reader * page */ if (cpu_buffer->tail_page == cpu_buffer->reader_page) bpage = cpu_buffer->reader_page; else bpage = rb_set_head_page(cpu_buffer); if (bpage) ret = bpage->page->time_stamp; raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_oldest_event_ts); /** * ring_buffer_bytes_cpu - get the number of bytes consumed in a cpu buffer * @buffer: The ring buffer * @cpu: The per CPU buffer to read from. */ unsigned long ring_buffer_bytes_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long ret; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; ret = local_read(&cpu_buffer->entries_bytes) - cpu_buffer->read_bytes; return ret; } EXPORT_SYMBOL_GPL(ring_buffer_bytes_cpu); /** * ring_buffer_entries_cpu - get the number of entries in a cpu buffer * @buffer: The ring buffer * @cpu: The per CPU buffer to get the entries from. */ unsigned long ring_buffer_entries_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; return rb_num_of_entries(cpu_buffer); } EXPORT_SYMBOL_GPL(ring_buffer_entries_cpu); /** * ring_buffer_overrun_cpu - get the number of overruns caused by the ring * buffer wrapping around (only if RB_FL_OVERWRITE is on). * @buffer: The ring buffer * @cpu: The per CPU buffer to get the number of overruns from */ unsigned long ring_buffer_overrun_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long ret; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; ret = local_read(&cpu_buffer->overrun); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_overrun_cpu); /** * ring_buffer_commit_overrun_cpu - get the number of overruns caused by * commits failing due to the buffer wrapping around while there are uncommitted * events, such as during an interrupt storm. * @buffer: The ring buffer * @cpu: The per CPU buffer to get the number of overruns from */ unsigned long ring_buffer_commit_overrun_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long ret; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; ret = local_read(&cpu_buffer->commit_overrun); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_commit_overrun_cpu); /** * ring_buffer_dropped_events_cpu - get the number of dropped events caused by * the ring buffer filling up (only if RB_FL_OVERWRITE is off). * @buffer: The ring buffer * @cpu: The per CPU buffer to get the number of overruns from */ unsigned long ring_buffer_dropped_events_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long ret; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; ret = local_read(&cpu_buffer->dropped_events); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_dropped_events_cpu); /** * ring_buffer_read_events_cpu - get the number of events successfully read * @buffer: The ring buffer * @cpu: The per CPU buffer to get the number of events read */ unsigned long ring_buffer_read_events_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; cpu_buffer = buffer->buffers[cpu]; return cpu_buffer->read; } EXPORT_SYMBOL_GPL(ring_buffer_read_events_cpu); /** * ring_buffer_entries - get the number of entries in a buffer * @buffer: The ring buffer * * Returns the total number of entries in the ring buffer * (all CPU entries) */ unsigned long ring_buffer_entries(struct ring_buffer *buffer) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long entries = 0; int cpu; /* if you care about this being correct, lock the buffer */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; entries += rb_num_of_entries(cpu_buffer); } return entries; } EXPORT_SYMBOL_GPL(ring_buffer_entries); /** * ring_buffer_overruns - get the number of overruns in buffer * @buffer: The ring buffer * * Returns the total number of overruns in the ring buffer * (all CPU entries) */ unsigned long ring_buffer_overruns(struct ring_buffer *buffer) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long overruns = 0; int cpu; /* if you care about this being correct, lock the buffer */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; overruns += local_read(&cpu_buffer->overrun); } return overruns; } EXPORT_SYMBOL_GPL(ring_buffer_overruns); static void rb_iter_reset(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer; /* Iterator usage is expected to have record disabled */ iter->head_page = cpu_buffer->reader_page; iter->head = cpu_buffer->reader_page->read; iter->cache_reader_page = iter->head_page; iter->cache_read = cpu_buffer->read; if (iter->head) iter->read_stamp = cpu_buffer->read_stamp; else iter->read_stamp = iter->head_page->page->time_stamp; } /** * ring_buffer_iter_reset - reset an iterator * @iter: The iterator to reset * * Resets the iterator, so that it will start from the beginning * again. */ void ring_buffer_iter_reset(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long flags; if (!iter) return; cpu_buffer = iter->cpu_buffer; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); rb_iter_reset(iter); raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); } EXPORT_SYMBOL_GPL(ring_buffer_iter_reset); /** * ring_buffer_iter_empty - check if an iterator has no more to read * @iter: The iterator to check */ int ring_buffer_iter_empty(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer; cpu_buffer = iter->cpu_buffer; return iter->head_page == cpu_buffer->commit_page && iter->head == rb_commit_index(cpu_buffer); } EXPORT_SYMBOL_GPL(ring_buffer_iter_empty); static void rb_update_read_stamp(struct ring_buffer_per_cpu *cpu_buffer, struct ring_buffer_event *event) { u64 delta; switch (event->type_len) { case RINGBUF_TYPE_PADDING: return; case RINGBUF_TYPE_TIME_EXTEND: delta = event->array[0]; delta <<= TS_SHIFT; delta += event->time_delta; cpu_buffer->read_stamp += delta; return; case RINGBUF_TYPE_TIME_STAMP: /* FIXME: not implemented */ return; case RINGBUF_TYPE_DATA: cpu_buffer->read_stamp += event->time_delta; return; default: BUG(); } return; } static void rb_update_iter_read_stamp(struct ring_buffer_iter *iter, struct ring_buffer_event *event) { u64 delta; switch (event->type_len) { case RINGBUF_TYPE_PADDING: return; case RINGBUF_TYPE_TIME_EXTEND: delta = event->array[0]; delta <<= TS_SHIFT; delta += event->time_delta; iter->read_stamp += delta; return; case RINGBUF_TYPE_TIME_STAMP: /* FIXME: not implemented */ return; case RINGBUF_TYPE_DATA: iter->read_stamp += event->time_delta; return; default: BUG(); } return; } static struct buffer_page * rb_get_reader_page(struct ring_buffer_per_cpu *cpu_buffer) { struct buffer_page *reader = NULL; unsigned long overwrite; unsigned long flags; int nr_loops = 0; int ret; local_irq_save(flags); arch_spin_lock(&cpu_buffer->lock); again: /* * This should normally only loop twice. But because the * start of the reader inserts an empty page, it causes * a case where we will loop three times. There should be no * reason to loop four times (that I know of). */ if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) { reader = NULL; goto out; } reader = cpu_buffer->reader_page; /* If there's more to read, return this page */ if (cpu_buffer->reader_page->read < rb_page_size(reader)) goto out; /* Never should we have an index greater than the size */ if (RB_WARN_ON(cpu_buffer, cpu_buffer->reader_page->read > rb_page_size(reader))) goto out; /* check if we caught up to the tail */ reader = NULL; if (cpu_buffer->commit_page == cpu_buffer->reader_page) goto out; /* Don't bother swapping if the ring buffer is empty */ if (rb_num_of_entries(cpu_buffer) == 0) goto out; /* * Reset the reader page to size zero. */ local_set(&cpu_buffer->reader_page->write, 0); local_set(&cpu_buffer->reader_page->entries, 0); local_set(&cpu_buffer->reader_page->page->commit, 0); cpu_buffer->reader_page->real_end = 0; spin: /* * Splice the empty reader page into the list around the head. */ reader = rb_set_head_page(cpu_buffer); if (!reader) goto out; cpu_buffer->reader_page->list.next = rb_list_head(reader->list.next); cpu_buffer->reader_page->list.prev = reader->list.prev; /* * cpu_buffer->pages just needs to point to the buffer, it * has no specific buffer page to point to. Lets move it out * of our way so we don't accidentally swap it. */ cpu_buffer->pages = reader->list.prev; /* The reader page will be pointing to the new head */ rb_set_list_to_head(cpu_buffer, &cpu_buffer->reader_page->list); /* * We want to make sure we read the overruns after we set up our * pointers to the next object. The writer side does a * cmpxchg to cross pages which acts as the mb on the writer * side. Note, the reader will constantly fail the swap * while the writer is updating the pointers, so this * guarantees that the overwrite recorded here is the one we * want to compare with the last_overrun. */ smp_mb(); overwrite = local_read(&(cpu_buffer->overrun)); /* * Here's the tricky part. * * We need to move the pointer past the header page. * But we can only do that if a writer is not currently * moving it. The page before the header page has the * flag bit '1' set if it is pointing to the page we want. * but if the writer is in the process of moving it * than it will be '2' or already moved '0'. */ ret = rb_head_page_replace(reader, cpu_buffer->reader_page); /* * If we did not convert it, then we must try again. */ if (!ret) goto spin; /* * Yeah! We succeeded in replacing the page. * * Now make the new head point back to the reader page. */ rb_list_head(reader->list.next)->prev = &cpu_buffer->reader_page->list; rb_inc_page(cpu_buffer, &cpu_buffer->head_page); /* Finally update the reader page to the new head */ cpu_buffer->reader_page = reader; cpu_buffer->reader_page->read = 0; if (overwrite != cpu_buffer->last_overrun) { cpu_buffer->lost_events = overwrite - cpu_buffer->last_overrun; cpu_buffer->last_overrun = overwrite; } goto again; out: /* Update the read_stamp on the first event */ if (reader && reader->read == 0) cpu_buffer->read_stamp = reader->page->time_stamp; arch_spin_unlock(&cpu_buffer->lock); local_irq_restore(flags); return reader; } static void rb_advance_reader(struct ring_buffer_per_cpu *cpu_buffer) { struct ring_buffer_event *event; struct buffer_page *reader; unsigned length; reader = rb_get_reader_page(cpu_buffer); /* This function should not be called when buffer is empty */ if (RB_WARN_ON(cpu_buffer, !reader)) return; event = rb_reader_event(cpu_buffer); if (event->type_len <= RINGBUF_TYPE_DATA_TYPE_LEN_MAX) cpu_buffer->read++; rb_update_read_stamp(cpu_buffer, event); length = rb_event_length(event); cpu_buffer->reader_page->read += length; } static void rb_advance_iter(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_event *event; unsigned length; cpu_buffer = iter->cpu_buffer; /* * Check if we are at the end of the buffer. */ if (iter->head >= rb_page_size(iter->head_page)) { /* discarded commits can make the page empty */ if (iter->head_page == cpu_buffer->commit_page) return; rb_inc_iter(iter); return; } event = rb_iter_head_event(iter); length = rb_event_length(event); /* * This should not be called to advance the header if we are * at the tail of the buffer. */ if (RB_WARN_ON(cpu_buffer, (iter->head_page == cpu_buffer->commit_page) && (iter->head + length > rb_commit_index(cpu_buffer)))) return; rb_update_iter_read_stamp(iter, event); iter->head += length; /* check for end of page padding */ if ((iter->head >= rb_page_size(iter->head_page)) && (iter->head_page != cpu_buffer->commit_page)) rb_inc_iter(iter); } static int rb_lost_events(struct ring_buffer_per_cpu *cpu_buffer) { return cpu_buffer->lost_events; } static struct ring_buffer_event * rb_buffer_peek(struct ring_buffer_per_cpu *cpu_buffer, u64 *ts, unsigned long *lost_events) { struct ring_buffer_event *event; struct buffer_page *reader; int nr_loops = 0; again: /* * We repeat when a time extend is encountered. * Since the time extend is always attached to a data event, * we should never loop more than once. * (We never hit the following condition more than twice). */ if (RB_WARN_ON(cpu_buffer, ++nr_loops > 2)) return NULL; reader = rb_get_reader_page(cpu_buffer); if (!reader) return NULL; event = rb_reader_event(cpu_buffer); switch (event->type_len) { case RINGBUF_TYPE_PADDING: if (rb_null_event(event)) RB_WARN_ON(cpu_buffer, 1); /* * Because the writer could be discarding every * event it creates (which would probably be bad) * if we were to go back to "again" then we may never * catch up, and will trigger the warn on, or lock * the box. Return the padding, and we will release * the current locks, and try again. */ return event; case RINGBUF_TYPE_TIME_EXTEND: /* Internal data, OK to advance */ rb_advance_reader(cpu_buffer); goto again; case RINGBUF_TYPE_TIME_STAMP: /* FIXME: not implemented */ rb_advance_reader(cpu_buffer); goto again; case RINGBUF_TYPE_DATA: if (ts) { *ts = cpu_buffer->read_stamp + event->time_delta; ring_buffer_normalize_time_stamp(cpu_buffer->buffer, cpu_buffer->cpu, ts); } if (lost_events) *lost_events = rb_lost_events(cpu_buffer); return event; default: BUG(); } return NULL; } EXPORT_SYMBOL_GPL(ring_buffer_peek); static struct ring_buffer_event * rb_iter_peek(struct ring_buffer_iter *iter, u64 *ts) { struct ring_buffer *buffer; struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_event *event; int nr_loops = 0; cpu_buffer = iter->cpu_buffer; buffer = cpu_buffer->buffer; /* * Check if someone performed a consuming read to * the buffer. A consuming read invalidates the iterator * and we need to reset the iterator in this case. */ if (unlikely(iter->cache_read != cpu_buffer->read || iter->cache_reader_page != cpu_buffer->reader_page)) rb_iter_reset(iter); again: if (ring_buffer_iter_empty(iter)) return NULL; /* * We repeat when a time extend is encountered or we hit * the end of the page. Since the time extend is always attached * to a data event, we should never loop more than three times. * Once for going to next page, once on time extend, and * finally once to get the event. * (We never hit the following condition more than thrice). */ if (RB_WARN_ON(cpu_buffer, ++nr_loops > 3)) return NULL; if (rb_per_cpu_empty(cpu_buffer)) return NULL; if (iter->head >= rb_page_size(iter->head_page)) { rb_inc_iter(iter); goto again; } event = rb_iter_head_event(iter); switch (event->type_len) { case RINGBUF_TYPE_PADDING: if (rb_null_event(event)) { rb_inc_iter(iter); goto again; } rb_advance_iter(iter); return event; case RINGBUF_TYPE_TIME_EXTEND: /* Internal data, OK to advance */ rb_advance_iter(iter); goto again; case RINGBUF_TYPE_TIME_STAMP: /* FIXME: not implemented */ rb_advance_iter(iter); goto again; case RINGBUF_TYPE_DATA: if (ts) { *ts = iter->read_stamp + event->time_delta; ring_buffer_normalize_time_stamp(buffer, cpu_buffer->cpu, ts); } return event; default: BUG(); } return NULL; } EXPORT_SYMBOL_GPL(ring_buffer_iter_peek); static inline bool rb_reader_lock(struct ring_buffer_per_cpu *cpu_buffer) { if (likely(!in_nmi())) { raw_spin_lock(&cpu_buffer->reader_lock); return true; } /* * If an NMI die dumps out the content of the ring buffer * trylock must be used to prevent a deadlock if the NMI * preempted a task that holds the ring buffer locks. If * we get the lock then all is fine, if not, then continue * to do the read, but this can corrupt the ring buffer, * so it must be permanently disabled from future writes. * Reading from NMI is a oneshot deal. */ if (raw_spin_trylock(&cpu_buffer->reader_lock)) return true; /* Continue without locking, but disable the ring buffer */ atomic_inc(&cpu_buffer->record_disabled); return false; } static inline void rb_reader_unlock(struct ring_buffer_per_cpu *cpu_buffer, bool locked) { if (likely(locked)) raw_spin_unlock(&cpu_buffer->reader_lock); return; } /** * ring_buffer_peek - peek at the next event to be read * @buffer: The ring buffer to read * @cpu: The cpu to peak at * @ts: The timestamp counter of this event. * @lost_events: a variable to store if events were lost (may be NULL) * * This will return the event that will be read next, but does * not consume the data. */ struct ring_buffer_event * ring_buffer_peek(struct ring_buffer *buffer, int cpu, u64 *ts, unsigned long *lost_events) { struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu]; struct ring_buffer_event *event; unsigned long flags; bool dolock; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return NULL; again: local_irq_save(flags); dolock = rb_reader_lock(cpu_buffer); event = rb_buffer_peek(cpu_buffer, ts, lost_events); if (event && event->type_len == RINGBUF_TYPE_PADDING) rb_advance_reader(cpu_buffer); rb_reader_unlock(cpu_buffer, dolock); local_irq_restore(flags); if (event && event->type_len == RINGBUF_TYPE_PADDING) goto again; return event; } /** * ring_buffer_iter_peek - peek at the next event to be read * @iter: The ring buffer iterator * @ts: The timestamp counter of this event. * * This will return the event that will be read next, but does * not increment the iterator. */ struct ring_buffer_event * ring_buffer_iter_peek(struct ring_buffer_iter *iter, u64 *ts) { struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer; struct ring_buffer_event *event; unsigned long flags; again: raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); event = rb_iter_peek(iter, ts); raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); if (event && event->type_len == RINGBUF_TYPE_PADDING) goto again; return event; } /** * ring_buffer_consume - return an event and consume it * @buffer: The ring buffer to get the next event from * @cpu: the cpu to read the buffer from * @ts: a variable to store the timestamp (may be NULL) * @lost_events: a variable to store if events were lost (may be NULL) * * Returns the next event in the ring buffer, and that event is consumed. * Meaning, that sequential reads will keep returning a different event, * and eventually empty the ring buffer if the producer is slower. */ struct ring_buffer_event * ring_buffer_consume(struct ring_buffer *buffer, int cpu, u64 *ts, unsigned long *lost_events) { struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_event *event = NULL; unsigned long flags; bool dolock; again: /* might be called in atomic */ preempt_disable(); if (!cpumask_test_cpu(cpu, buffer->cpumask)) goto out; cpu_buffer = buffer->buffers[cpu]; local_irq_save(flags); dolock = rb_reader_lock(cpu_buffer); event = rb_buffer_peek(cpu_buffer, ts, lost_events); if (event) { cpu_buffer->lost_events = 0; rb_advance_reader(cpu_buffer); } rb_reader_unlock(cpu_buffer, dolock); local_irq_restore(flags); out: preempt_enable(); if (event && event->type_len == RINGBUF_TYPE_PADDING) goto again; return event; } EXPORT_SYMBOL_GPL(ring_buffer_consume); /** * ring_buffer_read_prepare - Prepare for a non consuming read of the buffer * @buffer: The ring buffer to read from * @cpu: The cpu buffer to iterate over * * This performs the initial preparations necessary to iterate * through the buffer. Memory is allocated, buffer recording * is disabled, and the iterator pointer is returned to the caller. * * Disabling buffer recordng prevents the reading from being * corrupted. This is not a consuming read, so a producer is not * expected. * * After a sequence of ring_buffer_read_prepare calls, the user is * expected to make at least one call to ring_buffer_read_prepare_sync. * Afterwards, ring_buffer_read_start is invoked to get things going * for real. * * This overall must be paired with ring_buffer_read_finish. */ struct ring_buffer_iter * ring_buffer_read_prepare(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; struct ring_buffer_iter *iter; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return NULL; iter = kmalloc(sizeof(*iter), GFP_KERNEL); if (!iter) return NULL; cpu_buffer = buffer->buffers[cpu]; iter->cpu_buffer = cpu_buffer; atomic_inc(&buffer->resize_disabled); atomic_inc(&cpu_buffer->record_disabled); return iter; } EXPORT_SYMBOL_GPL(ring_buffer_read_prepare); /** * ring_buffer_read_prepare_sync - Synchronize a set of prepare calls * * All previously invoked ring_buffer_read_prepare calls to prepare * iterators will be synchronized. Afterwards, read_buffer_read_start * calls on those iterators are allowed. */ void ring_buffer_read_prepare_sync(void) { synchronize_sched(); } EXPORT_SYMBOL_GPL(ring_buffer_read_prepare_sync); /** * ring_buffer_read_start - start a non consuming read of the buffer * @iter: The iterator returned by ring_buffer_read_prepare * * This finalizes the startup of an iteration through the buffer. * The iterator comes from a call to ring_buffer_read_prepare and * an intervening ring_buffer_read_prepare_sync must have been * performed. * * Must be paired with ring_buffer_read_finish. */ void ring_buffer_read_start(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long flags; if (!iter) return; cpu_buffer = iter->cpu_buffer; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); arch_spin_lock(&cpu_buffer->lock); rb_iter_reset(iter); arch_spin_unlock(&cpu_buffer->lock); raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); } EXPORT_SYMBOL_GPL(ring_buffer_read_start); /** * ring_buffer_read_finish - finish reading the iterator of the buffer * @iter: The iterator retrieved by ring_buffer_start * * This re-enables the recording to the buffer, and frees the * iterator. */ void ring_buffer_read_finish(struct ring_buffer_iter *iter) { struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer; unsigned long flags; /* * Ring buffer is disabled from recording, here's a good place * to check the integrity of the ring buffer. * Must prevent readers from trying to read, as the check * clears the HEAD page and readers require it. */ raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); rb_check_pages(cpu_buffer); raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); atomic_dec(&cpu_buffer->record_disabled); atomic_dec(&cpu_buffer->buffer->resize_disabled); kfree(iter); } EXPORT_SYMBOL_GPL(ring_buffer_read_finish); /** * ring_buffer_read - read the next item in the ring buffer by the iterator * @iter: The ring buffer iterator * @ts: The time stamp of the event read. * * This reads the next event in the ring buffer and increments the iterator. */ struct ring_buffer_event * ring_buffer_read(struct ring_buffer_iter *iter, u64 *ts) { struct ring_buffer_event *event; struct ring_buffer_per_cpu *cpu_buffer = iter->cpu_buffer; unsigned long flags; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); again: event = rb_iter_peek(iter, ts); if (!event) goto out; if (event->type_len == RINGBUF_TYPE_PADDING) goto again; rb_advance_iter(iter); out: raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); return event; } EXPORT_SYMBOL_GPL(ring_buffer_read); /** * ring_buffer_size - return the size of the ring buffer (in bytes) * @buffer: The ring buffer. */ unsigned long ring_buffer_size(struct ring_buffer *buffer, int cpu) { /* * Earlier, this method returned * BUF_PAGE_SIZE * buffer->nr_pages * Since the nr_pages field is now removed, we have converted this to * return the per cpu buffer value. */ if (!cpumask_test_cpu(cpu, buffer->cpumask)) return 0; return BUF_PAGE_SIZE * buffer->buffers[cpu]->nr_pages; } EXPORT_SYMBOL_GPL(ring_buffer_size); static void rb_reset_cpu(struct ring_buffer_per_cpu *cpu_buffer) { rb_head_page_deactivate(cpu_buffer); cpu_buffer->head_page = list_entry(cpu_buffer->pages, struct buffer_page, list); local_set(&cpu_buffer->head_page->write, 0); local_set(&cpu_buffer->head_page->entries, 0); local_set(&cpu_buffer->head_page->page->commit, 0); cpu_buffer->head_page->read = 0; cpu_buffer->tail_page = cpu_buffer->head_page; cpu_buffer->commit_page = cpu_buffer->head_page; INIT_LIST_HEAD(&cpu_buffer->reader_page->list); INIT_LIST_HEAD(&cpu_buffer->new_pages); local_set(&cpu_buffer->reader_page->write, 0); local_set(&cpu_buffer->reader_page->entries, 0); local_set(&cpu_buffer->reader_page->page->commit, 0); cpu_buffer->reader_page->read = 0; local_set(&cpu_buffer->entries_bytes, 0); local_set(&cpu_buffer->overrun, 0); local_set(&cpu_buffer->commit_overrun, 0); local_set(&cpu_buffer->dropped_events, 0); local_set(&cpu_buffer->entries, 0); local_set(&cpu_buffer->committing, 0); local_set(&cpu_buffer->commits, 0); cpu_buffer->read = 0; cpu_buffer->read_bytes = 0; cpu_buffer->write_stamp = 0; cpu_buffer->read_stamp = 0; cpu_buffer->lost_events = 0; cpu_buffer->last_overrun = 0; rb_head_page_activate(cpu_buffer); } /** * ring_buffer_reset_cpu - reset a ring buffer per CPU buffer * @buffer: The ring buffer to reset a per cpu buffer of * @cpu: The CPU buffer to be reset */ void ring_buffer_reset_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu]; unsigned long flags; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return; atomic_inc(&buffer->resize_disabled); atomic_inc(&cpu_buffer->record_disabled); /* Make sure all commits have finished */ synchronize_sched(); raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); if (RB_WARN_ON(cpu_buffer, local_read(&cpu_buffer->committing))) goto out; arch_spin_lock(&cpu_buffer->lock); rb_reset_cpu(cpu_buffer); arch_spin_unlock(&cpu_buffer->lock); out: raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); atomic_dec(&cpu_buffer->record_disabled); atomic_dec(&buffer->resize_disabled); } EXPORT_SYMBOL_GPL(ring_buffer_reset_cpu); /** * ring_buffer_reset - reset a ring buffer * @buffer: The ring buffer to reset all cpu buffers */ void ring_buffer_reset(struct ring_buffer *buffer) { int cpu; for_each_buffer_cpu(buffer, cpu) ring_buffer_reset_cpu(buffer, cpu); } EXPORT_SYMBOL_GPL(ring_buffer_reset); /** * rind_buffer_empty - is the ring buffer empty? * @buffer: The ring buffer to test */ bool ring_buffer_empty(struct ring_buffer *buffer) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long flags; bool dolock; int cpu; int ret; /* yes this is racy, but if you don't like the race, lock the buffer */ for_each_buffer_cpu(buffer, cpu) { cpu_buffer = buffer->buffers[cpu]; local_irq_save(flags); dolock = rb_reader_lock(cpu_buffer); ret = rb_per_cpu_empty(cpu_buffer); rb_reader_unlock(cpu_buffer, dolock); local_irq_restore(flags); if (!ret) return false; } return true; } EXPORT_SYMBOL_GPL(ring_buffer_empty); /** * ring_buffer_empty_cpu - is a cpu buffer of a ring buffer empty? * @buffer: The ring buffer * @cpu: The CPU buffer to test */ bool ring_buffer_empty_cpu(struct ring_buffer *buffer, int cpu) { struct ring_buffer_per_cpu *cpu_buffer; unsigned long flags; bool dolock; int ret; if (!cpumask_test_cpu(cpu, buffer->cpumask)) return true; cpu_buffer = buffer->buffers[cpu]; local_irq_save(flags); dolock = rb_reader_lock(cpu_buffer); ret = rb_per_cpu_empty(cpu_buffer); rb_reader_unlock(cpu_buffer, dolock); local_irq_restore(flags); return ret; } EXPORT_SYMBOL_GPL(ring_buffer_empty_cpu); #ifdef CONFIG_RING_BUFFER_ALLOW_SWAP /** * ring_buffer_swap_cpu - swap a CPU buffer between two ring buffers * @buffer_a: One buffer to swap with * @buffer_b: The other buffer to swap with * * This function is useful for tracers that want to take a "snapshot" * of a CPU buffer and has another back up buffer lying around. * it is expected that the tracer handles the cpu buffer not being * used at the moment. */ int ring_buffer_swap_cpu(struct ring_buffer *buffer_a, struct ring_buffer *buffer_b, int cpu) { struct ring_buffer_per_cpu *cpu_buffer_a; struct ring_buffer_per_cpu *cpu_buffer_b; int ret = -EINVAL; if (!cpumask_test_cpu(cpu, buffer_a->cpumask) || !cpumask_test_cpu(cpu, buffer_b->cpumask)) goto out; cpu_buffer_a = buffer_a->buffers[cpu]; cpu_buffer_b = buffer_b->buffers[cpu]; /* At least make sure the two buffers are somewhat the same */ if (cpu_buffer_a->nr_pages != cpu_buffer_b->nr_pages) goto out; ret = -EAGAIN; if (atomic_read(&buffer_a->record_disabled)) goto out; if (atomic_read(&buffer_b->record_disabled)) goto out; if (atomic_read(&cpu_buffer_a->record_disabled)) goto out; if (atomic_read(&cpu_buffer_b->record_disabled)) goto out; /* * We can't do a synchronize_sched here because this * function can be called in atomic context. * Normally this will be called from the same CPU as cpu. * If not it's up to the caller to protect this. */ atomic_inc(&cpu_buffer_a->record_disabled); atomic_inc(&cpu_buffer_b->record_disabled); ret = -EBUSY; if (local_read(&cpu_buffer_a->committing)) goto out_dec; if (local_read(&cpu_buffer_b->committing)) goto out_dec; buffer_a->buffers[cpu] = cpu_buffer_b; buffer_b->buffers[cpu] = cpu_buffer_a; cpu_buffer_b->buffer = buffer_a; cpu_buffer_a->buffer = buffer_b; ret = 0; out_dec: atomic_dec(&cpu_buffer_a->record_disabled); atomic_dec(&cpu_buffer_b->record_disabled); out: return ret; } EXPORT_SYMBOL_GPL(ring_buffer_swap_cpu); #endif /* CONFIG_RING_BUFFER_ALLOW_SWAP */ /** * ring_buffer_alloc_read_page - allocate a page to read from buffer * @buffer: the buffer to allocate for. * @cpu: the cpu buffer to allocate. * * This function is used in conjunction with ring_buffer_read_page. * When reading a full page from the ring buffer, these functions * can be used to speed up the process. The calling function should * allocate a few pages first with this function. Then when it * needs to get pages from the ring buffer, it passes the result * of this function into ring_buffer_read_page, which will swap * the page that was allocated, with the read page of the buffer. * * Returns: * The page allocated, or NULL on error. */ void *ring_buffer_alloc_read_page(struct ring_buffer *buffer, int cpu) { struct buffer_data_page *bpage; struct page *page; page = alloc_pages_node(cpu_to_node(cpu), GFP_KERNEL | __GFP_NORETRY, 0); if (!page) return NULL; bpage = page_address(page); rb_init_page(bpage); return bpage; } EXPORT_SYMBOL_GPL(ring_buffer_alloc_read_page); /** * ring_buffer_free_read_page - free an allocated read page * @buffer: the buffer the page was allocate for * @data: the page to free * * Free a page allocated from ring_buffer_alloc_read_page. */ void ring_buffer_free_read_page(struct ring_buffer *buffer, void *data) { free_page((unsigned long)data); } EXPORT_SYMBOL_GPL(ring_buffer_free_read_page); /** * ring_buffer_read_page - extract a page from the ring buffer * @buffer: buffer to extract from * @data_page: the page to use allocated from ring_buffer_alloc_read_page * @len: amount to extract * @cpu: the cpu of the buffer to extract * @full: should the extraction only happen when the page is full. * * This function will pull out a page from the ring buffer and consume it. * @data_page must be the address of the variable that was returned * from ring_buffer_alloc_read_page. This is because the page might be used * to swap with a page in the ring buffer. * * for example: * rpage = ring_buffer_alloc_read_page(buffer, cpu); * if (!rpage) * return error; * ret = ring_buffer_read_page(buffer, &rpage, len, cpu, 0); * if (ret >= 0) * process_page(rpage, ret); * * When @full is set, the function will not return true unless * the writer is off the reader page. * * Note: it is up to the calling functions to handle sleeps and wakeups. * The ring buffer can be used anywhere in the kernel and can not * blindly call wake_up. The layer that uses the ring buffer must be * responsible for that. * * Returns: * >=0 if data has been transferred, returns the offset of consumed data. * <0 if no data has been transferred. */ int ring_buffer_read_page(struct ring_buffer *buffer, void **data_page, size_t len, int cpu, int full) { struct ring_buffer_per_cpu *cpu_buffer = buffer->buffers[cpu]; struct ring_buffer_event *event; struct buffer_data_page *bpage; struct buffer_page *reader; unsigned long missed_events; unsigned long flags; unsigned int commit; unsigned int read; u64 save_timestamp; int ret = -1; if (!cpumask_test_cpu(cpu, buffer->cpumask)) goto out; /* * If len is not big enough to hold the page header, then * we can not copy anything. */ if (len <= BUF_PAGE_HDR_SIZE) goto out; len -= BUF_PAGE_HDR_SIZE; if (!data_page) goto out; bpage = *data_page; if (!bpage) goto out; raw_spin_lock_irqsave(&cpu_buffer->reader_lock, flags); reader = rb_get_reader_page(cpu_buffer); if (!reader) goto out_unlock; event = rb_reader_event(cpu_buffer); read = reader->read; commit = rb_page_commit(reader); /* Check if any events were dropped */ missed_events = cpu_buffer->lost_events; /* * If this page has been partially read or * if len is not big enough to read the rest of the page or * a writer is still on the page, then * we must copy the data from the page to the buffer. * Otherwise, we can simply swap the page with the one passed in. */ if (read || (len < (commit - read)) || cpu_buffer->reader_page == cpu_buffer->commit_page) { struct buffer_data_page *rpage = cpu_buffer->reader_page->page; unsigned int rpos = read; unsigned int pos = 0; unsigned int size; if (full) goto out_unlock; if (len > (commit - read)) len = (commit - read); /* Always keep the time extend and data together */ size = rb_event_ts_length(event); if (len < size) goto out_unlock; /* save the current timestamp, since the user will need it */ save_timestamp = cpu_buffer->read_stamp; /* Need to copy one event at a time */ do { /* We need the size of one event, because * rb_advance_reader only advances by one event, * whereas rb_event_ts_length may include the size of * one or two events. * We have already ensured there's enough space if this * is a time extend. */ size = rb_event_length(event); memcpy(bpage->data + pos, rpage->data + rpos, size); len -= size; rb_advance_reader(cpu_buffer); rpos = reader->read; pos += size; if (rpos >= commit) break; event = rb_reader_event(cpu_buffer); /* Always keep the time extend and data together */ size = rb_event_ts_length(event); } while (len >= size); /* update bpage */ local_set(&bpage->commit, pos); bpage->time_stamp = save_timestamp; /* we copied everything to the beginning */ read = 0; } else { /* update the entry counter */ cpu_buffer->read += rb_page_entries(reader); cpu_buffer->read_bytes += BUF_PAGE_SIZE; /* swap the pages */ rb_init_page(bpage); bpage = reader->page; reader->page = *data_page; local_set(&reader->write, 0); local_set(&reader->entries, 0); reader->read = 0; *data_page = bpage; /* * Use the real_end for the data size, * This gives us a chance to store the lost events * on the page. */ if (reader->real_end) local_set(&bpage->commit, reader->real_end); } ret = read; cpu_buffer->lost_events = 0; commit = local_read(&bpage->commit); /* * Set a flag in the commit field if we lost events */ if (missed_events) { /* If there is room at the end of the page to save the * missed events, then record it there. */ if (BUF_PAGE_SIZE - commit >= sizeof(missed_events)) { memcpy(&bpage->data[commit], &missed_events, sizeof(missed_events)); local_add(RB_MISSED_STORED, &bpage->commit); commit += sizeof(missed_events); } local_add(RB_MISSED_EVENTS, &bpage->commit); } /* * This page may be off to user land. Zero it out here. */ if (commit < BUF_PAGE_SIZE) memset(&bpage->data[commit], 0, BUF_PAGE_SIZE - commit); out_unlock: raw_spin_unlock_irqrestore(&cpu_buffer->reader_lock, flags); out: return ret; } EXPORT_SYMBOL_GPL(ring_buffer_read_page); #ifdef CONFIG_HOTPLUG_CPU static int rb_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu) { struct ring_buffer *buffer = container_of(self, struct ring_buffer, cpu_notify); long cpu = (long)hcpu; long nr_pages_same; int cpu_i; unsigned long nr_pages; switch (action) { case CPU_UP_PREPARE: case CPU_UP_PREPARE_FROZEN: if (cpumask_test_cpu(cpu, buffer->cpumask)) return NOTIFY_OK; nr_pages = 0; nr_pages_same = 1; /* check if all cpu sizes are same */ for_each_buffer_cpu(buffer, cpu_i) { /* fill in the size from first enabled cpu */ if (nr_pages == 0) nr_pages = buffer->buffers[cpu_i]->nr_pages; if (nr_pages != buffer->buffers[cpu_i]->nr_pages) { nr_pages_same = 0; break; } } /* allocate minimum pages, user can later expand it */ if (!nr_pages_same) nr_pages = 2; buffer->buffers[cpu] = rb_allocate_cpu_buffer(buffer, nr_pages, cpu); if (!buffer->buffers[cpu]) { WARN(1, "failed to allocate ring buffer on CPU %ld\n", cpu); return NOTIFY_OK; } smp_wmb(); cpumask_set_cpu(cpu, buffer->cpumask); break; case CPU_DOWN_PREPARE: case CPU_DOWN_PREPARE_FROZEN: /* * Do nothing. * If we were to free the buffer, then the user would * lose any trace that was in the buffer. */ break; default: break; } return NOTIFY_OK; } #endif #ifdef CONFIG_RING_BUFFER_STARTUP_TEST /* * This is a basic integrity check of the ring buffer. * Late in the boot cycle this test will run when configured in. * It will kick off a thread per CPU that will go into a loop * writing to the per cpu ring buffer various sizes of data. * Some of the data will be large items, some small. * * Another thread is created that goes into a spin, sending out * IPIs to the other CPUs to also write into the ring buffer. * this is to test the nesting ability of the buffer. * * Basic stats are recorded and reported. If something in the * ring buffer should happen that's not expected, a big warning * is displayed and all ring buffers are disabled. */ static struct task_struct *rb_threads[NR_CPUS] __initdata; struct rb_test_data { struct ring_buffer *buffer; unsigned long events; unsigned long bytes_written; unsigned long bytes_alloc; unsigned long bytes_dropped; unsigned long events_nested; unsigned long bytes_written_nested; unsigned long bytes_alloc_nested; unsigned long bytes_dropped_nested; int min_size_nested; int max_size_nested; int max_size; int min_size; int cpu; int cnt; }; static struct rb_test_data rb_data[NR_CPUS] __initdata; /* 1 meg per cpu */ #define RB_TEST_BUFFER_SIZE 1048576 static char rb_string[] __initdata = "abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*()?+\\" "?+|:';\",.<>/?abcdefghijklmnopqrstuvwxyz1234567890" "!@#$%^&*()?+\\?+|:';\",.<>/?abcdefghijklmnopqrstuv"; static bool rb_test_started __initdata; struct rb_item { int size; char str[]; }; static __init int rb_write_something(struct rb_test_data *data, bool nested) { struct ring_buffer_event *event; struct rb_item *item; bool started; int event_len; int size; int len; int cnt; /* Have nested writes different that what is written */ cnt = data->cnt + (nested ? 27 : 0); /* Multiply cnt by ~e, to make some unique increment */ size = (data->cnt * 68 / 25) % (sizeof(rb_string) - 1); len = size + sizeof(struct rb_item); started = rb_test_started; /* read rb_test_started before checking buffer enabled */ smp_rmb(); event = ring_buffer_lock_reserve(data->buffer, len); if (!event) { /* Ignore dropped events before test starts. */ if (started) { if (nested) data->bytes_dropped += len; else data->bytes_dropped_nested += len; } return len; } event_len = ring_buffer_event_length(event); if (RB_WARN_ON(data->buffer, event_len < len)) goto out; item = ring_buffer_event_data(event); item->size = size; memcpy(item->str, rb_string, size); if (nested) { data->bytes_alloc_nested += event_len; data->bytes_written_nested += len; data->events_nested++; if (!data->min_size_nested || len < data->min_size_nested) data->min_size_nested = len; if (len > data->max_size_nested) data->max_size_nested = len; } else { data->bytes_alloc += event_len; data->bytes_written += len; data->events++; if (!data->min_size || len < data->min_size) data->max_size = len; if (len > data->max_size) data->max_size = len; } out: ring_buffer_unlock_commit(data->buffer, event); return 0; } static __init int rb_test(void *arg) { struct rb_test_data *data = arg; while (!kthread_should_stop()) { rb_write_something(data, false); data->cnt++; set_current_state(TASK_INTERRUPTIBLE); /* Now sleep between a min of 100-300us and a max of 1ms */ usleep_range(((data->cnt % 3) + 1) * 100, 1000); } return 0; } static __init void rb_ipi(void *ignore) { struct rb_test_data *data; int cpu = smp_processor_id(); data = &rb_data[cpu]; rb_write_something(data, true); } static __init int rb_hammer_test(void *arg) { while (!kthread_should_stop()) { /* Send an IPI to all cpus to write data! */ smp_call_function(rb_ipi, NULL, 1); /* No sleep, but for non preempt, let others run */ schedule(); } return 0; } static __init int test_ringbuffer(void) { struct task_struct *rb_hammer; struct ring_buffer *buffer; int cpu; int ret = 0; pr_info("Running ring buffer tests...\n"); buffer = ring_buffer_alloc(RB_TEST_BUFFER_SIZE, RB_FL_OVERWRITE); if (WARN_ON(!buffer)) return 0; /* Disable buffer so that threads can't write to it yet */ ring_buffer_record_off(buffer); for_each_online_cpu(cpu) { rb_data[cpu].buffer = buffer; rb_data[cpu].cpu = cpu; rb_data[cpu].cnt = cpu; rb_threads[cpu] = kthread_create(rb_test, &rb_data[cpu], "rbtester/%d", cpu); if (WARN_ON(!rb_threads[cpu])) { pr_cont("FAILED\n"); ret = -1; goto out_free; } kthread_bind(rb_threads[cpu], cpu); wake_up_process(rb_threads[cpu]); } /* Now create the rb hammer! */ rb_hammer = kthread_run(rb_hammer_test, NULL, "rbhammer"); if (WARN_ON(!rb_hammer)) { pr_cont("FAILED\n"); ret = -1; goto out_free; } ring_buffer_record_on(buffer); /* * Show buffer is enabled before setting rb_test_started. * Yes there's a small race window where events could be * dropped and the thread wont catch it. But when a ring * buffer gets enabled, there will always be some kind of * delay before other CPUs see it. Thus, we don't care about * those dropped events. We care about events dropped after * the threads see that the buffer is active. */ smp_wmb(); rb_test_started = true; set_current_state(TASK_INTERRUPTIBLE); /* Just run for 10 seconds */; schedule_timeout(10 * HZ); kthread_stop(rb_hammer); out_free: for_each_online_cpu(cpu) { if (!rb_threads[cpu]) break; kthread_stop(rb_threads[cpu]); } if (ret) { ring_buffer_free(buffer); return ret; } /* Report! */ pr_info("finished\n"); for_each_online_cpu(cpu) { struct ring_buffer_event *event; struct rb_test_data *data = &rb_data[cpu]; struct rb_item *item; unsigned long total_events; unsigned long total_dropped; unsigned long total_written; unsigned long total_alloc; unsigned long total_read = 0; unsigned long total_size = 0; unsigned long total_len = 0; unsigned long total_lost = 0; unsigned long lost; int big_event_size; int small_event_size; ret = -1; total_events = data->events + data->events_nested; total_written = data->bytes_written + data->bytes_written_nested; total_alloc = data->bytes_alloc + data->bytes_alloc_nested; total_dropped = data->bytes_dropped + data->bytes_dropped_nested; big_event_size = data->max_size + data->max_size_nested; small_event_size = data->min_size + data->min_size_nested; pr_info("CPU %d:\n", cpu); pr_info(" events: %ld\n", total_events); pr_info(" dropped bytes: %ld\n", total_dropped); pr_info(" alloced bytes: %ld\n", total_alloc); pr_info(" written bytes: %ld\n", total_written); pr_info(" biggest event: %d\n", big_event_size); pr_info(" smallest event: %d\n", small_event_size); if (RB_WARN_ON(buffer, total_dropped)) break; ret = 0; while ((event = ring_buffer_consume(buffer, cpu, NULL, &lost))) { total_lost += lost; item = ring_buffer_event_data(event); total_len += ring_buffer_event_length(event); total_size += item->size + sizeof(struct rb_item); if (memcmp(&item->str[0], rb_string, item->size) != 0) { pr_info("FAILED!\n"); pr_info("buffer had: %.*s\n", item->size, item->str); pr_info("expected: %.*s\n", item->size, rb_string); RB_WARN_ON(buffer, 1); ret = -1; break; } total_read++; } if (ret) break; ret = -1; pr_info(" read events: %ld\n", total_read); pr_info(" lost events: %ld\n", total_lost); pr_info(" total events: %ld\n", total_lost + total_read); pr_info(" recorded len bytes: %ld\n", total_len); pr_info(" recorded size bytes: %ld\n", total_size); if (total_lost) pr_info(" With dropped events, record len and size may not match\n" " alloced and written from above\n"); if (!total_lost) { if (RB_WARN_ON(buffer, total_len != total_alloc || total_size != total_written)) break; } if (RB_WARN_ON(buffer, total_lost + total_read != total_events)) break; ret = 0; } if (!ret) pr_info("Ring buffer PASSED!\n"); ring_buffer_free(buffer); return 0; } late_initcall(test_ringbuffer); #endif /* CONFIG_RING_BUFFER_STARTUP_TEST */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5498_0
crossvul-cpp_data_good_5181_0
/*- * Copyright (c) 2003-2007 Tim Kientzle * Copyright (c) 2009 Andreas Henriksson <andreas@fatal.se> * Copyright (c) 2009-2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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. */ #include "archive_platform.h" __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_iso9660.c 201246 2009-12-30 05:30:35Z kientzle $"); #ifdef HAVE_ERRNO_H #include <errno.h> #endif /* #include <stdint.h> */ /* See archive_platform.h */ #include <stdio.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_STRING_H #include <string.h> #endif #include <time.h> #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #include "archive.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_read_private.h" #include "archive_string.h" /* * An overview of ISO 9660 format: * * Each disk is laid out as follows: * * 32k reserved for private use * * Volume descriptor table. Each volume descriptor * is 2k and specifies basic format information. * The "Primary Volume Descriptor" (PVD) is defined by the * standard and should always be present; other volume * descriptors include various vendor-specific extensions. * * Files and directories. Each file/dir is specified by * an "extent" (starting sector and length in bytes). * Dirs are just files with directory records packed one * after another. The PVD contains a single dir entry * specifying the location of the root directory. Everything * else follows from there. * * This module works by first reading the volume descriptors, then * building a list of directory entries, sorted by starting * sector. At each step, I look for the earliest dir entry that * hasn't yet been read, seek forward to that location and read * that entry. If it's a dir, I slurp in the new dir entries and * add them to the heap; if it's a regular file, I return the * corresponding archive_entry and wait for the client to request * the file body. This strategy allows us to read most compliant * CDs with a single pass through the data, as required by libarchive. */ #define LOGICAL_BLOCK_SIZE 2048 #define SYSTEM_AREA_BLOCK 16 /* Structure of on-disk primary volume descriptor. */ #define PVD_type_offset 0 #define PVD_type_size 1 #define PVD_id_offset (PVD_type_offset + PVD_type_size) #define PVD_id_size 5 #define PVD_version_offset (PVD_id_offset + PVD_id_size) #define PVD_version_size 1 #define PVD_reserved1_offset (PVD_version_offset + PVD_version_size) #define PVD_reserved1_size 1 #define PVD_system_id_offset (PVD_reserved1_offset + PVD_reserved1_size) #define PVD_system_id_size 32 #define PVD_volume_id_offset (PVD_system_id_offset + PVD_system_id_size) #define PVD_volume_id_size 32 #define PVD_reserved2_offset (PVD_volume_id_offset + PVD_volume_id_size) #define PVD_reserved2_size 8 #define PVD_volume_space_size_offset (PVD_reserved2_offset + PVD_reserved2_size) #define PVD_volume_space_size_size 8 #define PVD_reserved3_offset (PVD_volume_space_size_offset + PVD_volume_space_size_size) #define PVD_reserved3_size 32 #define PVD_volume_set_size_offset (PVD_reserved3_offset + PVD_reserved3_size) #define PVD_volume_set_size_size 4 #define PVD_volume_sequence_number_offset (PVD_volume_set_size_offset + PVD_volume_set_size_size) #define PVD_volume_sequence_number_size 4 #define PVD_logical_block_size_offset (PVD_volume_sequence_number_offset + PVD_volume_sequence_number_size) #define PVD_logical_block_size_size 4 #define PVD_path_table_size_offset (PVD_logical_block_size_offset + PVD_logical_block_size_size) #define PVD_path_table_size_size 8 #define PVD_type_1_path_table_offset (PVD_path_table_size_offset + PVD_path_table_size_size) #define PVD_type_1_path_table_size 4 #define PVD_opt_type_1_path_table_offset (PVD_type_1_path_table_offset + PVD_type_1_path_table_size) #define PVD_opt_type_1_path_table_size 4 #define PVD_type_m_path_table_offset (PVD_opt_type_1_path_table_offset + PVD_opt_type_1_path_table_size) #define PVD_type_m_path_table_size 4 #define PVD_opt_type_m_path_table_offset (PVD_type_m_path_table_offset + PVD_type_m_path_table_size) #define PVD_opt_type_m_path_table_size 4 #define PVD_root_directory_record_offset (PVD_opt_type_m_path_table_offset + PVD_opt_type_m_path_table_size) #define PVD_root_directory_record_size 34 #define PVD_volume_set_id_offset (PVD_root_directory_record_offset + PVD_root_directory_record_size) #define PVD_volume_set_id_size 128 #define PVD_publisher_id_offset (PVD_volume_set_id_offset + PVD_volume_set_id_size) #define PVD_publisher_id_size 128 #define PVD_preparer_id_offset (PVD_publisher_id_offset + PVD_publisher_id_size) #define PVD_preparer_id_size 128 #define PVD_application_id_offset (PVD_preparer_id_offset + PVD_preparer_id_size) #define PVD_application_id_size 128 #define PVD_copyright_file_id_offset (PVD_application_id_offset + PVD_application_id_size) #define PVD_copyright_file_id_size 37 #define PVD_abstract_file_id_offset (PVD_copyright_file_id_offset + PVD_copyright_file_id_size) #define PVD_abstract_file_id_size 37 #define PVD_bibliographic_file_id_offset (PVD_abstract_file_id_offset + PVD_abstract_file_id_size) #define PVD_bibliographic_file_id_size 37 #define PVD_creation_date_offset (PVD_bibliographic_file_id_offset + PVD_bibliographic_file_id_size) #define PVD_creation_date_size 17 #define PVD_modification_date_offset (PVD_creation_date_offset + PVD_creation_date_size) #define PVD_modification_date_size 17 #define PVD_expiration_date_offset (PVD_modification_date_offset + PVD_modification_date_size) #define PVD_expiration_date_size 17 #define PVD_effective_date_offset (PVD_expiration_date_offset + PVD_expiration_date_size) #define PVD_effective_date_size 17 #define PVD_file_structure_version_offset (PVD_effective_date_offset + PVD_effective_date_size) #define PVD_file_structure_version_size 1 #define PVD_reserved4_offset (PVD_file_structure_version_offset + PVD_file_structure_version_size) #define PVD_reserved4_size 1 #define PVD_application_data_offset (PVD_reserved4_offset + PVD_reserved4_size) #define PVD_application_data_size 512 #define PVD_reserved5_offset (PVD_application_data_offset + PVD_application_data_size) #define PVD_reserved5_size (2048 - PVD_reserved5_offset) /* TODO: It would make future maintenance easier to just hardcode the * above values. In particular, ECMA119 states the offsets as part of * the standard. That would eliminate the need for the following check.*/ #if PVD_reserved5_offset != 1395 #error PVD offset and size definitions are wrong. #endif /* Structure of optional on-disk supplementary volume descriptor. */ #define SVD_type_offset 0 #define SVD_type_size 1 #define SVD_id_offset (SVD_type_offset + SVD_type_size) #define SVD_id_size 5 #define SVD_version_offset (SVD_id_offset + SVD_id_size) #define SVD_version_size 1 /* ... */ #define SVD_reserved1_offset 72 #define SVD_reserved1_size 8 #define SVD_volume_space_size_offset 80 #define SVD_volume_space_size_size 8 #define SVD_escape_sequences_offset (SVD_volume_space_size_offset + SVD_volume_space_size_size) #define SVD_escape_sequences_size 32 /* ... */ #define SVD_logical_block_size_offset 128 #define SVD_logical_block_size_size 4 #define SVD_type_L_path_table_offset 140 #define SVD_type_M_path_table_offset 148 /* ... */ #define SVD_root_directory_record_offset 156 #define SVD_root_directory_record_size 34 #define SVD_file_structure_version_offset 881 #define SVD_reserved2_offset 882 #define SVD_reserved2_size 1 #define SVD_reserved3_offset 1395 #define SVD_reserved3_size 653 /* ... */ /* FIXME: validate correctness of last SVD entry offset. */ /* Structure of an on-disk directory record. */ /* Note: ISO9660 stores each multi-byte integer twice, once in * each byte order. The sizes here are the size of just one * of the two integers. (This is why the offset of a field isn't * the same as the offset+size of the previous field.) */ #define DR_length_offset 0 #define DR_length_size 1 #define DR_ext_attr_length_offset 1 #define DR_ext_attr_length_size 1 #define DR_extent_offset 2 #define DR_extent_size 4 #define DR_size_offset 10 #define DR_size_size 4 #define DR_date_offset 18 #define DR_date_size 7 #define DR_flags_offset 25 #define DR_flags_size 1 #define DR_file_unit_size_offset 26 #define DR_file_unit_size_size 1 #define DR_interleave_offset 27 #define DR_interleave_size 1 #define DR_volume_sequence_number_offset 28 #define DR_volume_sequence_number_size 2 #define DR_name_len_offset 32 #define DR_name_len_size 1 #define DR_name_offset 33 #ifdef HAVE_ZLIB_H static const unsigned char zisofs_magic[8] = { 0x37, 0xE4, 0x53, 0x96, 0xC9, 0xDB, 0xD6, 0x07 }; struct zisofs { /* Set 1 if this file compressed by paged zlib */ int pz; int pz_log2_bs; /* Log2 of block size */ uint64_t pz_uncompressed_size; int initialized; unsigned char *uncompressed_buffer; size_t uncompressed_buffer_size; uint32_t pz_offset; unsigned char header[16]; size_t header_avail; int header_passed; unsigned char *block_pointers; size_t block_pointers_alloc; size_t block_pointers_size; size_t block_pointers_avail; size_t block_off; uint32_t block_avail; z_stream stream; int stream_valid; }; #else struct zisofs { /* Set 1 if this file compressed by paged zlib */ int pz; }; #endif struct content { uint64_t offset;/* Offset on disk. */ uint64_t size; /* File size in bytes. */ struct content *next; }; /* In-memory storage for a directory record. */ struct file_info { struct file_info *use_next; struct file_info *parent; struct file_info *next; struct file_info *re_next; int subdirs; uint64_t key; /* Heap Key. */ uint64_t offset; /* Offset on disk. */ uint64_t size; /* File size in bytes. */ uint32_t ce_offset; /* Offset of CE. */ uint32_t ce_size; /* Size of CE. */ char rr_moved; /* Flag to rr_moved. */ char rr_moved_has_re_only; char re; /* Having RRIP "RE" extension. */ char re_descendant; uint64_t cl_offset; /* Having RRIP "CL" extension. */ int birthtime_is_set; time_t birthtime; /* File created time. */ time_t mtime; /* File last modified time. */ time_t atime; /* File last accessed time. */ time_t ctime; /* File attribute change time. */ uint64_t rdev; /* Device number. */ mode_t mode; uid_t uid; gid_t gid; int64_t number; int nlinks; struct archive_string name; /* Pathname */ unsigned char *utf16be_name; size_t utf16be_bytes; char name_continues; /* Non-zero if name continues */ struct archive_string symlink; char symlink_continues; /* Non-zero if link continues */ /* Set 1 if this file compressed by paged zlib(zisofs) */ int pz; int pz_log2_bs; /* Log2 of block size */ uint64_t pz_uncompressed_size; /* Set 1 if this file is multi extent. */ int multi_extent; struct { struct content *first; struct content **last; } contents; struct { struct file_info *first; struct file_info **last; } rede_files; }; struct heap_queue { struct file_info **files; int allocated; int used; }; struct iso9660 { int magic; #define ISO9660_MAGIC 0x96609660 int opt_support_joliet; int opt_support_rockridge; struct archive_string pathname; char seenRockridge; /* Set true if RR extensions are used. */ char seenSUSP; /* Set true if SUSP is beging used. */ char seenJoliet; unsigned char suspOffset; struct file_info *rr_moved; struct read_ce_queue { struct read_ce_req { uint64_t offset;/* Offset of CE on disk. */ struct file_info *file; } *reqs; int cnt; int allocated; } read_ce_req; int64_t previous_number; struct archive_string previous_pathname; struct file_info *use_files; struct heap_queue pending_files; struct { struct file_info *first; struct file_info **last; } cache_files; struct { struct file_info *first; struct file_info **last; } re_files; uint64_t current_position; ssize_t logical_block_size; uint64_t volume_size; /* Total size of volume in bytes. */ int32_t volume_block;/* Total size of volume in logical blocks. */ struct vd { int location; /* Location of Extent. */ uint32_t size; } primary, joliet; int64_t entry_sparse_offset; int64_t entry_bytes_remaining; size_t entry_bytes_unconsumed; struct zisofs entry_zisofs; struct content *entry_content; struct archive_string_conv *sconv_utf16be; /* * Buffers for a full pathname in UTF-16BE in Joliet extensions. */ #define UTF16_NAME_MAX 1024 unsigned char *utf16be_path; size_t utf16be_path_len; unsigned char *utf16be_previous_path; size_t utf16be_previous_path_len; /* Null buufer used in bidder to improve its performance. */ unsigned char null[2048]; }; static int archive_read_format_iso9660_bid(struct archive_read *, int); static int archive_read_format_iso9660_options(struct archive_read *, const char *, const char *); static int archive_read_format_iso9660_cleanup(struct archive_read *); static int archive_read_format_iso9660_read_data(struct archive_read *, const void **, size_t *, int64_t *); static int archive_read_format_iso9660_read_data_skip(struct archive_read *); static int archive_read_format_iso9660_read_header(struct archive_read *, struct archive_entry *); static const char *build_pathname(struct archive_string *, struct file_info *, int); static int build_pathname_utf16be(unsigned char *, size_t, size_t *, struct file_info *); #if DEBUG static void dump_isodirrec(FILE *, const unsigned char *isodirrec); #endif static time_t time_from_tm(struct tm *); static time_t isodate17(const unsigned char *); static time_t isodate7(const unsigned char *); static int isBootRecord(struct iso9660 *, const unsigned char *); static int isVolumePartition(struct iso9660 *, const unsigned char *); static int isVDSetTerminator(struct iso9660 *, const unsigned char *); static int isJolietSVD(struct iso9660 *, const unsigned char *); static int isSVD(struct iso9660 *, const unsigned char *); static int isEVD(struct iso9660 *, const unsigned char *); static int isPVD(struct iso9660 *, const unsigned char *); static int next_cache_entry(struct archive_read *, struct iso9660 *, struct file_info **); static int next_entry_seek(struct archive_read *, struct iso9660 *, struct file_info **); static struct file_info * parse_file_info(struct archive_read *a, struct file_info *parent, const unsigned char *isodirrec); static int parse_rockridge(struct archive_read *a, struct file_info *file, const unsigned char *start, const unsigned char *end); static int register_CE(struct archive_read *a, int32_t location, struct file_info *file); static int read_CE(struct archive_read *a, struct iso9660 *iso9660); static void parse_rockridge_NM1(struct file_info *, const unsigned char *, int); static void parse_rockridge_SL1(struct file_info *, const unsigned char *, int); static void parse_rockridge_TF1(struct file_info *, const unsigned char *, int); static void parse_rockridge_ZF1(struct file_info *, const unsigned char *, int); static void register_file(struct iso9660 *, struct file_info *); static void release_files(struct iso9660 *); static unsigned toi(const void *p, int n); static inline void re_add_entry(struct iso9660 *, struct file_info *); static inline struct file_info * re_get_entry(struct iso9660 *); static inline int rede_add_entry(struct file_info *); static inline struct file_info * rede_get_entry(struct file_info *); static inline void cache_add_entry(struct iso9660 *iso9660, struct file_info *file); static inline struct file_info *cache_get_entry(struct iso9660 *iso9660); static int heap_add_entry(struct archive_read *a, struct heap_queue *heap, struct file_info *file, uint64_t key); static struct file_info *heap_get_entry(struct heap_queue *heap); #define add_entry(arch, iso9660, file) \ heap_add_entry(arch, &((iso9660)->pending_files), file, file->offset) #define next_entry(iso9660) \ heap_get_entry(&((iso9660)->pending_files)) int archive_read_support_format_iso9660(struct archive *_a) { struct archive_read *a = (struct archive_read *)_a; struct iso9660 *iso9660; int r; archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW, "archive_read_support_format_iso9660"); iso9660 = (struct iso9660 *)calloc(1, sizeof(*iso9660)); if (iso9660 == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate iso9660 data"); return (ARCHIVE_FATAL); } iso9660->magic = ISO9660_MAGIC; iso9660->cache_files.first = NULL; iso9660->cache_files.last = &(iso9660->cache_files.first); iso9660->re_files.first = NULL; iso9660->re_files.last = &(iso9660->re_files.first); /* Enable to support Joliet extensions by default. */ iso9660->opt_support_joliet = 1; /* Enable to support Rock Ridge extensions by default. */ iso9660->opt_support_rockridge = 1; r = __archive_read_register_format(a, iso9660, "iso9660", archive_read_format_iso9660_bid, archive_read_format_iso9660_options, archive_read_format_iso9660_read_header, archive_read_format_iso9660_read_data, archive_read_format_iso9660_read_data_skip, NULL, archive_read_format_iso9660_cleanup, NULL, NULL); if (r != ARCHIVE_OK) { free(iso9660); return (r); } return (ARCHIVE_OK); } static int archive_read_format_iso9660_bid(struct archive_read *a, int best_bid) { struct iso9660 *iso9660; ssize_t bytes_read; const unsigned char *p; int seenTerminator; /* If there's already a better bid than we can ever make, don't bother testing. */ if (best_bid > 48) return (-1); iso9660 = (struct iso9660 *)(a->format->data); /* * Skip the first 32k (reserved area) and get the first * 8 sectors of the volume descriptor table. Of course, * if the I/O layer gives us more, we'll take it. */ #define RESERVED_AREA (SYSTEM_AREA_BLOCK * LOGICAL_BLOCK_SIZE) p = __archive_read_ahead(a, RESERVED_AREA + 8 * LOGICAL_BLOCK_SIZE, &bytes_read); if (p == NULL) return (-1); /* Skip the reserved area. */ bytes_read -= RESERVED_AREA; p += RESERVED_AREA; /* Check each volume descriptor. */ seenTerminator = 0; for (; bytes_read > LOGICAL_BLOCK_SIZE; bytes_read -= LOGICAL_BLOCK_SIZE, p += LOGICAL_BLOCK_SIZE) { /* Do not handle undefined Volume Descriptor Type. */ if (p[0] >= 4 && p[0] <= 254) return (0); /* Standard Identifier must be "CD001" */ if (memcmp(p + 1, "CD001", 5) != 0) return (0); if (isPVD(iso9660, p)) continue; if (!iso9660->joliet.location) { if (isJolietSVD(iso9660, p)) continue; } if (isBootRecord(iso9660, p)) continue; if (isEVD(iso9660, p)) continue; if (isSVD(iso9660, p)) continue; if (isVolumePartition(iso9660, p)) continue; if (isVDSetTerminator(iso9660, p)) { seenTerminator = 1; break; } return (0); } /* * ISO 9660 format must have Primary Volume Descriptor and * Volume Descriptor Set Terminator. */ if (seenTerminator && iso9660->primary.location > 16) return (48); /* We didn't find a valid PVD; return a bid of zero. */ return (0); } static int archive_read_format_iso9660_options(struct archive_read *a, const char *key, const char *val) { struct iso9660 *iso9660; iso9660 = (struct iso9660 *)(a->format->data); if (strcmp(key, "joliet") == 0) { if (val == NULL || strcmp(val, "off") == 0 || strcmp(val, "ignore") == 0 || strcmp(val, "disable") == 0 || strcmp(val, "0") == 0) iso9660->opt_support_joliet = 0; else iso9660->opt_support_joliet = 1; return (ARCHIVE_OK); } if (strcmp(key, "rockridge") == 0 || strcmp(key, "Rockridge") == 0) { iso9660->opt_support_rockridge = val != NULL; return (ARCHIVE_OK); } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); } static int isNull(struct iso9660 *iso9660, const unsigned char *h, unsigned offset, unsigned bytes) { while (bytes >= sizeof(iso9660->null)) { if (!memcmp(iso9660->null, h + offset, sizeof(iso9660->null))) return (0); offset += sizeof(iso9660->null); bytes -= sizeof(iso9660->null); } if (bytes) return memcmp(iso9660->null, h + offset, bytes) == 0; else return (1); } static int isBootRecord(struct iso9660 *iso9660, const unsigned char *h) { (void)iso9660; /* UNUSED */ /* Type of the Volume Descriptor Boot Record must be 0. */ if (h[0] != 0) return (0); /* Volume Descriptor Version must be 1. */ if (h[6] != 1) return (0); return (1); } static int isVolumePartition(struct iso9660 *iso9660, const unsigned char *h) { int32_t location; /* Type of the Volume Partition Descriptor must be 3. */ if (h[0] != 3) return (0); /* Volume Descriptor Version must be 1. */ if (h[6] != 1) return (0); /* Unused Field */ if (h[7] != 0) return (0); location = archive_le32dec(h + 72); if (location <= SYSTEM_AREA_BLOCK || location >= iso9660->volume_block) return (0); if ((uint32_t)location != archive_be32dec(h + 76)) return (0); return (1); } static int isVDSetTerminator(struct iso9660 *iso9660, const unsigned char *h) { (void)iso9660; /* UNUSED */ /* Type of the Volume Descriptor Set Terminator must be 255. */ if (h[0] != 255) return (0); /* Volume Descriptor Version must be 1. */ if (h[6] != 1) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, 7, 2048-7)) return (0); return (1); } static int isJolietSVD(struct iso9660 *iso9660, const unsigned char *h) { const unsigned char *p; ssize_t logical_block_size; int32_t volume_block; /* Check if current sector is a kind of Supplementary Volume * Descriptor. */ if (!isSVD(iso9660, h)) return (0); /* FIXME: do more validations according to joliet spec. */ /* check if this SVD contains joliet extension! */ p = h + SVD_escape_sequences_offset; /* N.B. Joliet spec says p[1] == '\\', but.... */ if (p[0] == '%' && p[1] == '/') { int level = 0; if (p[2] == '@') level = 1; else if (p[2] == 'C') level = 2; else if (p[2] == 'E') level = 3; else /* not joliet */ return (0); iso9660->seenJoliet = level; } else /* not joliet */ return (0); logical_block_size = archive_le16dec(h + SVD_logical_block_size_offset); volume_block = archive_le32dec(h + SVD_volume_space_size_offset); iso9660->logical_block_size = logical_block_size; iso9660->volume_block = volume_block; iso9660->volume_size = logical_block_size * (uint64_t)volume_block; /* Read Root Directory Record in Volume Descriptor. */ p = h + SVD_root_directory_record_offset; iso9660->joliet.location = archive_le32dec(p + DR_extent_offset); iso9660->joliet.size = archive_le32dec(p + DR_size_offset); return (48); } static int isSVD(struct iso9660 *iso9660, const unsigned char *h) { const unsigned char *p; ssize_t logical_block_size; int32_t volume_block; int32_t location; (void)iso9660; /* UNUSED */ /* Type 2 means it's a SVD. */ if (h[SVD_type_offset] != 2) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, SVD_reserved1_offset, SVD_reserved1_size)) return (0); if (!isNull(iso9660, h, SVD_reserved2_offset, SVD_reserved2_size)) return (0); if (!isNull(iso9660, h, SVD_reserved3_offset, SVD_reserved3_size)) return (0); /* File structure version must be 1 for ISO9660/ECMA119. */ if (h[SVD_file_structure_version_offset] != 1) return (0); logical_block_size = archive_le16dec(h + SVD_logical_block_size_offset); if (logical_block_size <= 0) return (0); volume_block = archive_le32dec(h + SVD_volume_space_size_offset); if (volume_block <= SYSTEM_AREA_BLOCK+4) return (0); /* Location of Occurrence of Type L Path Table must be * available location, * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_le32dec(h+SVD_type_L_path_table_offset); if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) return (0); /* The Type M Path Table must be at a valid location (WinISO * and probably other programs omit this, so we allow zero) * * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_be32dec(h+SVD_type_M_path_table_offset); if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) || location >= volume_block) return (0); /* Read Root Directory Record in Volume Descriptor. */ p = h + SVD_root_directory_record_offset; if (p[DR_length_offset] != 34) return (0); return (48); } static int isEVD(struct iso9660 *iso9660, const unsigned char *h) { const unsigned char *p; ssize_t logical_block_size; int32_t volume_block; int32_t location; (void)iso9660; /* UNUSED */ /* Type of the Enhanced Volume Descriptor must be 2. */ if (h[PVD_type_offset] != 2) return (0); /* EVD version must be 2. */ if (h[PVD_version_offset] != 2) return (0); /* Reserved field must be 0. */ if (h[PVD_reserved1_offset] != 0) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved2_offset, PVD_reserved2_size)) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved3_offset, PVD_reserved3_size)) return (0); /* Logical block size must be > 0. */ /* I've looked at Ecma 119 and can't find any stronger * restriction on this field. */ logical_block_size = archive_le16dec(h + PVD_logical_block_size_offset); if (logical_block_size <= 0) return (0); volume_block = archive_le32dec(h + PVD_volume_space_size_offset); if (volume_block <= SYSTEM_AREA_BLOCK+4) return (0); /* File structure version must be 2 for ISO9660:1999. */ if (h[PVD_file_structure_version_offset] != 2) return (0); /* Location of Occurrence of Type L Path Table must be * available location, * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_le32dec(h+PVD_type_1_path_table_offset); if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) return (0); /* Location of Occurrence of Type M Path Table must be * available location, * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_be32dec(h+PVD_type_m_path_table_offset); if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) || location >= volume_block) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved4_offset, PVD_reserved4_size)) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved5_offset, PVD_reserved5_size)) return (0); /* Read Root Directory Record in Volume Descriptor. */ p = h + PVD_root_directory_record_offset; if (p[DR_length_offset] != 34) return (0); return (48); } static int isPVD(struct iso9660 *iso9660, const unsigned char *h) { const unsigned char *p; ssize_t logical_block_size; int32_t volume_block; int32_t location; int i; /* Type of the Primary Volume Descriptor must be 1. */ if (h[PVD_type_offset] != 1) return (0); /* PVD version must be 1. */ if (h[PVD_version_offset] != 1) return (0); /* Reserved field must be 0. */ if (h[PVD_reserved1_offset] != 0) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved2_offset, PVD_reserved2_size)) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved3_offset, PVD_reserved3_size)) return (0); /* Logical block size must be > 0. */ /* I've looked at Ecma 119 and can't find any stronger * restriction on this field. */ logical_block_size = archive_le16dec(h + PVD_logical_block_size_offset); if (logical_block_size <= 0) return (0); volume_block = archive_le32dec(h + PVD_volume_space_size_offset); if (volume_block <= SYSTEM_AREA_BLOCK+4) return (0); /* File structure version must be 1 for ISO9660/ECMA119. */ if (h[PVD_file_structure_version_offset] != 1) return (0); /* Location of Occurrence of Type L Path Table must be * available location, * > SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_le32dec(h+PVD_type_1_path_table_offset); if (location < SYSTEM_AREA_BLOCK+2 || location >= volume_block) return (0); /* The Type M Path Table must also be at a valid location * (although ECMA 119 requires a Type M Path Table, WinISO and * probably other programs omit it, so we permit a zero here) * * >= SYSTEM_AREA_BLOCK(16) + 2 and < Volume Space Size. */ location = archive_be32dec(h+PVD_type_m_path_table_offset); if ((location > 0 && location < SYSTEM_AREA_BLOCK+2) || location >= volume_block) return (0); /* Reserved field must be 0. */ /* But accept NetBSD/FreeBSD "makefs" images with 0x20 here. */ for (i = 0; i < PVD_reserved4_size; ++i) if (h[PVD_reserved4_offset + i] != 0 && h[PVD_reserved4_offset + i] != 0x20) return (0); /* Reserved field must be 0. */ if (!isNull(iso9660, h, PVD_reserved5_offset, PVD_reserved5_size)) return (0); /* XXX TODO: Check other values for sanity; reject more * malformed PVDs. XXX */ /* Read Root Directory Record in Volume Descriptor. */ p = h + PVD_root_directory_record_offset; if (p[DR_length_offset] != 34) return (0); if (!iso9660->primary.location) { iso9660->logical_block_size = logical_block_size; iso9660->volume_block = volume_block; iso9660->volume_size = logical_block_size * (uint64_t)volume_block; iso9660->primary.location = archive_le32dec(p + DR_extent_offset); iso9660->primary.size = archive_le32dec(p + DR_size_offset); } return (48); } static int read_children(struct archive_read *a, struct file_info *parent) { struct iso9660 *iso9660; const unsigned char *b, *p; struct file_info *multi; size_t step, skip_size; iso9660 = (struct iso9660 *)(a->format->data); /* flush any remaining bytes from the last round to ensure * we're positioned */ if (iso9660->entry_bytes_unconsumed) { __archive_read_consume(a, iso9660->entry_bytes_unconsumed); iso9660->entry_bytes_unconsumed = 0; } if (iso9660->current_position > parent->offset) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Ignoring out-of-order directory (%s) %jd > %jd", parent->name.s, (intmax_t)iso9660->current_position, (intmax_t)parent->offset); return (ARCHIVE_WARN); } if (parent->offset + parent->size > iso9660->volume_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Directory is beyond end-of-media: %s", parent->name.s); return (ARCHIVE_WARN); } if (iso9660->current_position < parent->offset) { int64_t skipsize; skipsize = parent->offset - iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = parent->offset; } step = (size_t)(((parent->size + iso9660->logical_block_size -1) / iso9660->logical_block_size) * iso9660->logical_block_size); b = __archive_read_ahead(a, step, NULL); if (b == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } iso9660->current_position += step; multi = NULL; skip_size = step; while (step) { p = b; b += iso9660->logical_block_size; step -= iso9660->logical_block_size; for (; *p != 0 && p < b && p + *p <= b; p += *p) { struct file_info *child; /* N.B.: these special directory identifiers * are 8 bit "values" even on a * Joliet CD with UCS-2 (16bit) encoding. */ /* Skip '.' entry. */ if (*(p + DR_name_len_offset) == 1 && *(p + DR_name_offset) == '\0') continue; /* Skip '..' entry. */ if (*(p + DR_name_len_offset) == 1 && *(p + DR_name_offset) == '\001') continue; child = parse_file_info(a, parent, p); if (child == NULL) { __archive_read_consume(a, skip_size); return (ARCHIVE_FATAL); } if (child->cl_offset == 0 && (child->multi_extent || multi != NULL)) { struct content *con; if (multi == NULL) { multi = child; multi->contents.first = NULL; multi->contents.last = &(multi->contents.first); } con = malloc(sizeof(struct content)); if (con == NULL) { archive_set_error( &a->archive, ENOMEM, "No memory for multi extent"); __archive_read_consume(a, skip_size); return (ARCHIVE_FATAL); } con->offset = child->offset; con->size = child->size; con->next = NULL; *multi->contents.last = con; multi->contents.last = &(con->next); if (multi == child) { if (add_entry(a, iso9660, child) != ARCHIVE_OK) return (ARCHIVE_FATAL); } else { multi->size += child->size; if (!child->multi_extent) multi = NULL; } } else if (add_entry(a, iso9660, child) != ARCHIVE_OK) return (ARCHIVE_FATAL); } } __archive_read_consume(a, skip_size); /* Read data which recorded by RRIP "CE" extension. */ if (read_CE(a, iso9660) != ARCHIVE_OK) return (ARCHIVE_FATAL); return (ARCHIVE_OK); } static int choose_volume(struct archive_read *a, struct iso9660 *iso9660) { struct file_info *file; int64_t skipsize; struct vd *vd; const void *block; char seenJoliet; vd = &(iso9660->primary); if (!iso9660->opt_support_joliet) iso9660->seenJoliet = 0; if (iso9660->seenJoliet && vd->location > iso9660->joliet.location) /* This condition is unlikely; by way of caution. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position = skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } /* * While reading Root Directory, flag seenJoliet must be zero to * avoid converting special name 0x00(Current Directory) and * next byte to UCS2. */ seenJoliet = iso9660->seenJoliet;/* Save flag. */ iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; /* * If the iso image has both RockRidge and Joliet, we preferentially * use RockRidge Extensions rather than Joliet ones. */ if (vd == &(iso9660->primary) && iso9660->seenRockridge && iso9660->seenJoliet) iso9660->seenJoliet = 0; if (vd == &(iso9660->primary) && !iso9660->seenRockridge && iso9660->seenJoliet) { /* Switch reading data from primary to joliet. */ vd = &(iso9660->joliet); skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location; skipsize -= iso9660->current_position; skipsize = __archive_read_consume(a, skipsize); if (skipsize < 0) return ((int)skipsize); iso9660->current_position += skipsize; block = __archive_read_ahead(a, vd->size, NULL); if (block == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } iso9660->seenJoliet = 0; file = parse_file_info(a, NULL, block); if (file == NULL) return (ARCHIVE_FATAL); iso9660->seenJoliet = seenJoliet; } /* Store the root directory in the pending list. */ if (add_entry(a, iso9660, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->seenRockridge) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE; a->archive.archive_format_name = "ISO9660 with Rockridge extensions"; } return (ARCHIVE_OK); } static int archive_read_format_iso9660_read_header(struct archive_read *a, struct archive_entry *entry) { struct iso9660 *iso9660; struct file_info *file; int r, rd_r = ARCHIVE_OK; iso9660 = (struct iso9660 *)(a->format->data); if (!a->archive.archive_format) { a->archive.archive_format = ARCHIVE_FORMAT_ISO9660; a->archive.archive_format_name = "ISO9660"; } if (iso9660->current_position == 0) { r = choose_volume(a, iso9660); if (r != ARCHIVE_OK) return (r); } file = NULL;/* Eliminate a warning. */ /* Get the next entry that appears after the current offset. */ r = next_entry_seek(a, iso9660, &file); if (r != ARCHIVE_OK) return (r); if (iso9660->seenJoliet) { /* * Convert UTF-16BE of a filename to local locale MBS * and store the result into a filename field. */ if (iso9660->sconv_utf16be == NULL) { iso9660->sconv_utf16be = archive_string_conversion_from_charset( &(a->archive), "UTF-16BE", 1); if (iso9660->sconv_utf16be == NULL) /* Coundn't allocate memory */ return (ARCHIVE_FATAL); } if (iso9660->utf16be_path == NULL) { iso9660->utf16be_path = malloc(UTF16_NAME_MAX); if (iso9660->utf16be_path == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory"); return (ARCHIVE_FATAL); } } if (iso9660->utf16be_previous_path == NULL) { iso9660->utf16be_previous_path = malloc(UTF16_NAME_MAX); if (iso9660->utf16be_previous_path == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory"); return (ARCHIVE_FATAL); } } iso9660->utf16be_path_len = 0; if (build_pathname_utf16be(iso9660->utf16be_path, UTF16_NAME_MAX, &(iso9660->utf16be_path_len), file) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname is too long"); return (ARCHIVE_FATAL); } r = archive_entry_copy_pathname_l(entry, (const char *)iso9660->utf16be_path, iso9660->utf16be_path_len, iso9660->sconv_utf16be); if (r != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "No memory for Pathname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name( iso9660->sconv_utf16be)); rd_r = ARCHIVE_WARN; } } else { const char *path = build_pathname(&iso9660->pathname, file, 0); if (path == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Pathname is too long"); return (ARCHIVE_FATAL); } else { archive_string_empty(&iso9660->pathname); archive_entry_set_pathname(entry, path); } } iso9660->entry_bytes_remaining = file->size; /* Offset for sparse-file-aware clients. */ iso9660->entry_sparse_offset = 0; if (file->offset + file->size > iso9660->volume_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "File is beyond end-of-media: %s", archive_entry_pathname(entry)); iso9660->entry_bytes_remaining = 0; return (ARCHIVE_WARN); } /* Set up the entry structure with information about this entry. */ archive_entry_set_mode(entry, file->mode); archive_entry_set_uid(entry, file->uid); archive_entry_set_gid(entry, file->gid); archive_entry_set_nlink(entry, file->nlinks); if (file->birthtime_is_set) archive_entry_set_birthtime(entry, file->birthtime, 0); else archive_entry_unset_birthtime(entry); archive_entry_set_mtime(entry, file->mtime, 0); archive_entry_set_ctime(entry, file->ctime, 0); archive_entry_set_atime(entry, file->atime, 0); /* N.B.: Rock Ridge supports 64-bit device numbers. */ archive_entry_set_rdev(entry, (dev_t)file->rdev); archive_entry_set_size(entry, iso9660->entry_bytes_remaining); if (file->symlink.s != NULL) archive_entry_copy_symlink(entry, file->symlink.s); /* Note: If the input isn't seekable, we can't rewind to * return the same body again, so if the next entry refers to * the same data, we have to return it as a hardlink to the * original entry. */ if (file->number != -1 && file->number == iso9660->previous_number) { if (iso9660->seenJoliet) { r = archive_entry_copy_hardlink_l(entry, (const char *)iso9660->utf16be_previous_path, iso9660->utf16be_previous_path_len, iso9660->sconv_utf16be); if (r != 0) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "No memory for Linkname"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Linkname cannot be converted " "from %s to current locale.", archive_string_conversion_charset_name( iso9660->sconv_utf16be)); rd_r = ARCHIVE_WARN; } } else archive_entry_set_hardlink(entry, iso9660->previous_pathname.s); archive_entry_unset_size(entry); iso9660->entry_bytes_remaining = 0; return (rd_r); } if ((file->mode & AE_IFMT) != AE_IFDIR && file->offset < iso9660->current_position) { int64_t r64; r64 = __archive_read_seek(a, file->offset, SEEK_SET); if (r64 != (int64_t)file->offset) { /* We can't seek backwards to extract it, so issue * a warning. Note that this can only happen if * this entry was added to the heap after we passed * this offset, that is, only if the directory * mentioning this entry is later than the body of * the entry. Such layouts are very unusual; most * ISO9660 writers lay out and record all directory * information first, then store all file bodies. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Ignoring out-of-order file @%jx (%s) %jd < %jd", (intmax_t)file->number, iso9660->pathname.s, (intmax_t)file->offset, (intmax_t)iso9660->current_position); iso9660->entry_bytes_remaining = 0; return (ARCHIVE_WARN); } iso9660->current_position = (uint64_t)r64; } /* Initialize zisofs variables. */ iso9660->entry_zisofs.pz = file->pz; if (file->pz) { #ifdef HAVE_ZLIB_H struct zisofs *zisofs; zisofs = &iso9660->entry_zisofs; zisofs->initialized = 0; zisofs->pz_log2_bs = file->pz_log2_bs; zisofs->pz_uncompressed_size = file->pz_uncompressed_size; zisofs->pz_offset = 0; zisofs->header_avail = 0; zisofs->header_passed = 0; zisofs->block_pointers_avail = 0; #endif archive_entry_set_size(entry, file->pz_uncompressed_size); } iso9660->previous_number = file->number; if (iso9660->seenJoliet) { memcpy(iso9660->utf16be_previous_path, iso9660->utf16be_path, iso9660->utf16be_path_len); iso9660->utf16be_previous_path_len = iso9660->utf16be_path_len; } else archive_strcpy( &iso9660->previous_pathname, iso9660->pathname.s); /* Reset entry_bytes_remaining if the file is multi extent. */ iso9660->entry_content = file->contents.first; if (iso9660->entry_content != NULL) iso9660->entry_bytes_remaining = iso9660->entry_content->size; if (archive_entry_filetype(entry) == AE_IFDIR) { /* Overwrite nlinks by proper link number which is * calculated from number of sub directories. */ archive_entry_set_nlink(entry, 2 + file->subdirs); /* Directory data has been read completely. */ iso9660->entry_bytes_remaining = 0; } if (rd_r != ARCHIVE_OK) return (rd_r); return (ARCHIVE_OK); } static int archive_read_format_iso9660_read_data_skip(struct archive_read *a) { /* Because read_next_header always does an explicit skip * to the next entry, we don't need to do anything here. */ (void)a; /* UNUSED */ return (ARCHIVE_OK); } #ifdef HAVE_ZLIB_H static int zisofs_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { struct iso9660 *iso9660; struct zisofs *zisofs; const unsigned char *p; size_t avail; ssize_t bytes_read; size_t uncompressed_size; int r; iso9660 = (struct iso9660 *)(a->format->data); zisofs = &iso9660->entry_zisofs; p = __archive_read_ahead(a, 1, &bytes_read); if (bytes_read <= 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Truncated zisofs file body"); return (ARCHIVE_FATAL); } if (bytes_read > iso9660->entry_bytes_remaining) bytes_read = (ssize_t)iso9660->entry_bytes_remaining; avail = bytes_read; uncompressed_size = 0; if (!zisofs->initialized) { size_t ceil, xsize; /* Allocate block pointers buffer. */ ceil = (size_t)((zisofs->pz_uncompressed_size + (((int64_t)1) << zisofs->pz_log2_bs) - 1) >> zisofs->pz_log2_bs); xsize = (ceil + 1) * 4; if (zisofs->block_pointers_alloc < xsize) { size_t alloc; if (zisofs->block_pointers != NULL) free(zisofs->block_pointers); alloc = ((xsize >> 10) + 1) << 10; zisofs->block_pointers = malloc(alloc); if (zisofs->block_pointers == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for zisofs decompression"); return (ARCHIVE_FATAL); } zisofs->block_pointers_alloc = alloc; } zisofs->block_pointers_size = xsize; /* Allocate uncompressed data buffer. */ xsize = (size_t)1UL << zisofs->pz_log2_bs; if (zisofs->uncompressed_buffer_size < xsize) { if (zisofs->uncompressed_buffer != NULL) free(zisofs->uncompressed_buffer); zisofs->uncompressed_buffer = malloc(xsize); if (zisofs->uncompressed_buffer == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for zisofs decompression"); return (ARCHIVE_FATAL); } } zisofs->uncompressed_buffer_size = xsize; /* * Read the file header, and check the magic code of zisofs. */ if (zisofs->header_avail < sizeof(zisofs->header)) { xsize = sizeof(zisofs->header) - zisofs->header_avail; if (avail < xsize) xsize = avail; memcpy(zisofs->header + zisofs->header_avail, p, xsize); zisofs->header_avail += xsize; avail -= xsize; p += xsize; } if (!zisofs->header_passed && zisofs->header_avail == sizeof(zisofs->header)) { int err = 0; if (memcmp(zisofs->header, zisofs_magic, sizeof(zisofs_magic)) != 0) err = 1; if (archive_le32dec(zisofs->header + 8) != zisofs->pz_uncompressed_size) err = 1; if (zisofs->header[12] != 4) err = 1; if (zisofs->header[13] != zisofs->pz_log2_bs) err = 1; if (err) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs file body"); return (ARCHIVE_FATAL); } zisofs->header_passed = 1; } /* * Read block pointers. */ if (zisofs->header_passed && zisofs->block_pointers_avail < zisofs->block_pointers_size) { xsize = zisofs->block_pointers_size - zisofs->block_pointers_avail; if (avail < xsize) xsize = avail; memcpy(zisofs->block_pointers + zisofs->block_pointers_avail, p, xsize); zisofs->block_pointers_avail += xsize; avail -= xsize; p += xsize; if (zisofs->block_pointers_avail == zisofs->block_pointers_size) { /* We've got all block pointers and initialize * related variables. */ zisofs->block_off = 0; zisofs->block_avail = 0; /* Complete a initialization */ zisofs->initialized = 1; } } if (!zisofs->initialized) goto next_data; /* We need more data. */ } /* * Get block offsets from block pointers. */ if (zisofs->block_avail == 0) { uint32_t bst, bed; if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { /* There isn't a pair of offsets. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers"); return (ARCHIVE_FATAL); } bst = archive_le32dec( zisofs->block_pointers + zisofs->block_off); if (bst != zisofs->pz_offset + (bytes_read - avail)) { /* TODO: Should we seek offset of current file * by bst ? */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers(cannot seek)"); return (ARCHIVE_FATAL); } bed = archive_le32dec( zisofs->block_pointers + zisofs->block_off + 4); if (bed < bst) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers"); return (ARCHIVE_FATAL); } zisofs->block_avail = bed - bst; zisofs->block_off += 4; /* Initialize compression library for new block. */ if (zisofs->stream_valid) r = inflateReset(&zisofs->stream); else r = inflateInit(&zisofs->stream); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Can't initialize zisofs decompression."); return (ARCHIVE_FATAL); } zisofs->stream_valid = 1; zisofs->stream.total_in = 0; zisofs->stream.total_out = 0; } /* * Make uncompressed data. */ if (zisofs->block_avail == 0) { memset(zisofs->uncompressed_buffer, 0, zisofs->uncompressed_buffer_size); uncompressed_size = zisofs->uncompressed_buffer_size; } else { zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; if (avail > zisofs->block_avail) zisofs->stream.avail_in = zisofs->block_avail; else zisofs->stream.avail_in = (uInt)avail; zisofs->stream.next_out = zisofs->uncompressed_buffer; zisofs->stream.avail_out = (uInt)zisofs->uncompressed_buffer_size; r = inflate(&zisofs->stream, 0); switch (r) { case Z_OK: /* Decompressor made some progress.*/ case Z_STREAM_END: /* Found end of stream. */ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "zisofs decompression failed (%d)", r); return (ARCHIVE_FATAL); } uncompressed_size = zisofs->uncompressed_buffer_size - zisofs->stream.avail_out; avail -= zisofs->stream.next_in - p; zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); } next_data: bytes_read -= avail; *buff = zisofs->uncompressed_buffer; *size = uncompressed_size; *offset = iso9660->entry_sparse_offset; iso9660->entry_sparse_offset += uncompressed_size; iso9660->entry_bytes_remaining -= bytes_read; iso9660->current_position += bytes_read; zisofs->pz_offset += (uint32_t)bytes_read; iso9660->entry_bytes_unconsumed += bytes_read; return (ARCHIVE_OK); } #else /* HAVE_ZLIB_H */ static int zisofs_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { (void)buff;/* UNUSED */ (void)size;/* UNUSED */ (void)offset;/* UNUSED */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "zisofs is not supported on this platform."); return (ARCHIVE_FAILED); } #endif /* HAVE_ZLIB_H */ static int archive_read_format_iso9660_read_data(struct archive_read *a, const void **buff, size_t *size, int64_t *offset) { ssize_t bytes_read; struct iso9660 *iso9660; iso9660 = (struct iso9660 *)(a->format->data); if (iso9660->entry_bytes_unconsumed) { __archive_read_consume(a, iso9660->entry_bytes_unconsumed); iso9660->entry_bytes_unconsumed = 0; } if (iso9660->entry_bytes_remaining <= 0) { if (iso9660->entry_content != NULL) iso9660->entry_content = iso9660->entry_content->next; if (iso9660->entry_content == NULL) { *buff = NULL; *size = 0; *offset = iso9660->entry_sparse_offset; return (ARCHIVE_EOF); } /* Seek forward to the start of the entry. */ if (iso9660->current_position < iso9660->entry_content->offset) { int64_t step; step = iso9660->entry_content->offset - iso9660->current_position; step = __archive_read_consume(a, step); if (step < 0) return ((int)step); iso9660->current_position = iso9660->entry_content->offset; } if (iso9660->entry_content->offset < iso9660->current_position) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Ignoring out-of-order file (%s) %jd < %jd", iso9660->pathname.s, (intmax_t)iso9660->entry_content->offset, (intmax_t)iso9660->current_position); *buff = NULL; *size = 0; *offset = iso9660->entry_sparse_offset; return (ARCHIVE_WARN); } iso9660->entry_bytes_remaining = iso9660->entry_content->size; } if (iso9660->entry_zisofs.pz) return (zisofs_read_data(a, buff, size, offset)); *buff = __archive_read_ahead(a, 1, &bytes_read); if (bytes_read == 0) archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Truncated input file"); if (*buff == NULL) return (ARCHIVE_FATAL); if (bytes_read > iso9660->entry_bytes_remaining) bytes_read = (ssize_t)iso9660->entry_bytes_remaining; *size = bytes_read; *offset = iso9660->entry_sparse_offset; iso9660->entry_sparse_offset += bytes_read; iso9660->entry_bytes_remaining -= bytes_read; iso9660->entry_bytes_unconsumed = bytes_read; iso9660->current_position += bytes_read; return (ARCHIVE_OK); } static int archive_read_format_iso9660_cleanup(struct archive_read *a) { struct iso9660 *iso9660; int r = ARCHIVE_OK; iso9660 = (struct iso9660 *)(a->format->data); release_files(iso9660); free(iso9660->read_ce_req.reqs); archive_string_free(&iso9660->pathname); archive_string_free(&iso9660->previous_pathname); if (iso9660->pending_files.files) free(iso9660->pending_files.files); #ifdef HAVE_ZLIB_H free(iso9660->entry_zisofs.uncompressed_buffer); free(iso9660->entry_zisofs.block_pointers); if (iso9660->entry_zisofs.stream_valid) { if (inflateEnd(&iso9660->entry_zisofs.stream) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up zlib decompressor"); r = ARCHIVE_FATAL; } } #endif free(iso9660->utf16be_path); free(iso9660->utf16be_previous_path); free(iso9660); (a->format->data) = NULL; return (r); } /* * This routine parses a single ISO directory record, makes sense * of any extensions, and stores the result in memory. */ static struct file_info * parse_file_info(struct archive_read *a, struct file_info *parent, const unsigned char *isodirrec) { struct iso9660 *iso9660; struct file_info *file, *filep; size_t name_len; const unsigned char *rr_start, *rr_end; const unsigned char *p; size_t dr_len; uint64_t fsize, offset; int32_t location; int flags; iso9660 = (struct iso9660 *)(a->format->data); dr_len = (size_t)isodirrec[DR_length_offset]; name_len = (size_t)isodirrec[DR_name_len_offset]; location = archive_le32dec(isodirrec + DR_extent_offset); fsize = toi(isodirrec + DR_size_offset, DR_size_size); /* Sanity check that dr_len needs at least 34. */ if (dr_len < 34) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid length of directory record"); return (NULL); } /* Sanity check that name_len doesn't exceed dr_len. */ if (dr_len - 33 < name_len || name_len == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid length of file identifier"); return (NULL); } /* Sanity check that location doesn't exceed volume block. * Don't check lower limit of location; it's possibility * the location has negative value when file type is symbolic * link or file size is zero. As far as I know latest mkisofs * do that. */ if (location > 0 && (location + ((fsize + iso9660->logical_block_size -1) / iso9660->logical_block_size)) > (uint32_t)iso9660->volume_block) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid location of extent of file"); return (NULL); } /* Sanity check that location doesn't have a negative value * when the file is not empty. it's too large. */ if (fsize != 0 && location < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid location of extent of file"); return (NULL); } /* Sanity check that this entry does not create a cycle. */ offset = iso9660->logical_block_size * (uint64_t)location; for (filep = parent; filep != NULL; filep = filep->parent) { if (filep->offset == offset) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Directory structure contains loop"); return (NULL); } } /* Create a new file entry and copy data from the ISO dir record. */ file = (struct file_info *)calloc(1, sizeof(*file)); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for file entry"); return (NULL); } file->parent = parent; file->offset = offset; file->size = fsize; file->mtime = isodate7(isodirrec + DR_date_offset); file->ctime = file->atime = file->mtime; file->rede_files.first = NULL; file->rede_files.last = &(file->rede_files.first); p = isodirrec + DR_name_offset; /* Rockridge extensions (if any) follow name. Compute this * before fidgeting the name_len below. */ rr_start = p + name_len + (name_len & 1 ? 0 : 1); rr_end = isodirrec + dr_len; if (iso9660->seenJoliet) { /* Joliet names are max 64 chars (128 bytes) according to spec, * but genisoimage/mkisofs allows recording longer Joliet * names which are 103 UCS2 characters(206 bytes) by their * option '-joliet-long'. */ if (name_len > 206) name_len = 206; name_len &= ~1; /* trim trailing first version and dot from filename. * * Remember we were in UTF-16BE land! * SEPARATOR 1 (.) and SEPARATOR 2 (;) are both * 16 bits big endian characters on Joliet. * * TODO: sanitize filename? * Joliet allows any UCS-2 char except: * *, /, :, ;, ? and \. */ /* Chop off trailing ';1' from files. */ if (name_len > 4 && p[name_len-4] == 0 && p[name_len-3] == ';' && p[name_len-2] == 0 && p[name_len-1] == '1') name_len -= 4; #if 0 /* XXX: this somehow manages to strip of single-character file extensions, like '.c'. */ /* Chop off trailing '.' from filenames. */ if (name_len > 2 && p[name_len-2] == 0 && p[name_len-1] == '.') name_len -= 2; #endif if ((file->utf16be_name = malloc(name_len)) == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for file name"); return (NULL); } memcpy(file->utf16be_name, p, name_len); file->utf16be_bytes = name_len; } else { /* Chop off trailing ';1' from files. */ if (name_len > 2 && p[name_len - 2] == ';' && p[name_len - 1] == '1') name_len -= 2; /* Chop off trailing '.' from filenames. */ if (name_len > 1 && p[name_len - 1] == '.') --name_len; archive_strncpy(&file->name, (const char *)p, name_len); } flags = isodirrec[DR_flags_offset]; if (flags & 0x02) file->mode = AE_IFDIR | 0700; else file->mode = AE_IFREG | 0400; if (flags & 0x80) file->multi_extent = 1; else file->multi_extent = 0; /* * Use a location for the file number, which is treated as an inode * number to find out hardlink target. If Rockridge extensions is * being used, the file number will be overwritten by FILE SERIAL * NUMBER of RRIP "PX" extension. * Note: Old mkisofs did not record that FILE SERIAL NUMBER * in ISO images. * Note2: xorriso set 0 to the location of a symlink file. */ if (file->size == 0 && location >= 0) { /* If file->size is zero, its location points wrong place, * and so we should not use it for the file number. * When the location has negative value, it can be used * for the file number. */ file->number = -1; /* Do not appear before any directory entries. */ file->offset = -1; } else file->number = (int64_t)(uint32_t)location; /* Rockridge extensions overwrite information from above. */ if (iso9660->opt_support_rockridge) { if (parent == NULL && rr_end - rr_start >= 7) { p = rr_start; if (memcmp(p, "SP\x07\x01\xbe\xef", 6) == 0) { /* * SP extension stores the suspOffset * (Number of bytes to skip between * filename and SUSP records.) * It is mandatory by the SUSP standard * (IEEE 1281). * * It allows SUSP to coexist with * non-SUSP uses of the System * Use Area by placing non-SUSP data * before SUSP data. * * SP extension must be in the root * directory entry, disable all SUSP * processing if not found. */ iso9660->suspOffset = p[6]; iso9660->seenSUSP = 1; rr_start += 7; } } if (iso9660->seenSUSP) { int r; file->name_continues = 0; file->symlink_continues = 0; rr_start += iso9660->suspOffset; r = parse_rockridge(a, file, rr_start, rr_end); if (r != ARCHIVE_OK) { free(file); return (NULL); } /* * A file size of symbolic link files in ISO images * made by makefs is not zero and its location is * the same as those of next regular file. That is * the same as hard like file and it causes unexpected * error. */ if (file->size > 0 && (file->mode & AE_IFMT) == AE_IFLNK) { file->size = 0; file->number = -1; file->offset = -1; } } else /* If there isn't SUSP, disable parsing * rock ridge extensions. */ iso9660->opt_support_rockridge = 0; } file->nlinks = 1;/* Reset nlink. we'll calculate it later. */ /* Tell file's parent how many children that parent has. */ if (parent != NULL && (flags & 0x02)) parent->subdirs++; if (iso9660->seenRockridge) { if (parent != NULL && parent->parent == NULL && (flags & 0x02) && iso9660->rr_moved == NULL && file->name.s && (strcmp(file->name.s, "rr_moved") == 0 || strcmp(file->name.s, ".rr_moved") == 0)) { iso9660->rr_moved = file; file->rr_moved = 1; file->rr_moved_has_re_only = 1; file->re = 0; parent->subdirs--; } else if (file->re) { /* * Sanity check: file's parent is rr_moved. */ if (parent == NULL || parent->rr_moved == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge RE"); return (NULL); } /* * Sanity check: file does not have "CL" extension. */ if (file->cl_offset) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge RE and CL"); return (NULL); } /* * Sanity check: The file type must be a directory. */ if ((flags & 0x02) == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge RE"); return (NULL); } } else if (parent != NULL && parent->rr_moved) file->rr_moved_has_re_only = 0; else if (parent != NULL && (flags & 0x02) && (parent->re || parent->re_descendant)) file->re_descendant = 1; if (file->cl_offset) { struct file_info *r; if (parent == NULL || parent->parent == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge CL"); return (NULL); } /* * Sanity check: The file type must be a regular file. */ if ((flags & 0x02) != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge CL"); return (NULL); } parent->subdirs++; /* Overwrite an offset and a number of this "CL" entry * to appear before other dirs. "+1" to those is to * make sure to appear after "RE" entry which this * "CL" entry should be connected with. */ file->offset = file->number = file->cl_offset + 1; /* * Sanity check: cl_offset does not point at its * the parents or itself. */ for (r = parent; r; r = r->parent) { if (r->offset == file->cl_offset) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge CL"); return (NULL); } } if (file->cl_offset == file->offset || parent->rr_moved) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid Rockridge CL"); return (NULL); } } } #if DEBUG /* DEBUGGING: Warn about attributes I don't yet fully support. */ if ((flags & ~0x02) != 0) { fprintf(stderr, "\n ** Unrecognized flag: "); dump_isodirrec(stderr, isodirrec); fprintf(stderr, "\n"); } else if (toi(isodirrec + DR_volume_sequence_number_offset, 2) != 1) { fprintf(stderr, "\n ** Unrecognized sequence number: "); dump_isodirrec(stderr, isodirrec); fprintf(stderr, "\n"); } else if (*(isodirrec + DR_file_unit_size_offset) != 0) { fprintf(stderr, "\n ** Unexpected file unit size: "); dump_isodirrec(stderr, isodirrec); fprintf(stderr, "\n"); } else if (*(isodirrec + DR_interleave_offset) != 0) { fprintf(stderr, "\n ** Unexpected interleave: "); dump_isodirrec(stderr, isodirrec); fprintf(stderr, "\n"); } else if (*(isodirrec + DR_ext_attr_length_offset) != 0) { fprintf(stderr, "\n ** Unexpected extended attribute length: "); dump_isodirrec(stderr, isodirrec); fprintf(stderr, "\n"); } #endif register_file(iso9660, file); return (file); } static int parse_rockridge(struct archive_read *a, struct file_info *file, const unsigned char *p, const unsigned char *end) { struct iso9660 *iso9660; iso9660 = (struct iso9660 *)(a->format->data); while (p + 4 <= end /* Enough space for another entry. */ && p[0] >= 'A' && p[0] <= 'Z' /* Sanity-check 1st char of name. */ && p[1] >= 'A' && p[1] <= 'Z' /* Sanity-check 2nd char of name. */ && p[2] >= 4 /* Sanity-check length. */ && p + p[2] <= end) { /* Sanity-check length. */ const unsigned char *data = p + 4; int data_length = p[2] - 4; int version = p[3]; switch(p[0]) { case 'C': if (p[1] == 'E') { if (version == 1 && data_length == 24) { /* * CE extension comprises: * 8 byte sector containing extension * 8 byte offset w/in above sector * 8 byte length of continuation */ int32_t location = archive_le32dec(data); file->ce_offset = archive_le32dec(data+8); file->ce_size = archive_le32dec(data+16); if (register_CE(a, location, file) != ARCHIVE_OK) return (ARCHIVE_FATAL); } } else if (p[1] == 'L') { if (version == 1 && data_length == 8) { file->cl_offset = (uint64_t) iso9660->logical_block_size * (uint64_t)archive_le32dec(data); iso9660->seenRockridge = 1; } } break; case 'N': if (p[1] == 'M') { if (version == 1) { parse_rockridge_NM1(file, data, data_length); iso9660->seenRockridge = 1; } } break; case 'P': /* * PD extension is padding; * contents are always ignored. * * PL extension won't appear; * contents are always ignored. */ if (p[1] == 'N') { if (version == 1 && data_length == 16) { file->rdev = toi(data,4); file->rdev <<= 32; file->rdev |= toi(data + 8, 4); iso9660->seenRockridge = 1; } } else if (p[1] == 'X') { /* * PX extension comprises: * 8 bytes for mode, * 8 bytes for nlinks, * 8 bytes for uid, * 8 bytes for gid, * 8 bytes for inode. */ if (version == 1) { if (data_length >= 8) file->mode = toi(data, 4); if (data_length >= 16) file->nlinks = toi(data + 8, 4); if (data_length >= 24) file->uid = toi(data + 16, 4); if (data_length >= 32) file->gid = toi(data + 24, 4); if (data_length >= 40) file->number = toi(data + 32, 4); iso9660->seenRockridge = 1; } } break; case 'R': if (p[1] == 'E' && version == 1) { file->re = 1; iso9660->seenRockridge = 1; } else if (p[1] == 'R' && version == 1) { /* * RR extension comprises: * one byte flag value * This extension is obsolete, * so contents are always ignored. */ } break; case 'S': if (p[1] == 'L') { if (version == 1) { parse_rockridge_SL1(file, data, data_length); iso9660->seenRockridge = 1; } } else if (p[1] == 'T' && data_length == 0 && version == 1) { /* * ST extension marks end of this * block of SUSP entries. * * It allows SUSP to coexist with * non-SUSP uses of the System * Use Area by placing non-SUSP data * after SUSP data. */ iso9660->seenSUSP = 0; iso9660->seenRockridge = 0; return (ARCHIVE_OK); } break; case 'T': if (p[1] == 'F') { if (version == 1) { parse_rockridge_TF1(file, data, data_length); iso9660->seenRockridge = 1; } } break; case 'Z': if (p[1] == 'F') { if (version == 1) parse_rockridge_ZF1(file, data, data_length); } break; default: break; } p += p[2]; } return (ARCHIVE_OK); } static int register_CE(struct archive_read *a, int32_t location, struct file_info *file) { struct iso9660 *iso9660; struct read_ce_queue *heap; struct read_ce_req *p; uint64_t offset, parent_offset; int hole, parent; iso9660 = (struct iso9660 *)(a->format->data); offset = ((uint64_t)location) * (uint64_t)iso9660->logical_block_size; if (((file->mode & AE_IFMT) == AE_IFREG && offset >= file->offset) || offset < iso9660->current_position || (((uint64_t)file->ce_offset) + file->ce_size) > (uint64_t)iso9660->logical_block_size || offset + file->ce_offset + file->ce_size > iso9660->volume_size) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid parameter in SUSP \"CE\" extension"); return (ARCHIVE_FATAL); } /* Expand our CE list as necessary. */ heap = &(iso9660->read_ce_req); if (heap->cnt >= heap->allocated) { int new_size; if (heap->allocated < 16) new_size = 16; else new_size = heap->allocated * 2; /* Overflow might keep us from growing the list. */ if (new_size <= heap->allocated) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } p = calloc(new_size, sizeof(p[0])); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } if (heap->reqs != NULL) { memcpy(p, heap->reqs, heap->cnt * sizeof(*p)); free(heap->reqs); } heap->reqs = p; heap->allocated = new_size; } /* * Start with hole at end, walk it up tree to find insertion point. */ hole = heap->cnt++; while (hole > 0) { parent = (hole - 1)/2; parent_offset = heap->reqs[parent].offset; if (offset >= parent_offset) { heap->reqs[hole].offset = offset; heap->reqs[hole].file = file; return (ARCHIVE_OK); } /* Move parent into hole <==> move hole up tree. */ heap->reqs[hole] = heap->reqs[parent]; hole = parent; } heap->reqs[0].offset = offset; heap->reqs[0].file = file; return (ARCHIVE_OK); } static void next_CE(struct read_ce_queue *heap) { uint64_t a_offset, b_offset, c_offset; int a, b, c; struct read_ce_req tmp; if (heap->cnt < 1) return; /* * Move the last item in the heap to the root of the tree */ heap->reqs[0] = heap->reqs[--(heap->cnt)]; /* * Rebalance the heap. */ a = 0; /* Starting element and its offset */ a_offset = heap->reqs[a].offset; for (;;) { b = a + a + 1; /* First child */ if (b >= heap->cnt) return; b_offset = heap->reqs[b].offset; c = b + 1; /* Use second child if it is smaller. */ if (c < heap->cnt) { c_offset = heap->reqs[c].offset; if (c_offset < b_offset) { b = c; b_offset = c_offset; } } if (a_offset <= b_offset) return; tmp = heap->reqs[a]; heap->reqs[a] = heap->reqs[b]; heap->reqs[b] = tmp; a = b; } } static int read_CE(struct archive_read *a, struct iso9660 *iso9660) { struct read_ce_queue *heap; const unsigned char *b, *p, *end; struct file_info *file; size_t step; int r; /* Read data which RRIP "CE" extension points. */ heap = &(iso9660->read_ce_req); step = iso9660->logical_block_size; while (heap->cnt && heap->reqs[0].offset == iso9660->current_position) { b = __archive_read_ahead(a, step, NULL); if (b == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to read full block when scanning " "ISO9660 directory list"); return (ARCHIVE_FATAL); } do { file = heap->reqs[0].file; if (file->ce_offset + file->ce_size > step) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Malformed CE information"); return (ARCHIVE_FATAL); } p = b + file->ce_offset; end = p + file->ce_size; next_CE(heap); r = parse_rockridge(a, file, p, end); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } while (heap->cnt && heap->reqs[0].offset == iso9660->current_position); /* NOTE: Do not move this consume's code to fron of * do-while loop. Registration of nested CE extension * might cause error because of current position. */ __archive_read_consume(a, step); iso9660->current_position += step; } return (ARCHIVE_OK); } static void parse_rockridge_NM1(struct file_info *file, const unsigned char *data, int data_length) { if (!file->name_continues) archive_string_empty(&file->name); file->name_continues = 0; if (data_length < 1) return; /* * NM version 1 extension comprises: * 1 byte flag, value is one of: * = 0: remainder is name * = 1: remainder is name, next NM entry continues name * = 2: "." * = 4: ".." * = 32: Implementation specific * All other values are reserved. */ switch(data[0]) { case 0: if (data_length < 2) return; archive_strncat(&file->name, (const char *)data + 1, data_length - 1); break; case 1: if (data_length < 2) return; archive_strncat(&file->name, (const char *)data + 1, data_length - 1); file->name_continues = 1; break; case 2: archive_strcat(&file->name, "."); break; case 4: archive_strcat(&file->name, ".."); break; default: return; } } static void parse_rockridge_TF1(struct file_info *file, const unsigned char *data, int data_length) { char flag; /* * TF extension comprises: * one byte flag * create time (optional) * modify time (optional) * access time (optional) * attribute time (optional) * Time format and presence of fields * is controlled by flag bits. */ if (data_length < 1) return; flag = data[0]; ++data; --data_length; if (flag & 0x80) { /* Use 17-byte time format. */ if ((flag & 1) && data_length >= 17) { /* Create time. */ file->birthtime_is_set = 1; file->birthtime = isodate17(data); data += 17; data_length -= 17; } if ((flag & 2) && data_length >= 17) { /* Modify time. */ file->mtime = isodate17(data); data += 17; data_length -= 17; } if ((flag & 4) && data_length >= 17) { /* Access time. */ file->atime = isodate17(data); data += 17; data_length -= 17; } if ((flag & 8) && data_length >= 17) { /* Attribute change time. */ file->ctime = isodate17(data); } } else { /* Use 7-byte time format. */ if ((flag & 1) && data_length >= 7) { /* Create time. */ file->birthtime_is_set = 1; file->birthtime = isodate7(data); data += 7; data_length -= 7; } if ((flag & 2) && data_length >= 7) { /* Modify time. */ file->mtime = isodate7(data); data += 7; data_length -= 7; } if ((flag & 4) && data_length >= 7) { /* Access time. */ file->atime = isodate7(data); data += 7; data_length -= 7; } if ((flag & 8) && data_length >= 7) { /* Attribute change time. */ file->ctime = isodate7(data); } } } static void parse_rockridge_SL1(struct file_info *file, const unsigned char *data, int data_length) { const char *separator = ""; if (!file->symlink_continues || file->symlink.length < 1) archive_string_empty(&file->symlink); file->symlink_continues = 0; /* * Defined flag values: * 0: This is the last SL record for this symbolic link * 1: this symbolic link field continues in next SL entry * All other values are reserved. */ if (data_length < 1) return; switch(*data) { case 0: break; case 1: file->symlink_continues = 1; break; default: return; } ++data; /* Skip flag byte. */ --data_length; /* * SL extension body stores "components". * Basically, this is a complicated way of storing * a POSIX path. It also interferes with using * symlinks for storing non-path data. <sigh> * * Each component is 2 bytes (flag and length) * possibly followed by name data. */ while (data_length >= 2) { unsigned char flag = *data++; unsigned char nlen = *data++; data_length -= 2; archive_strcat(&file->symlink, separator); separator = "/"; switch(flag) { case 0: /* Usual case, this is text. */ if (data_length < nlen) return; archive_strncat(&file->symlink, (const char *)data, nlen); break; case 0x01: /* Text continues in next component. */ if (data_length < nlen) return; archive_strncat(&file->symlink, (const char *)data, nlen); separator = ""; break; case 0x02: /* Current dir. */ archive_strcat(&file->symlink, "."); break; case 0x04: /* Parent dir. */ archive_strcat(&file->symlink, ".."); break; case 0x08: /* Root of filesystem. */ archive_strcat(&file->symlink, "/"); separator = ""; break; case 0x10: /* Undefined (historically "volume root" */ archive_string_empty(&file->symlink); archive_strcat(&file->symlink, "ROOT"); break; case 0x20: /* Undefined (historically "hostname") */ archive_strcat(&file->symlink, "hostname"); break; default: /* TODO: issue a warning ? */ return; } data += nlen; data_length -= nlen; } } static void parse_rockridge_ZF1(struct file_info *file, const unsigned char *data, int data_length) { if (data[0] == 0x70 && data[1] == 0x7a && data_length == 12) { /* paged zlib */ file->pz = 1; file->pz_log2_bs = data[3]; file->pz_uncompressed_size = archive_le32dec(&data[4]); } } static void register_file(struct iso9660 *iso9660, struct file_info *file) { file->use_next = iso9660->use_files; iso9660->use_files = file; } static void release_files(struct iso9660 *iso9660) { struct content *con, *connext; struct file_info *file; file = iso9660->use_files; while (file != NULL) { struct file_info *next = file->use_next; archive_string_free(&file->name); archive_string_free(&file->symlink); free(file->utf16be_name); con = file->contents.first; while (con != NULL) { connext = con->next; free(con); con = connext; } free(file); file = next; } } static int next_entry_seek(struct archive_read *a, struct iso9660 *iso9660, struct file_info **pfile) { struct file_info *file; int r; r = next_cache_entry(a, iso9660, pfile); if (r != ARCHIVE_OK) return (r); file = *pfile; /* Don't waste time seeking for zero-length bodies. */ if (file->size == 0) file->offset = iso9660->current_position; /* flush any remaining bytes from the last round to ensure * we're positioned */ if (iso9660->entry_bytes_unconsumed) { __archive_read_consume(a, iso9660->entry_bytes_unconsumed); iso9660->entry_bytes_unconsumed = 0; } /* Seek forward to the start of the entry. */ if (iso9660->current_position < file->offset) { int64_t step; step = file->offset - iso9660->current_position; step = __archive_read_consume(a, step); if (step < 0) return ((int)step); iso9660->current_position = file->offset; } /* We found body of file; handle it now. */ return (ARCHIVE_OK); } static int next_cache_entry(struct archive_read *a, struct iso9660 *iso9660, struct file_info **pfile) { struct file_info *file; struct { struct file_info *first; struct file_info **last; } empty_files; int64_t number; int count; file = cache_get_entry(iso9660); if (file != NULL) { *pfile = file; return (ARCHIVE_OK); } for (;;) { struct file_info *re, *d; *pfile = file = next_entry(iso9660); if (file == NULL) { /* * If directory entries all which are descendant of * rr_moved are stil remaning, expose their. */ if (iso9660->re_files.first != NULL && iso9660->rr_moved != NULL && iso9660->rr_moved->rr_moved_has_re_only) /* Expose "rr_moved" entry. */ cache_add_entry(iso9660, iso9660->rr_moved); while ((re = re_get_entry(iso9660)) != NULL) { /* Expose its descendant dirs. */ while ((d = rede_get_entry(re)) != NULL) cache_add_entry(iso9660, d); } if (iso9660->cache_files.first != NULL) return (next_cache_entry(a, iso9660, pfile)); return (ARCHIVE_EOF); } if (file->cl_offset) { struct file_info *first_re = NULL; int nexted_re = 0; /* * Find "RE" dir for the current file, which * has "CL" flag. */ while ((re = re_get_entry(iso9660)) != first_re) { if (first_re == NULL) first_re = re; if (re->offset == file->cl_offset) { re->parent->subdirs--; re->parent = file->parent; re->re = 0; if (re->parent->re_descendant) { nexted_re = 1; re->re_descendant = 1; if (rede_add_entry(re) < 0) goto fatal_rr; /* Move a list of descendants * to a new ancestor. */ while ((d = rede_get_entry( re)) != NULL) if (rede_add_entry(d) < 0) goto fatal_rr; break; } /* Replace the current file * with "RE" dir */ *pfile = file = re; /* Expose its descendant */ while ((d = rede_get_entry( file)) != NULL) cache_add_entry( iso9660, d); break; } else re_add_entry(iso9660, re); } if (nexted_re) { /* * Do not expose this at this time * because we have not gotten its full-path * name yet. */ continue; } } else if ((file->mode & AE_IFMT) == AE_IFDIR) { int r; /* Read file entries in this dir. */ r = read_children(a, file); if (r != ARCHIVE_OK) return (r); /* * Handle a special dir of Rockridge extensions, * "rr_moved". */ if (file->rr_moved) { /* * If this has only the subdirectories which * have "RE" flags, do not expose at this time. */ if (file->rr_moved_has_re_only) continue; /* Otherwise expose "rr_moved" entry. */ } else if (file->re) { /* * Do not expose this at this time * because we have not gotten its full-path * name yet. */ re_add_entry(iso9660, file); continue; } else if (file->re_descendant) { /* * If the top level "RE" entry of this entry * is not exposed, we, accordingly, should not * expose this entry at this time because * we cannot make its proper full-path name. */ if (rede_add_entry(file) == 0) continue; /* Otherwise we can expose this entry because * it seems its top level "RE" has already been * exposed. */ } } break; } if ((file->mode & AE_IFMT) != AE_IFREG || file->number == -1) return (ARCHIVE_OK); count = 0; number = file->number; iso9660->cache_files.first = NULL; iso9660->cache_files.last = &(iso9660->cache_files.first); empty_files.first = NULL; empty_files.last = &empty_files.first; /* Collect files which has the same file serial number. * Peek pending_files so that file which number is different * is not put bak. */ while (iso9660->pending_files.used > 0 && (iso9660->pending_files.files[0]->number == -1 || iso9660->pending_files.files[0]->number == number)) { if (file->number == -1) { /* This file has the same offset * but it's wrong offset which empty files * and symlink files have. * NOTE: This wrong offse was recorded by * old mkisofs utility. If ISO images is * created by latest mkisofs, this does not * happen. */ file->next = NULL; *empty_files.last = file; empty_files.last = &(file->next); } else { count++; cache_add_entry(iso9660, file); } file = next_entry(iso9660); } if (count == 0) { *pfile = file; return ((file == NULL)?ARCHIVE_EOF:ARCHIVE_OK); } if (file->number == -1) { file->next = NULL; *empty_files.last = file; empty_files.last = &(file->next); } else { count++; cache_add_entry(iso9660, file); } if (count > 1) { /* The count is the same as number of hardlink, * so much so that each nlinks of files in cache_file * is overwritten by value of the count. */ for (file = iso9660->cache_files.first; file != NULL; file = file->next) file->nlinks = count; } /* If there are empty files, that files are added * to the tail of the cache_files. */ if (empty_files.first != NULL) { *iso9660->cache_files.last = empty_files.first; iso9660->cache_files.last = empty_files.last; } *pfile = cache_get_entry(iso9660); return ((*pfile == NULL)?ARCHIVE_EOF:ARCHIVE_OK); fatal_rr: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to connect 'CL' pointer to 'RE' rr_moved pointer of " "Rockridge extensions: current position = %jd, CL offset = %jd", (intmax_t)iso9660->current_position, (intmax_t)file->cl_offset); return (ARCHIVE_FATAL); } static inline void re_add_entry(struct iso9660 *iso9660, struct file_info *file) { file->re_next = NULL; *iso9660->re_files.last = file; iso9660->re_files.last = &(file->re_next); } static inline struct file_info * re_get_entry(struct iso9660 *iso9660) { struct file_info *file; if ((file = iso9660->re_files.first) != NULL) { iso9660->re_files.first = file->re_next; if (iso9660->re_files.first == NULL) iso9660->re_files.last = &(iso9660->re_files.first); } return (file); } static inline int rede_add_entry(struct file_info *file) { struct file_info *re; /* * Find "RE" entry. */ re = file->parent; while (re != NULL && !re->re) re = re->parent; if (re == NULL) return (-1); file->re_next = NULL; *re->rede_files.last = file; re->rede_files.last = &(file->re_next); return (0); } static inline struct file_info * rede_get_entry(struct file_info *re) { struct file_info *file; if ((file = re->rede_files.first) != NULL) { re->rede_files.first = file->re_next; if (re->rede_files.first == NULL) re->rede_files.last = &(re->rede_files.first); } return (file); } static inline void cache_add_entry(struct iso9660 *iso9660, struct file_info *file) { file->next = NULL; *iso9660->cache_files.last = file; iso9660->cache_files.last = &(file->next); } static inline struct file_info * cache_get_entry(struct iso9660 *iso9660) { struct file_info *file; if ((file = iso9660->cache_files.first) != NULL) { iso9660->cache_files.first = file->next; if (iso9660->cache_files.first == NULL) iso9660->cache_files.last = &(iso9660->cache_files.first); } return (file); } static int heap_add_entry(struct archive_read *a, struct heap_queue *heap, struct file_info *file, uint64_t key) { uint64_t file_key, parent_key; int hole, parent; /* Expand our pending files list as necessary. */ if (heap->used >= heap->allocated) { struct file_info **new_pending_files; int new_size = heap->allocated * 2; if (heap->allocated < 1024) new_size = 1024; /* Overflow might keep us from growing the list. */ if (new_size <= heap->allocated) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } new_pending_files = (struct file_info **) malloc(new_size * sizeof(new_pending_files[0])); if (new_pending_files == NULL) { archive_set_error(&a->archive, ENOMEM, "Out of memory"); return (ARCHIVE_FATAL); } memcpy(new_pending_files, heap->files, heap->allocated * sizeof(new_pending_files[0])); if (heap->files != NULL) free(heap->files); heap->files = new_pending_files; heap->allocated = new_size; } file_key = file->key = key; /* * Start with hole at end, walk it up tree to find insertion point. */ hole = heap->used++; while (hole > 0) { parent = (hole - 1)/2; parent_key = heap->files[parent]->key; if (file_key >= parent_key) { heap->files[hole] = file; return (ARCHIVE_OK); } /* Move parent into hole <==> move hole up tree. */ heap->files[hole] = heap->files[parent]; hole = parent; } heap->files[0] = file; return (ARCHIVE_OK); } static struct file_info * heap_get_entry(struct heap_queue *heap) { uint64_t a_key, b_key, c_key; int a, b, c; struct file_info *r, *tmp; if (heap->used < 1) return (NULL); /* * The first file in the list is the earliest; we'll return this. */ r = heap->files[0]; /* * Move the last item in the heap to the root of the tree */ heap->files[0] = heap->files[--(heap->used)]; /* * Rebalance the heap. */ a = 0; /* Starting element and its heap key */ a_key = heap->files[a]->key; for (;;) { b = a + a + 1; /* First child */ if (b >= heap->used) return (r); b_key = heap->files[b]->key; c = b + 1; /* Use second child if it is smaller. */ if (c < heap->used) { c_key = heap->files[c]->key; if (c_key < b_key) { b = c; b_key = c_key; } } if (a_key <= b_key) return (r); tmp = heap->files[a]; heap->files[a] = heap->files[b]; heap->files[b] = tmp; a = b; } } static unsigned int toi(const void *p, int n) { const unsigned char *v = (const unsigned char *)p; if (n > 1) return v[0] + 256 * toi(v + 1, n - 1); if (n == 1) return v[0]; return (0); } static time_t isodate7(const unsigned char *v) { struct tm tm; int offset; time_t t; memset(&tm, 0, sizeof(tm)); tm.tm_year = v[0]; tm.tm_mon = v[1] - 1; tm.tm_mday = v[2]; tm.tm_hour = v[3]; tm.tm_min = v[4]; tm.tm_sec = v[5]; /* v[6] is the signed timezone offset, in 1/4-hour increments. */ offset = ((const signed char *)v)[6]; if (offset > -48 && offset < 52) { tm.tm_hour -= offset / 4; tm.tm_min -= (offset % 4) * 15; } t = time_from_tm(&tm); if (t == (time_t)-1) return ((time_t)0); return (t); } static time_t isodate17(const unsigned char *v) { struct tm tm; int offset; time_t t; memset(&tm, 0, sizeof(tm)); tm.tm_year = (v[0] - '0') * 1000 + (v[1] - '0') * 100 + (v[2] - '0') * 10 + (v[3] - '0') - 1900; tm.tm_mon = (v[4] - '0') * 10 + (v[5] - '0'); tm.tm_mday = (v[6] - '0') * 10 + (v[7] - '0'); tm.tm_hour = (v[8] - '0') * 10 + (v[9] - '0'); tm.tm_min = (v[10] - '0') * 10 + (v[11] - '0'); tm.tm_sec = (v[12] - '0') * 10 + (v[13] - '0'); /* v[16] is the signed timezone offset, in 1/4-hour increments. */ offset = ((const signed char *)v)[16]; if (offset > -48 && offset < 52) { tm.tm_hour -= offset / 4; tm.tm_min -= (offset % 4) * 15; } t = time_from_tm(&tm); if (t == (time_t)-1) return ((time_t)0); return (t); } static time_t time_from_tm(struct tm *t) { #if HAVE_TIMEGM /* Use platform timegm() if available. */ return (timegm(t)); #elif HAVE__MKGMTIME64 return (_mkgmtime64(t)); #else /* Else use direct calculation using POSIX assumptions. */ /* First, fix up tm_yday based on the year/month/day. */ if (mktime(t) == (time_t)-1) return ((time_t)-1); /* Then we can compute timegm() from first principles. */ return (t->tm_sec + t->tm_min * 60 + t->tm_hour * 3600 + t->tm_yday * 86400 + (t->tm_year - 70) * 31536000 + ((t->tm_year - 69) / 4) * 86400 - ((t->tm_year - 1) / 100) * 86400 + ((t->tm_year + 299) / 400) * 86400); #endif } static const char * build_pathname(struct archive_string *as, struct file_info *file, int depth) { // Plain ISO9660 only allows 8 dir levels; if we get // to 1000, then something is very, very wrong. if (depth > 1000) { return NULL; } if (file->parent != NULL && archive_strlen(&file->parent->name) > 0) { if (build_pathname(as, file->parent, depth + 1) == NULL) { return NULL; } archive_strcat(as, "/"); } if (archive_strlen(&file->name) == 0) archive_strcat(as, "."); else archive_string_concat(as, &file->name); return (as->s); } static int build_pathname_utf16be(unsigned char *p, size_t max, size_t *len, struct file_info *file) { if (file->parent != NULL && file->parent->utf16be_bytes > 0) { if (build_pathname_utf16be(p, max, len, file->parent) != 0) return (-1); p[*len] = 0; p[*len + 1] = '/'; *len += 2; } if (file->utf16be_bytes == 0) { if (*len + 2 > max) return (-1);/* Path is too long! */ p[*len] = 0; p[*len + 1] = '.'; *len += 2; } else { if (*len + file->utf16be_bytes > max) return (-1);/* Path is too long! */ memcpy(p + *len, file->utf16be_name, file->utf16be_bytes); *len += file->utf16be_bytes; } return (0); } #if DEBUG static void dump_isodirrec(FILE *out, const unsigned char *isodirrec) { fprintf(out, " l %d,", toi(isodirrec + DR_length_offset, DR_length_size)); fprintf(out, " a %d,", toi(isodirrec + DR_ext_attr_length_offset, DR_ext_attr_length_size)); fprintf(out, " ext 0x%x,", toi(isodirrec + DR_extent_offset, DR_extent_size)); fprintf(out, " s %d,", toi(isodirrec + DR_size_offset, DR_extent_size)); fprintf(out, " f 0x%x,", toi(isodirrec + DR_flags_offset, DR_flags_size)); fprintf(out, " u %d,", toi(isodirrec + DR_file_unit_size_offset, DR_file_unit_size_size)); fprintf(out, " ilv %d,", toi(isodirrec + DR_interleave_offset, DR_interleave_size)); fprintf(out, " seq %d,", toi(isodirrec + DR_volume_sequence_number_offset, DR_volume_sequence_number_size)); fprintf(out, " nl %d:", toi(isodirrec + DR_name_len_offset, DR_name_len_size)); fprintf(out, " `%.*s'", toi(isodirrec + DR_name_len_offset, DR_name_len_size), isodirrec + DR_name_offset); } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_5181_0
crossvul-cpp_data_good_540_1
/* * The copyright in this software is being made available under the 2-clauses * BSD License, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such rights * are granted under this license. * * Copyright (c) 2002-2014, Universite catholique de Louvain (UCL), Belgium * Copyright (c) 2002-2014, Professor Benoit Macq * Copyright (c) 2001-2003, David Janssens * Copyright (c) 2002-2003, Yannick Verschueren * Copyright (c) 2003-2007, Francois-Olivier Devaux * Copyright (c) 2003-2014, Antonin Descampe * Copyright (c) 2005, Herve Drolon, FreeImage Team * Copyright (c) 2006-2007, Parvatha Elangovan * Copyright (c) 2008, 2011-2012, Centre National d'Etudes Spatiales (CNES), FR * Copyright (c) 2012, CS Systemes d'Information, France * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * 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. */ #include "opj_includes.h" /* ----------------------------------------------------------------------- */ /* TODO MSD: */ #ifdef TODO_MSD void tcd_dump(FILE *fd, opj_tcd_t *tcd, opj_tcd_image_t * img) { int tileno, compno, resno, bandno, precno;/*, cblkno;*/ fprintf(fd, "image {\n"); fprintf(fd, " tw=%d, th=%d x0=%d x1=%d y0=%d y1=%d\n", img->tw, img->th, tcd->image->x0, tcd->image->x1, tcd->image->y0, tcd->image->y1); for (tileno = 0; tileno < img->th * img->tw; tileno++) { opj_tcd_tile_t *tile = &tcd->tcd_image->tiles[tileno]; fprintf(fd, " tile {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numcomps=%d\n", tile->x0, tile->y0, tile->x1, tile->y1, tile->numcomps); for (compno = 0; compno < tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tile->comps[compno]; fprintf(fd, " tilec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, numresolutions=%d\n", tilec->x0, tilec->y0, tilec->x1, tilec->y1, tilec->numresolutions); for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; fprintf(fd, "\n res {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, pw=%d, ph=%d, numbands=%d\n", res->x0, res->y0, res->x1, res->y1, res->pw, res->ph, res->numbands); for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; fprintf(fd, " band {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, stepsize=%f, numbps=%d\n", band->x0, band->y0, band->x1, band->y1, band->stepsize, band->numbps); for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prec = &band->precincts[precno]; fprintf(fd, " prec {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d, cw=%d, ch=%d\n", prec->x0, prec->y0, prec->x1, prec->y1, prec->cw, prec->ch); /* for (cblkno = 0; cblkno < prec->cw * prec->ch; cblkno++) { opj_tcd_cblk_t *cblk = &prec->cblks[cblkno]; fprintf(fd, " cblk {\n"); fprintf(fd, " x0=%d, y0=%d, x1=%d, y1=%d\n", cblk->x0, cblk->y0, cblk->x1, cblk->y1); fprintf(fd, " }\n"); } */ fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, " }\n"); } fprintf(fd, "}\n"); } #endif /** * Initializes tile coding/decoding */ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block); /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block); /** * Deallocates the decoding data of the given precinct. */ static void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct); /** * Allocates memory for an encoding code block (but not data). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block); /** * Allocates data for an encoding code block */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block); /** * Deallocates the encoding data of the given precinct. */ static void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct); /** Free the memory allocated for encoding @param tcd TCD handle */ static void opj_tcd_free_tile(opj_tcd_t *tcd); static OPJ_BOOL opj_tcd_t2_decode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index ); static OPJ_BOOL opj_tcd_t1_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dwt_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_mct_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dc_level_shift_decode (opj_tcd_t *p_tcd); static OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ); static OPJ_BOOL opj_tcd_t2_encode ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); static OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ); /* ----------------------------------------------------------------------- */ /** Create a new TCD handle */ opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder) { opj_tcd_t *l_tcd = 00; /* create the tcd structure */ l_tcd = (opj_tcd_t*) opj_calloc(1,sizeof(opj_tcd_t)); if (!l_tcd) { return 00; } l_tcd->m_is_decoder = p_is_decoder ? 1 : 0; l_tcd->tcd_image = (opj_tcd_image_t*)opj_calloc(1,sizeof(opj_tcd_image_t)); if (!l_tcd->tcd_image) { opj_free(l_tcd); return 00; } return l_tcd; } /* ----------------------------------------------------------------------- */ void opj_tcd_rateallocate_fixed(opj_tcd_t *tcd) { OPJ_UINT32 layno; for (layno = 0; layno < tcd->tcp->numlayers; layno++) { opj_tcd_makelayer_fixed(tcd, layno, 1); } } void opj_tcd_makelayer( opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_FLOAT64 thresh, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_UINT32 passno; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; tcd_tile->distolayer[layno] = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; for (passno = cblk->numpassesinlayers; passno < cblk->totalpasses; passno++) { OPJ_UINT32 dr; OPJ_FLOAT64 dd; opj_tcd_pass_t *pass = &cblk->passes[passno]; if (n == 0) { dr = pass->rate; dd = pass->distortiondec; } else { dr = pass->rate - cblk->passes[n - 1].rate; dd = pass->distortiondec - cblk->passes[n - 1].distortiondec; } if (!dr) { if (dd != 0) n = passno + 1; continue; } if (dd / dr >= thresh) n = passno + 1; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) { layer->disto = 0; continue; } if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; layer->disto = cblk->passes[n - 1].distortiondec; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; layer->disto = cblk->passes[n - 1].distortiondec - cblk->passes[cblk->numpassesinlayers - 1].distortiondec; } tcd_tile->distolayer[layno] += layer->disto; /* fixed_quality */ if (final) cblk->numpassesinlayers = n; } } } } } } void opj_tcd_makelayer_fixed(opj_tcd_t *tcd, OPJ_UINT32 layno, OPJ_UINT32 final) { OPJ_UINT32 compno, resno, bandno, precno, cblkno; OPJ_INT32 value; /*, matrice[tcd_tcp->numlayers][tcd_tile->comps[0].numresolutions][3]; */ OPJ_INT32 matrice[10][10][3]; OPJ_UINT32 i, j, k; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; for (i = 0; i < tcd_tcp->numlayers; i++) { for (j = 0; j < tilec->numresolutions; j++) { for (k = 0; k < 3; k++) { matrice[i][j][k] = (OPJ_INT32) ((OPJ_FLOAT32)cp->m_specific_param.m_enc.m_matrice[i * tilec->numresolutions * 3 + j * 3 + k] * (OPJ_FLOAT32) (tcd->image->comps[compno].prec / 16.0)); } } } for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; opj_tcd_layer_t *layer = &cblk->layers[layno]; OPJ_UINT32 n; OPJ_INT32 imsb = (OPJ_INT32)(tcd->image->comps[compno].prec - cblk->numbps); /* number of bit-plan equal to zero */ /* Correction of the matrix of coefficient to include the IMSB information */ if (layno == 0) { value = matrice[layno][resno][bandno]; if (imsb >= value) { value = 0; } else { value -= imsb; } } else { value = matrice[layno][resno][bandno] - matrice[layno - 1][resno][bandno]; if (imsb >= matrice[layno - 1][resno][bandno]) { value -= (imsb - matrice[layno - 1][resno][bandno]); if (value < 0) { value = 0; } } } if (layno == 0) { cblk->numpassesinlayers = 0; } n = cblk->numpassesinlayers; if (cblk->numpassesinlayers == 0) { if (value != 0) { n = 3 * (OPJ_UINT32)value - 2 + cblk->numpassesinlayers; } else { n = cblk->numpassesinlayers; } } else { n = 3 * (OPJ_UINT32)value + cblk->numpassesinlayers; } layer->numpasses = n - cblk->numpassesinlayers; if (!layer->numpasses) continue; if (cblk->numpassesinlayers == 0) { layer->len = cblk->passes[n - 1].rate; layer->data = cblk->data; } else { layer->len = cblk->passes[n - 1].rate - cblk->passes[cblk->numpassesinlayers - 1].rate; layer->data = cblk->data + cblk->passes[cblk->numpassesinlayers - 1].rate; } if (final) cblk->numpassesinlayers = n; } } } } } } OPJ_BOOL opj_tcd_rateallocate( opj_tcd_t *tcd, OPJ_BYTE *dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 len, opj_codestream_info_t *cstr_info) { OPJ_UINT32 compno, resno, bandno, precno, cblkno, layno; OPJ_UINT32 passno; OPJ_FLOAT64 min, max; OPJ_FLOAT64 cumdisto[100]; /* fixed_quality */ const OPJ_FLOAT64 K = 1; /* 1.1; fixed_quality */ OPJ_FLOAT64 maxSE = 0; opj_cp_t *cp = tcd->cp; opj_tcd_tile_t *tcd_tile = tcd->tcd_image->tiles; opj_tcp_t *tcd_tcp = tcd->tcp; min = DBL_MAX; max = 0; tcd_tile->numpix = 0; /* fixed_quality */ for (compno = 0; compno < tcd_tile->numcomps; compno++) { opj_tcd_tilecomp_t *tilec = &tcd_tile->comps[compno]; tilec->numpix = 0; for (resno = 0; resno < tilec->numresolutions; resno++) { opj_tcd_resolution_t *res = &tilec->resolutions[resno]; for (bandno = 0; bandno < res->numbands; bandno++) { opj_tcd_band_t *band = &res->bands[bandno]; for (precno = 0; precno < res->pw * res->ph; precno++) { opj_tcd_precinct_t *prc = &band->precincts[precno]; for (cblkno = 0; cblkno < prc->cw * prc->ch; cblkno++) { opj_tcd_cblk_enc_t *cblk = &prc->cblks.enc[cblkno]; for (passno = 0; passno < cblk->totalpasses; passno++) { opj_tcd_pass_t *pass = &cblk->passes[passno]; OPJ_INT32 dr; OPJ_FLOAT64 dd, rdslope; if (passno == 0) { dr = (OPJ_INT32)pass->rate; dd = pass->distortiondec; } else { dr = (OPJ_INT32)(pass->rate - cblk->passes[passno - 1].rate); dd = pass->distortiondec - cblk->passes[passno - 1].distortiondec; } if (dr == 0) { continue; } rdslope = dd / dr; if (rdslope < min) { min = rdslope; } if (rdslope > max) { max = rdslope; } } /* passno */ /* fixed_quality */ tcd_tile->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); tilec->numpix += ((cblk->x1 - cblk->x0) * (cblk->y1 - cblk->y0)); } /* cbklno */ } /* precno */ } /* bandno */ } /* resno */ maxSE += (((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) - 1.0) * ((OPJ_FLOAT64)(1 << tcd->image->comps[compno].prec) -1.0)) * ((OPJ_FLOAT64)(tilec->numpix)); } /* compno */ /* index file */ if(cstr_info) { opj_tile_info_t *tile_info = &cstr_info->tile[tcd->tcd_tileno]; tile_info->numpix = tcd_tile->numpix; tile_info->distotile = tcd_tile->distotile; tile_info->thresh = (OPJ_FLOAT64 *) opj_malloc(tcd_tcp->numlayers * sizeof(OPJ_FLOAT64)); if (!tile_info->thresh) { /* FIXME event manager error callback */ return OPJ_FALSE; } } for (layno = 0; layno < tcd_tcp->numlayers; layno++) { OPJ_FLOAT64 lo = min; OPJ_FLOAT64 hi = max; OPJ_BOOL success = OPJ_FALSE; OPJ_UINT32 maxlen = tcd_tcp->rates[layno] ? opj_uint_min(((OPJ_UINT32) ceil(tcd_tcp->rates[layno])), len) : len; OPJ_FLOAT64 goodthresh = 0; OPJ_FLOAT64 stable_thresh = 0; OPJ_UINT32 i; OPJ_FLOAT64 distotarget; /* fixed_quality */ /* fixed_quality */ distotarget = tcd_tile->distotile - ((K * maxSE) / pow((OPJ_FLOAT32)10, tcd_tcp->distoratio[layno] / 10)); /* Don't try to find an optimal threshold but rather take everything not included yet, if -r xx,yy,zz,0 (disto_alloc == 1 and rates == 0) -q xx,yy,zz,0 (fixed_quality == 1 and distoratio == 0) ==> possible to have some lossy layers and the last layer for sure lossless */ if ( ((cp->m_specific_param.m_enc.m_disto_alloc==1) && (tcd_tcp->rates[layno]>0)) || ((cp->m_specific_param.m_enc.m_fixed_quality==1) && (tcd_tcp->distoratio[layno]>0))) { opj_t2_t*t2 = opj_t2_create(tcd->image, cp); OPJ_FLOAT64 thresh = 0; if (t2 == 00) { return OPJ_FALSE; } for (i = 0; i < 128; ++i) { OPJ_FLOAT64 distoachieved = 0; /* fixed_quality */ thresh = (lo + hi) / 2; opj_tcd_makelayer(tcd, layno, thresh, 0); if (cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ if(OPJ_IS_CINEMA(cp->rsiz)){ if (! opj_t2_encode_packets(t2,tcd->tcd_tileno, tcd_tile, layno + 1, dest, p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { lo = thresh; continue; } else { distoachieved = layno == 0 ? tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno]; if (distoachieved < distotarget) { hi=thresh; stable_thresh = thresh; continue; }else{ lo=thresh; } } }else{ distoachieved = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); if (distoachieved < distotarget) { hi = thresh; stable_thresh = thresh; continue; } lo = thresh; } } else { if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,p_data_written, maxlen, cstr_info,tcd->cur_tp_num,tcd->tp_pos,tcd->cur_pino,THRESH_CALC)) { /* TODO: what to do with l ??? seek / tell ??? */ /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */ lo = thresh; continue; } hi = thresh; stable_thresh = thresh; } } success = OPJ_TRUE; goodthresh = stable_thresh == 0? thresh : stable_thresh; opj_t2_destroy(t2); } else { success = OPJ_TRUE; goodthresh = min; } if (!success) { return OPJ_FALSE; } if(cstr_info) { /* Threshold for Marcela Index */ cstr_info->tile[tcd->tcd_tileno].thresh[layno] = goodthresh; } opj_tcd_makelayer(tcd, layno, goodthresh, 1); /* fixed_quality */ cumdisto[layno] = (layno == 0) ? tcd_tile->distolayer[0] : (cumdisto[layno - 1] + tcd_tile->distolayer[layno]); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_init( opj_tcd_t *p_tcd, opj_image_t * p_image, opj_cp_t * p_cp ) { p_tcd->image = p_image; p_tcd->cp = p_cp; p_tcd->tcd_image->tiles = (opj_tcd_tile_t *) opj_calloc(1,sizeof(opj_tcd_tile_t)); if (! p_tcd->tcd_image->tiles) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->comps = (opj_tcd_tilecomp_t *) opj_calloc(p_image->numcomps,sizeof(opj_tcd_tilecomp_t)); if (! p_tcd->tcd_image->tiles->comps ) { return OPJ_FALSE; } p_tcd->tcd_image->tiles->numcomps = p_image->numcomps; p_tcd->tp_pos = p_cp->m_specific_param.m_enc.m_tp_pos; return OPJ_TRUE; } /** Destroy a previously created TCD handle */ void opj_tcd_destroy(opj_tcd_t *tcd) { if (tcd) { opj_tcd_free_tile(tcd); if (tcd->tcd_image) { opj_free(tcd->tcd_image); tcd->tcd_image = 00; } opj_free(tcd); } } OPJ_BOOL opj_alloc_tile_component_data(opj_tcd_tilecomp_t *l_tilec) { if ((l_tilec->data == 00) || ((l_tilec->data_size_needed > l_tilec->data_size) && (l_tilec->ownsData == OPJ_FALSE))) { l_tilec->data = (OPJ_INT32 *) opj_malloc(l_tilec->data_size_needed); if (! l_tilec->data ) { return OPJ_FALSE; } /*fprintf(stderr, "tAllocate data of tilec (int): %d x OPJ_UINT32n",l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } else if (l_tilec->data_size_needed > l_tilec->data_size) { OPJ_INT32 * new_data = (OPJ_INT32 *) opj_realloc(l_tilec->data, l_tilec->data_size_needed); /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle tile datan"); */ /* fprintf(stderr, "Not enough memory to handle tile data"); */ if (! new_data) { opj_free(l_tilec->data); l_tilec->data = NULL; l_tilec->data_size = 0; l_tilec->data_size_needed = 0; l_tilec->ownsData = OPJ_FALSE; return OPJ_FALSE; } l_tilec->data = new_data; /*fprintf(stderr, "tReallocate data of tilec (int): from %d to %d x OPJ_UINT32n", l_tilec->data_size, l_data_size);*/ l_tilec->data_size = l_tilec->data_size_needed; l_tilec->ownsData = OPJ_TRUE; } return OPJ_TRUE; } /* ----------------------------------------------------------------------- */ static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block) { OPJ_UINT32 (*l_gain_ptr)(OPJ_UINT32) = 00; OPJ_UINT32 compno, resno, bandno, precno, cblkno; opj_tcp_t * l_tcp = 00; opj_cp_t * l_cp = 00; opj_tcd_tile_t * l_tile = 00; opj_tccp_t *l_tccp = 00; opj_tcd_tilecomp_t *l_tilec = 00; opj_image_comp_t * l_image_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_stepsize_t * l_step_size = 00; opj_tcd_precinct_t *l_current_precinct = 00; opj_image_t *l_image = 00; OPJ_UINT32 p,q; OPJ_UINT32 l_level_no; OPJ_UINT32 l_pdx, l_pdy; OPJ_UINT32 l_gain; OPJ_INT32 l_x0b, l_y0b; /* extent of precincts , top left, bottom right**/ OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end; /* number of precinct for a resolution */ OPJ_UINT32 l_nb_precincts; /* room needed to store l_nb_precinct precinct for a resolution */ OPJ_UINT32 l_nb_precinct_size; /* number of code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks; /* room needed to store l_nb_code_blocks code blocks for a precinct*/ OPJ_UINT32 l_nb_code_blocks_size; /* size of data for a tile */ OPJ_UINT32 l_data_size; l_cp = p_tcd->cp; l_tcp = &(l_cp->tcps[p_tile_no]); l_tile = p_tcd->tcd_image->tiles; l_tccp = l_tcp->tccps; l_tilec = l_tile->comps; l_image = p_tcd->image; l_image_comp = p_tcd->image->comps; p = p_tile_no % l_cp->tw; /* tile coordinates */ q = p_tile_no / l_cp->tw; /*fprintf(stderr, "Tile coordinate = %d,%d\n", p, q);*/ /* 4 borders of the tile rescale on the image if necessary */ l_tile->x0 = (OPJ_INT32)opj_uint_max(l_cp->tx0 + p * l_cp->tdx, l_image->x0); l_tile->y0 = (OPJ_INT32)opj_uint_max(l_cp->ty0 + q * l_cp->tdy, l_image->y0); l_tile->x1 = (OPJ_INT32)opj_uint_min(l_cp->tx0 + (p + 1) * l_cp->tdx, l_image->x1); l_tile->y1 = (OPJ_INT32)opj_uint_min(l_cp->ty0 + (q + 1) * l_cp->tdy, l_image->y1); /* testcase 1888.pdf.asan.35.988 */ if (l_tccp->numresolutions == 0) { fprintf(stderr, "tiles require at least one resolution\n"); return OPJ_FALSE; } /*fprintf(stderr, "Tile border = %d,%d,%d,%d\n", l_tile->x0, l_tile->y0,l_tile->x1,l_tile->y1);*/ /*tile->numcomps = image->numcomps; */ for (compno = 0; compno < l_tile->numcomps; ++compno) { /*fprintf(stderr, "compno = %d/%d\n", compno, l_tile->numcomps);*/ l_image_comp->resno_decoded = 0; /* border of each l_tile component (global) */ l_tilec->x0 = opj_int_ceildiv(l_tile->x0, (OPJ_INT32)l_image_comp->dx); l_tilec->y0 = opj_int_ceildiv(l_tile->y0, (OPJ_INT32)l_image_comp->dy); l_tilec->x1 = opj_int_ceildiv(l_tile->x1, (OPJ_INT32)l_image_comp->dx); l_tilec->y1 = opj_int_ceildiv(l_tile->y1, (OPJ_INT32)l_image_comp->dy); /*fprintf(stderr, "\tTile compo border = %d,%d,%d,%d\n", l_tilec->x0, l_tilec->y0,l_tilec->x1,l_tilec->y1);*/ /* compute l_data_size with overflow check */ l_data_size = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0); if ((((OPJ_UINT32)-1) / l_data_size) < (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0)) { /* TODO event */ return OPJ_FALSE; } l_data_size = l_data_size * (OPJ_UINT32)(l_tilec->y1 - l_tilec->y0); if ((((OPJ_UINT32)-1) / (OPJ_UINT32)sizeof(OPJ_UINT32)) < l_data_size) { /* TODO event */ return OPJ_FALSE; } l_data_size = l_data_size * (OPJ_UINT32)sizeof(OPJ_UINT32); l_tilec->numresolutions = l_tccp->numresolutions; if (l_tccp->numresolutions < l_cp->m_specific_param.m_dec.m_reduce) { l_tilec->minimum_num_resolutions = 1; } else { l_tilec->minimum_num_resolutions = l_tccp->numresolutions - l_cp->m_specific_param.m_dec.m_reduce; } l_tilec->data_size_needed = l_data_size; if (p_tcd->m_is_decoder && !opj_alloc_tile_component_data(l_tilec)) { return OPJ_FALSE; } l_data_size = l_tilec->numresolutions * (OPJ_UINT32)sizeof(opj_tcd_resolution_t); if (l_tilec->resolutions == 00) { l_tilec->resolutions = (opj_tcd_resolution_t *) opj_malloc(l_data_size); if (! l_tilec->resolutions ) { return OPJ_FALSE; } /*fprintf(stderr, "\tAllocate resolutions of tilec (opj_tcd_resolution_t): %d\n",l_data_size);*/ l_tilec->resolutions_size = l_data_size; memset(l_tilec->resolutions,0,l_data_size); } else if (l_data_size > l_tilec->resolutions_size) { opj_tcd_resolution_t* new_resolutions = (opj_tcd_resolution_t *) opj_realloc(l_tilec->resolutions, l_data_size); if (! new_resolutions) { /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to tile resolutions\n"); */ fprintf(stderr, "Not enough memory to tile resolutions\n"); opj_free(l_tilec->resolutions); l_tilec->resolutions = NULL; l_tilec->resolutions_size = 0; return OPJ_FALSE; } l_tilec->resolutions = new_resolutions; /*fprintf(stderr, "\tReallocate data of tilec (int): from %d to %d x OPJ_UINT32\n", l_tilec->resolutions_size, l_data_size);*/ memset(((OPJ_BYTE*) l_tilec->resolutions)+l_tilec->resolutions_size,0,l_data_size - l_tilec->resolutions_size); l_tilec->resolutions_size = l_data_size; } l_level_no = l_tilec->numresolutions - 1; l_res = l_tilec->resolutions; l_step_size = l_tccp->stepsizes; if (l_tccp->qmfbid == 0) { l_gain_ptr = &opj_dwt_getgain_real; } else { l_gain_ptr = &opj_dwt_getgain; } /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/ for (resno = 0; resno < l_tilec->numresolutions; ++resno) { /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/ OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/; OPJ_UINT32 cbgwidthexpn, cbgheightexpn; OPJ_UINT32 cblkwidthexpn, cblkheightexpn; /* border for each resolution level (global) */ l_res->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_res->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_res->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_res->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); /*fprintf(stderr, "\t\t\tres_x0= %d, res_y0 =%d, res_x1=%d, res_y1=%d\n", l_res->x0, l_res->y0, l_res->x1, l_res->y1);*/ /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */ l_pdx = l_tccp->prcw[resno]; l_pdy = l_tccp->prch[resno]; /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/ /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000) */ l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx; l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy; l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx; l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy; /*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/ l_res->pw = (l_res->x0 == l_res->x1) ? 0 : (OPJ_UINT32)((l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx); l_res->ph = (l_res->y0 == l_res->y1) ? 0 : (OPJ_UINT32)((l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy); /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/ l_nb_precincts = l_res->pw * l_res->ph; l_nb_precinct_size = l_nb_precincts * (OPJ_UINT32)sizeof(opj_tcd_precinct_t); if (resno == 0) { tlcbgxstart = l_tl_prc_x_start; tlcbgystart = l_tl_prc_y_start; /*brcbgxend = l_br_prc_x_end;*/ /* brcbgyend = l_br_prc_y_end;*/ cbgwidthexpn = l_pdx; cbgheightexpn = l_pdy; l_res->numbands = 1; } else { tlcbgxstart = opj_int_ceildivpow2(l_tl_prc_x_start, 1); tlcbgystart = opj_int_ceildivpow2(l_tl_prc_y_start, 1); /*brcbgxend = opj_int_ceildivpow2(l_br_prc_x_end, 1);*/ /*brcbgyend = opj_int_ceildivpow2(l_br_prc_y_end, 1);*/ cbgwidthexpn = l_pdx - 1; cbgheightexpn = l_pdy - 1; l_res->numbands = 3; } cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn); cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn); l_band = l_res->bands; for (bandno = 0; bandno < l_res->numbands; ++bandno) { OPJ_INT32 numbps; /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/ if (resno == 0) { l_band->bandno = 0 ; l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no); l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no); l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no); l_band->y1 = opj_int_ceildivpow2(l_tilec->y1, (OPJ_INT32)l_level_no); } else { l_band->bandno = bandno + 1; /* x0b = 1 if bandno = 1 or 3 */ l_x0b = l_band->bandno&1; /* y0b = 1 if bandno = 2 or 3 */ l_y0b = (OPJ_INT32)((l_band->bandno)>>1); /* l_band border (global) */ l_band->x0 = opj_int_ceildivpow2(l_tilec->x0 - (1 << l_level_no) * l_x0b, (OPJ_INT32)(l_level_no + 1)); l_band->y0 = opj_int_ceildivpow2(l_tilec->y0 - (1 << l_level_no) * l_y0b, (OPJ_INT32)(l_level_no + 1)); l_band->x1 = opj_int_ceildivpow2(l_tilec->x1 - (1 << l_level_no) * l_x0b, (OPJ_INT32)(l_level_no + 1)); l_band->y1 = opj_int_ceildivpow2(l_tilec->y1 - (1 << l_level_no) * l_y0b, (OPJ_INT32)(l_level_no + 1)); } /** avoid an if with storing function pointer */ l_gain = (*l_gain_ptr) (l_band->bandno); numbps = (OPJ_INT32)(l_image_comp->prec + l_gain); l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0, (OPJ_INT32) (numbps - l_step_size->expn)))) * fraction; l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits - 1; /* WHY -1 ? */ if (! l_band->precincts) { l_band->precincts = (opj_tcd_precinct_t *) opj_malloc( /*3 * */ l_nb_precinct_size); if (! l_band->precincts) { return OPJ_FALSE; } /*fprintf(stderr, "\t\t\t\tAllocate precincts of a band (opj_tcd_precinct_t): %d\n",l_nb_precinct_size); */ memset(l_band->precincts,0,l_nb_precinct_size); l_band->precincts_data_size = l_nb_precinct_size; } else if (l_band->precincts_data_size < l_nb_precinct_size) { opj_tcd_precinct_t * new_precincts = (opj_tcd_precinct_t *) opj_realloc(l_band->precincts,/*3 * */ l_nb_precinct_size); if (! new_precincts) { /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory to handle band precints\n"); */ fprintf(stderr, "Not enough memory to handle band precints\n"); opj_free(l_band->precincts); l_band->precincts = NULL; l_band->precincts_data_size = 0; return OPJ_FALSE; } l_band->precincts = new_precincts; /*fprintf(stderr, "\t\t\t\tReallocate precincts of a band (opj_tcd_precinct_t): from %d to %d\n",l_band->precincts_data_size, l_nb_precinct_size);*/ memset(((OPJ_BYTE *) l_band->precincts) + l_band->precincts_data_size,0,l_nb_precinct_size - l_band->precincts_data_size); l_band->precincts_data_size = l_nb_precinct_size; } l_current_precinct = l_band->precincts; for (precno = 0; precno < l_nb_precincts; ++precno) { OPJ_INT32 tlcblkxstart, tlcblkystart, brcblkxend, brcblkyend; OPJ_INT32 cbgxstart = tlcbgxstart + (OPJ_INT32)(precno % l_res->pw) * (1 << cbgwidthexpn); OPJ_INT32 cbgystart = tlcbgystart + (OPJ_INT32)(precno / l_res->pw) * (1 << cbgheightexpn); OPJ_INT32 cbgxend = cbgxstart + (1 << cbgwidthexpn); OPJ_INT32 cbgyend = cbgystart + (1 << cbgheightexpn); /*fprintf(stderr, "\t precno=%d; bandno=%d, resno=%d; compno=%d\n", precno, bandno , resno, compno);*/ /*fprintf(stderr, "\t tlcbgxstart(=%d) + (precno(=%d) percent res->pw(=%d)) * (1 << cbgwidthexpn(=%d)) \n",tlcbgxstart,precno,l_res->pw,cbgwidthexpn);*/ /* precinct size (global) */ /*fprintf(stderr, "\t cbgxstart=%d, l_band->x0 = %d \n",cbgxstart, l_band->x0);*/ l_current_precinct->x0 = opj_int_max(cbgxstart, l_band->x0); l_current_precinct->y0 = opj_int_max(cbgystart, l_band->y0); l_current_precinct->x1 = opj_int_min(cbgxend, l_band->x1); l_current_precinct->y1 = opj_int_min(cbgyend, l_band->y1); /*fprintf(stderr, "\t prc_x0=%d; prc_y0=%d, prc_x1=%d; prc_y1=%d\n",l_current_precinct->x0, l_current_precinct->y0 ,l_current_precinct->x1, l_current_precinct->y1);*/ tlcblkxstart = opj_int_floordivpow2(l_current_precinct->x0, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, "\t tlcblkxstart =%d\n",tlcblkxstart );*/ tlcblkystart = opj_int_floordivpow2(l_current_precinct->y0, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, "\t tlcblkystart =%d\n",tlcblkystart );*/ brcblkxend = opj_int_ceildivpow2(l_current_precinct->x1, (OPJ_INT32)cblkwidthexpn) << cblkwidthexpn; /*fprintf(stderr, "\t brcblkxend =%d\n",brcblkxend );*/ brcblkyend = opj_int_ceildivpow2(l_current_precinct->y1, (OPJ_INT32)cblkheightexpn) << cblkheightexpn; /*fprintf(stderr, "\t brcblkyend =%d\n",brcblkyend );*/ l_current_precinct->cw = (OPJ_UINT32)((brcblkxend - tlcblkxstart) >> cblkwidthexpn); l_current_precinct->ch = (OPJ_UINT32)((brcblkyend - tlcblkystart) >> cblkheightexpn); l_nb_code_blocks = l_current_precinct->cw * l_current_precinct->ch; /*fprintf(stderr, "\t\t\t\t precinct_cw = %d x recinct_ch = %d\n",l_current_precinct->cw, l_current_precinct->ch); */ l_nb_code_blocks_size = l_nb_code_blocks * (OPJ_UINT32)sizeof_block; if (! l_current_precinct->cblks.blocks) { l_current_precinct->cblks.blocks = opj_malloc(l_nb_code_blocks_size); if (! l_current_precinct->cblks.blocks ) { return OPJ_FALSE; } /*fprintf(stderr, "\t\t\t\tAllocate cblks of a precinct (opj_tcd_cblk_dec_t): %d\n",l_nb_code_blocks_size);*/ memset(l_current_precinct->cblks.blocks,0,l_nb_code_blocks_size); l_current_precinct->block_size = l_nb_code_blocks_size; } else if (l_nb_code_blocks_size > l_current_precinct->block_size) { void *new_blocks = opj_realloc(l_current_precinct->cblks.blocks, l_nb_code_blocks_size); if (! new_blocks) { opj_free(l_current_precinct->cblks.blocks); l_current_precinct->cblks.blocks = NULL; l_current_precinct->block_size = 0; /* opj_event_msg(p_manager, EVT_ERROR, "Not enough memory for current precinct codeblock element\n"); */ fprintf(stderr, "Not enough memory for current precinct codeblock element\n"); return OPJ_FALSE; } l_current_precinct->cblks.blocks = new_blocks; /*fprintf(stderr, "\t\t\t\tReallocate cblks of a precinct (opj_tcd_cblk_dec_t): from %d to %d\n",l_current_precinct->block_size, l_nb_code_blocks_size); */ memset(((OPJ_BYTE *) l_current_precinct->cblks.blocks) + l_current_precinct->block_size ,0 ,l_nb_code_blocks_size - l_current_precinct->block_size); l_current_precinct->block_size = l_nb_code_blocks_size; } if (! l_current_precinct->incltree) { l_current_precinct->incltree = opj_tgt_create(l_current_precinct->cw, l_current_precinct->ch); } else{ l_current_precinct->incltree = opj_tgt_init(l_current_precinct->incltree, l_current_precinct->cw, l_current_precinct->ch); } if (! l_current_precinct->incltree) { fprintf(stderr, "WARNING: No incltree created.\n"); /*return OPJ_FALSE;*/ } if (! l_current_precinct->imsbtree) { l_current_precinct->imsbtree = opj_tgt_create( l_current_precinct->cw, l_current_precinct->ch); } else { l_current_precinct->imsbtree = opj_tgt_init( l_current_precinct->imsbtree, l_current_precinct->cw, l_current_precinct->ch); } if (! l_current_precinct->imsbtree) { fprintf(stderr, "WARNING: No imsbtree created.\n"); /*return OPJ_FALSE;*/ } for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { OPJ_INT32 cblkxstart = tlcblkxstart + (OPJ_INT32)(cblkno % l_current_precinct->cw) * (1 << cblkwidthexpn); OPJ_INT32 cblkystart = tlcblkystart + (OPJ_INT32)(cblkno / l_current_precinct->cw) * (1 << cblkheightexpn); OPJ_INT32 cblkxend = cblkxstart + (1 << cblkwidthexpn); OPJ_INT32 cblkyend = cblkystart + (1 << cblkheightexpn); if (isEncoder) { opj_tcd_cblk_enc_t* l_code_block = l_current_precinct->cblks.enc + cblkno; if (! opj_tcd_code_block_enc_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); if (! opj_tcd_code_block_enc_allocate_data(l_code_block)) { return OPJ_FALSE; } } else { opj_tcd_cblk_dec_t* l_code_block = l_current_precinct->cblks.dec + cblkno; if (! opj_tcd_code_block_dec_allocate(l_code_block)) { return OPJ_FALSE; } /* code-block size (global) */ l_code_block->x0 = opj_int_max(cblkxstart, l_current_precinct->x0); l_code_block->y0 = opj_int_max(cblkystart, l_current_precinct->y0); l_code_block->x1 = opj_int_min(cblkxend, l_current_precinct->x1); l_code_block->y1 = opj_int_min(cblkyend, l_current_precinct->y1); } } ++l_current_precinct; } /* precno */ ++l_band; ++l_step_size; } /* bandno */ ++l_res; --l_level_no; } /* resno */ ++l_tccp; ++l_tilec; ++l_image_comp; } /* compno */ return OPJ_TRUE; } OPJ_BOOL opj_tcd_init_encode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F, sizeof(opj_tcd_cblk_enc_t)); } OPJ_BOOL opj_tcd_init_decode_tile (opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no) { return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F, sizeof(opj_tcd_cblk_dec_t)); } /** * Allocates memory for an encoding code block (but not data memory). */ static OPJ_BOOL opj_tcd_code_block_enc_allocate (opj_tcd_cblk_enc_t * p_code_block) { if (! p_code_block->layers) { /* no memset since data */ p_code_block->layers = (opj_tcd_layer_t*) opj_calloc(100, sizeof(opj_tcd_layer_t)); if (! p_code_block->layers) { return OPJ_FALSE; } } if (! p_code_block->passes) { p_code_block->passes = (opj_tcd_pass_t*) opj_calloc(100, sizeof(opj_tcd_pass_t)); if (! p_code_block->passes) { return OPJ_FALSE; } } return OPJ_TRUE; } /** * Allocates data memory for an encoding code block. */ static OPJ_BOOL opj_tcd_code_block_enc_allocate_data (opj_tcd_cblk_enc_t * p_code_block) { OPJ_UINT32 l_data_size; l_data_size = (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) * (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32)); if (l_data_size > p_code_block->data_size) { if (p_code_block->data) { opj_free(p_code_block->data - 1); /* again, why -1 */ } p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size); if(! p_code_block->data) { p_code_block->data_size = 0U; return OPJ_FALSE; } p_code_block->data_size = l_data_size; p_code_block->data[0] = 0; p_code_block->data+=1; /*why +1 ?*/ } return OPJ_TRUE; } /** * Allocates memory for a decoding code block. */ static OPJ_BOOL opj_tcd_code_block_dec_allocate (opj_tcd_cblk_dec_t * p_code_block) { if (! p_code_block->data) { p_code_block->data = (OPJ_BYTE*) opj_malloc(OPJ_J2K_DEFAULT_CBLK_DATA_SIZE); if (! p_code_block->data) { return OPJ_FALSE; } p_code_block->data_max_size = OPJ_J2K_DEFAULT_CBLK_DATA_SIZE; /*fprintf(stderr, "Allocate 8192 elements of code_block->data\n");*/ p_code_block->segs = (opj_tcd_seg_t *) opj_calloc(OPJ_J2K_DEFAULT_NB_SEGS,sizeof(opj_tcd_seg_t)); if (! p_code_block->segs) { return OPJ_FALSE; } /*fprintf(stderr, "Allocate %d elements of code_block->data\n", OPJ_J2K_DEFAULT_NB_SEGS * sizeof(opj_tcd_seg_t));*/ p_code_block->m_current_max_segs = OPJ_J2K_DEFAULT_NB_SEGS; /*fprintf(stderr, "m_current_max_segs of code_block->data = %d\n", p_code_block->m_current_max_segs);*/ } else { /* sanitize */ OPJ_BYTE* l_data = p_code_block->data; OPJ_UINT32 l_data_max_size = p_code_block->data_max_size; opj_tcd_seg_t * l_segs = p_code_block->segs; OPJ_UINT32 l_current_max_segs = p_code_block->m_current_max_segs; memset(p_code_block, 0, sizeof(opj_tcd_cblk_dec_t)); p_code_block->data = l_data; p_code_block->data_max_size = l_data_max_size; p_code_block->segs = l_segs; p_code_block->m_current_max_segs = l_current_max_segs; } return OPJ_TRUE; } OPJ_UINT32 opj_tcd_get_decoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i; OPJ_UINT32 l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tcd_resolution_t * l_res = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tile_comp = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if(l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_res = l_tile_comp->resolutions + l_tile_comp->minimum_num_resolutions - 1; l_data_size += l_size_comp * (OPJ_UINT32)((l_res->x1 - l_res->x0) * (l_res->y1 - l_res->y0)); ++l_img_comp; ++l_tile_comp; } return l_data_size; } OPJ_BOOL opj_tcd_encode_tile( opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no, OPJ_BYTE *p_dest, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_length, opj_codestream_info_t *p_cstr_info) { if (p_tcd->cur_tp_num == 0) { p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no]; /* INDEX >> "Precinct_nb_X et Precinct_nb_Y" */ if(p_cstr_info) { OPJ_UINT32 l_num_packs = 0; OPJ_UINT32 i; opj_tcd_tilecomp_t *l_tilec_idx = &p_tcd->tcd_image->tiles->comps[0]; /* based on component 0 */ opj_tccp_t *l_tccp = p_tcd->tcp->tccps; /* based on component 0 */ for (i = 0; i < l_tilec_idx->numresolutions; i++) { opj_tcd_resolution_t *l_res_idx = &l_tilec_idx->resolutions[i]; p_cstr_info->tile[p_tile_no].pw[i] = (int)l_res_idx->pw; p_cstr_info->tile[p_tile_no].ph[i] = (int)l_res_idx->ph; l_num_packs += l_res_idx->pw * l_res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[i] = (int)l_tccp->prcw[i]; p_cstr_info->tile[p_tile_no].pdy[i] = (int)l_tccp->prch[i]; } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t*) opj_calloc((size_t)p_cstr_info->numcomps * (size_t)p_cstr_info->numlayers * l_num_packs, sizeof(opj_packet_info_t)); if (!p_cstr_info->tile[p_tile_no].packet) { /* FIXME event manager error callback */ return OPJ_FALSE; } } /* << INDEX */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ if (! opj_tcd_dc_level_shift_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_encode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /* FIXME _ProfStart(PGROUP_RATE); */ if (! opj_tcd_rate_allocate_encode(p_tcd,p_dest,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_RATE); */ } /*--------------TIER2------------------*/ /* INDEX */ if (p_cstr_info) { p_cstr_info->index_write = 1; } /* FIXME _ProfStart(PGROUP_T2); */ if (! opj_tcd_t2_encode(p_tcd,p_dest,p_data_written,p_max_length,p_cstr_info)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_decode_tile( opj_tcd_t *p_tcd, OPJ_BYTE *p_src, OPJ_UINT32 p_max_length, OPJ_UINT32 p_tile_no, opj_codestream_index_t *p_cstr_index ) { OPJ_UINT32 l_data_read; p_tcd->tcd_tileno = p_tile_no; p_tcd->tcp = &(p_tcd->cp->tcps[p_tile_no]); #ifdef TODO_MSD /* FIXME */ /* INDEX >> */ if(p_cstr_info) { OPJ_UINT32 resno, compno, numprec = 0; for (compno = 0; compno < (OPJ_UINT32) p_cstr_info->numcomps; compno++) { opj_tcp_t *tcp = &p_tcd->cp->tcps[0]; opj_tccp_t *tccp = &tcp->tccps[compno]; opj_tcd_tilecomp_t *tilec_idx = &p_tcd->tcd_image->tiles->comps[compno]; for (resno = 0; resno < tilec_idx->numresolutions; resno++) { opj_tcd_resolution_t *res_idx = &tilec_idx->resolutions[resno]; p_cstr_info->tile[p_tile_no].pw[resno] = res_idx->pw; p_cstr_info->tile[p_tile_no].ph[resno] = res_idx->ph; numprec += res_idx->pw * res_idx->ph; p_cstr_info->tile[p_tile_no].pdx[resno] = tccp->prcw[resno]; p_cstr_info->tile[p_tile_no].pdy[resno] = tccp->prch[resno]; } } p_cstr_info->tile[p_tile_no].packet = (opj_packet_info_t *) opj_malloc(p_cstr_info->numlayers * numprec * sizeof(opj_packet_info_t)); p_cstr_info->packno = 0; } /* << INDEX */ #endif /*--------------TIER2------------------*/ /* FIXME _ProfStart(PGROUP_T2); */ l_data_read = 0; if (! opj_tcd_t2_decode(p_tcd, p_src, &l_data_read, p_max_length, p_cstr_index)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T2); */ /*------------------TIER1-----------------*/ /* FIXME _ProfStart(PGROUP_T1); */ if (! opj_tcd_t1_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_T1); */ /*----------------DWT---------------------*/ /* FIXME _ProfStart(PGROUP_DWT); */ if (! opj_tcd_dwt_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DWT); */ /*----------------MCT-------------------*/ /* FIXME _ProfStart(PGROUP_MCT); */ if (! opj_tcd_mct_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_MCT); */ /* FIXME _ProfStart(PGROUP_DC_SHIFT); */ if (! opj_tcd_dc_level_shift_decode(p_tcd)) { return OPJ_FALSE; } /* FIXME _ProfStop(PGROUP_DC_SHIFT); */ /*---------------TILE-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_update_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest, OPJ_UINT32 p_dest_length ) { OPJ_UINT32 i,j,k,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; opj_tcd_resolution_t * l_res; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_stride, l_width,l_height; l_data_size = opj_tcd_get_decoded_tile_size(p_tcd); if (l_data_size > p_dest_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_res = l_tilec->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tilec->x1 - l_tilec->x0) - l_width; if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_dest_ptr = (OPJ_CHAR *) p_dest; const OPJ_INT32 * l_src_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_CHAR) ((*(l_src_ptr++))&0xff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE *)l_dest_ptr; } break; case 2: { const OPJ_INT32 * l_src_ptr = l_tilec->data; OPJ_INT16 * l_dest_ptr = (OPJ_INT16 *) p_dest; if (l_img_comp->sgnd) { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) (*(l_src_ptr++)); } l_src_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (OPJ_INT16) ((*(l_src_ptr++))&0xffff); } l_src_ptr += l_stride; } } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; case 4: { OPJ_INT32 * l_dest_ptr = (OPJ_INT32 *) p_dest; OPJ_INT32 * l_src_ptr = l_tilec->data; for (j=0;j<l_height;++j) { for (k=0;k<l_width;++k) { *(l_dest_ptr++) = (*(l_src_ptr++)); } l_src_ptr += l_stride; } p_dest = (OPJ_BYTE*) l_dest_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; } void opj_tcd_free_tile(opj_tcd_t *p_tcd) { OPJ_UINT32 compno, resno, bandno, precno; opj_tcd_tile_t *l_tile = 00; opj_tcd_tilecomp_t *l_tile_comp = 00; opj_tcd_resolution_t *l_res = 00; opj_tcd_band_t *l_band = 00; opj_tcd_precinct_t *l_precinct = 00; OPJ_UINT32 l_nb_resolutions, l_nb_precincts; void (* l_tcd_code_block_deallocate) (opj_tcd_precinct_t *) = 00; if (! p_tcd) { return; } if (! p_tcd->tcd_image) { return; } if (p_tcd->m_is_decoder) { l_tcd_code_block_deallocate = opj_tcd_code_block_dec_deallocate; } else { l_tcd_code_block_deallocate = opj_tcd_code_block_enc_deallocate; } l_tile = p_tcd->tcd_image->tiles; if (! l_tile) { return; } l_tile_comp = l_tile->comps; for (compno = 0; compno < l_tile->numcomps; ++compno) { l_res = l_tile_comp->resolutions; if (l_res) { l_nb_resolutions = l_tile_comp->resolutions_size / sizeof(opj_tcd_resolution_t); for (resno = 0; resno < l_nb_resolutions; ++resno) { l_band = l_res->bands; for (bandno = 0; bandno < 3; ++bandno) { l_precinct = l_band->precincts; if (l_precinct) { l_nb_precincts = l_band->precincts_data_size / sizeof(opj_tcd_precinct_t); for (precno = 0; precno < l_nb_precincts; ++precno) { opj_tgt_destroy(l_precinct->incltree); l_precinct->incltree = 00; opj_tgt_destroy(l_precinct->imsbtree); l_precinct->imsbtree = 00; (*l_tcd_code_block_deallocate) (l_precinct); ++l_precinct; } opj_free(l_band->precincts); l_band->precincts = 00; } ++l_band; } /* for (resno */ ++l_res; } opj_free(l_tile_comp->resolutions); l_tile_comp->resolutions = 00; } if (l_tile_comp->ownsData && l_tile_comp->data) { opj_free(l_tile_comp->data); l_tile_comp->data = 00; l_tile_comp->ownsData = 0; l_tile_comp->data_size = 0; l_tile_comp->data_size_needed = 0; } ++l_tile_comp; } opj_free(l_tile->comps); l_tile->comps = 00; opj_free(p_tcd->tcd_image->tiles); p_tcd->tcd_image->tiles = 00; } OPJ_BOOL opj_tcd_t2_decode (opj_tcd_t *p_tcd, OPJ_BYTE * p_src_data, OPJ_UINT32 * p_data_read, OPJ_UINT32 p_max_src_size, opj_codestream_index_t *p_cstr_index ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_decode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_src_data, p_data_read, p_max_src_size, p_cstr_index)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_t1_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_t1_t * l_t1; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t* l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; l_t1 = opj_t1_create(OPJ_FALSE); if (l_t1 == 00) { return OPJ_FALSE; } for (compno = 0; compno < l_tile->numcomps; ++compno) { /* The +3 is headroom required by the vectorized DWT */ if (OPJ_FALSE == opj_t1_decode_cblks(l_t1, l_tile_comp, l_tccp)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } ++l_tile_comp; ++l_tccp; } opj_t1_destroy(l_t1); return OPJ_TRUE; } OPJ_BOOL opj_tcd_dwt_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; opj_image_comp_t * l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { /* if (tcd->cp->reduce != 0) { tcd->image->comps[compno].resno_decoded = tile->comps[compno].numresolutions - tcd->cp->reduce - 1; if (tcd->image->comps[compno].resno_decoded < 0) { return false; } } numres2decode = tcd->image->comps[compno].resno_decoded + 1; if(numres2decode > 0){ */ if (l_tccp->qmfbid == 1) { if (! opj_dwt_decode(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } else { if (! opj_dwt_decode_real(l_tile_comp, l_img_comp->resno_decoded+1)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_img_comp; ++l_tccp; } return OPJ_TRUE; } OPJ_BOOL opj_tcd_mct_decode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcp_t * l_tcp = p_tcd->tcp; opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps; OPJ_UINT32 l_samples,i; if (! l_tcp->mct) { return OPJ_TRUE; } l_samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tile->numcomps >= 3 ){ /* testcase 1336.pdf.asan.47.376 */ if ((l_tile->comps[0].x1 - l_tile->comps[0].x0) * (l_tile->comps[0].y1 - l_tile->comps[0].y0) < (OPJ_INT32)l_samples || (l_tile->comps[1].x1 - l_tile->comps[1].x0) * (l_tile->comps[1].y1 - l_tile->comps[1].y0) < (OPJ_INT32)l_samples || (l_tile->comps[2].x1 - l_tile->comps[2].x0) * (l_tile->comps[2].y1 - l_tile->comps[2].y0) < (OPJ_INT32)l_samples) { fprintf(stderr, "Tiles don't all have the same dimension. Skip the MCT step.\n"); return OPJ_FALSE; } else if (l_tcp->mct == 2) { OPJ_BYTE ** l_data; if (! l_tcp->m_mct_decoding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_decode_custom(/* MCT data */ (OPJ_BYTE*) l_tcp->m_mct_decoding_matrix, /* size of components */ l_samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd)) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else { if (l_tcp->tccps->qmfbid == 1) { opj_mct_decode( l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, l_samples); } else { opj_mct_decode_real((OPJ_FLOAT32*)l_tile->comps[0].data, (OPJ_FLOAT32*)l_tile->comps[1].data, (OPJ_FLOAT32*)l_tile->comps[2].data, l_samples); } } } else { /* FIXME need to use opj_event_msg function */ fprintf(stderr,"Number of components (%d) is inconsistent with a MCT. Skip the MCT step.\n",l_tile->numcomps); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_dc_level_shift_decode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_resolution_t* l_res = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_width,l_height,i,j; OPJ_INT32 * l_current_ptr; OPJ_INT32 l_min, l_max; OPJ_UINT32 l_stride; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_res = l_tile_comp->resolutions + l_img_comp->resno_decoded; l_width = (OPJ_UINT32)(l_res->x1 - l_res->x0); l_height = (OPJ_UINT32)(l_res->y1 - l_res->y0); l_stride = (OPJ_UINT32)(l_tile_comp->x1 - l_tile_comp->x0) - l_width; assert(l_height == 0 || l_width + l_stride <= l_tile_comp->data_size / l_height); /*MUPDF*/ if (l_img_comp->sgnd) { l_min = -(1 << (l_img_comp->prec - 1)); l_max = (1 << (l_img_comp->prec - 1)) - 1; } else { l_min = 0; l_max = (1 << l_img_comp->prec) - 1; } l_current_ptr = l_tile_comp->data; if (l_tccp->qmfbid == 1) { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { *l_current_ptr = opj_int_clamp(*l_current_ptr + l_tccp->m_dc_level_shift, l_min, l_max); ++l_current_ptr; } l_current_ptr += l_stride; } } else { for (j=0;j<l_height;++j) { for (i = 0; i < l_width; ++i) { OPJ_FLOAT32 l_value = *((OPJ_FLOAT32 *) l_current_ptr); *l_current_ptr = opj_int_clamp((OPJ_INT32)lrintf(l_value) + l_tccp->m_dc_level_shift, l_min, l_max); ; ++l_current_ptr; } l_current_ptr += l_stride; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } /** * Deallocates the encoding data of the given precinct. */ void opj_tcd_code_block_dec_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_dec_t * l_code_block = p_precinct->cblks.dec; if (l_code_block) { /*fprintf(stderr,"deallocate codeblock:{\n");*/ /*fprintf(stderr,"\t x0=%d, y0=%d, x1=%d, y1=%d\n",l_code_block->x0, l_code_block->y0, l_code_block->x1, l_code_block->y1);*/ /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ", l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/ l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_dec_t); /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/ for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data); l_code_block->data = 00; } if (l_code_block->segs) { opj_free(l_code_block->segs ); l_code_block->segs = 00; } ++l_code_block; } opj_free(p_precinct->cblks.dec); p_precinct->cblks.dec = 00; } } /** * Deallocates the encoding data of the given precinct. */ void opj_tcd_code_block_enc_deallocate (opj_tcd_precinct_t * p_precinct) { OPJ_UINT32 cblkno , l_nb_code_blocks; opj_tcd_cblk_enc_t * l_code_block = p_precinct->cblks.enc; if (l_code_block) { l_nb_code_blocks = p_precinct->block_size / sizeof(opj_tcd_cblk_enc_t); for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { if (l_code_block->data) { opj_free(l_code_block->data - 1); l_code_block->data = 00; } if (l_code_block->layers) { opj_free(l_code_block->layers ); l_code_block->layers = 00; } if (l_code_block->passes) { opj_free(l_code_block->passes ); l_code_block->passes = 00; } ++l_code_block; } opj_free(p_precinct->cblks.enc); p_precinct->cblks.enc = 00; } } OPJ_UINT32 opj_tcd_get_encoded_tile_size ( opj_tcd_t *p_tcd ) { OPJ_UINT32 i,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } l_data_size += l_size_comp * (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); ++l_img_comp; ++l_tilec; } return l_data_size; } OPJ_BOOL opj_tcd_dc_level_shift_encode ( opj_tcd_t *p_tcd ) { OPJ_UINT32 compno; opj_tcd_tilecomp_t * l_tile_comp = 00; opj_tccp_t * l_tccp = 00; opj_image_comp_t * l_img_comp = 00; opj_tcd_tile_t * l_tile; OPJ_UINT32 l_nb_elem,i; OPJ_INT32 * l_current_ptr; l_tile = p_tcd->tcd_image->tiles; l_tile_comp = l_tile->comps; l_tccp = p_tcd->tcp->tccps; l_img_comp = p_tcd->image->comps; for (compno = 0; compno < l_tile->numcomps; compno++) { l_current_ptr = l_tile_comp->data; l_nb_elem = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); if (l_tccp->qmfbid == 1) { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr -= l_tccp->m_dc_level_shift ; ++l_current_ptr; } } else { for (i = 0; i < l_nb_elem; ++i) { *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) << 11 ; ++l_current_ptr; } } ++l_img_comp; ++l_tccp; ++l_tile_comp; } return OPJ_TRUE; } OPJ_BOOL opj_tcd_mct_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; OPJ_UINT32 samples = (OPJ_UINT32)((l_tile_comp->x1 - l_tile_comp->x0) * (l_tile_comp->y1 - l_tile_comp->y0)); OPJ_UINT32 i; OPJ_BYTE ** l_data = 00; opj_tcp_t * l_tcp = p_tcd->tcp; if(!p_tcd->tcp->mct) { return OPJ_TRUE; } if (p_tcd->tcp->mct == 2) { if (! p_tcd->tcp->m_mct_coding_matrix) { return OPJ_TRUE; } l_data = (OPJ_BYTE **) opj_malloc(l_tile->numcomps*sizeof(OPJ_BYTE*)); if (! l_data) { return OPJ_FALSE; } for (i=0;i<l_tile->numcomps;++i) { l_data[i] = (OPJ_BYTE*) l_tile_comp->data; ++l_tile_comp; } if (! opj_mct_encode_custom(/* MCT data */ (OPJ_BYTE*) p_tcd->tcp->m_mct_coding_matrix, /* size of components */ samples, /* components */ l_data, /* nb of components (i.e. size of pData) */ l_tile->numcomps, /* tells if the data is signed */ p_tcd->image->comps->sgnd) ) { opj_free(l_data); return OPJ_FALSE; } opj_free(l_data); } else if (l_tcp->tccps->qmfbid == 0) { opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } else { opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data, l_tile->comps[2].data, samples); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_dwt_encode ( opj_tcd_t *p_tcd ) { opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles; opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps; opj_tccp_t * l_tccp = p_tcd->tcp->tccps; OPJ_UINT32 compno; for (compno = 0; compno < l_tile->numcomps; ++compno) { if (l_tccp->qmfbid == 1) { if (! opj_dwt_encode(l_tile_comp)) { return OPJ_FALSE; } } else if (l_tccp->qmfbid == 0) { if (! opj_dwt_encode_real(l_tile_comp)) { return OPJ_FALSE; } } ++l_tile_comp; ++l_tccp; } return OPJ_TRUE; } OPJ_BOOL opj_tcd_t1_encode ( opj_tcd_t *p_tcd ) { opj_t1_t * l_t1; const OPJ_FLOAT64 * l_mct_norms; OPJ_UINT32 l_mct_numcomps = 0U; opj_tcp_t * l_tcp = p_tcd->tcp; l_t1 = opj_t1_create(OPJ_TRUE); if (l_t1 == 00) { return OPJ_FALSE; } if (l_tcp->mct == 1) { l_mct_numcomps = 3U; /* irreversible encoding */ if (l_tcp->tccps->qmfbid == 0) { l_mct_norms = opj_mct_get_mct_norms_real(); } else { l_mct_norms = opj_mct_get_mct_norms(); } } else { l_mct_numcomps = p_tcd->image->numcomps; l_mct_norms = (const OPJ_FLOAT64 *) (l_tcp->mct_norms); } if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles , l_tcp, l_mct_norms, l_mct_numcomps)) { opj_t1_destroy(l_t1); return OPJ_FALSE; } opj_t1_destroy(l_t1); return OPJ_TRUE; } OPJ_BOOL opj_tcd_t2_encode (opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 * p_data_written, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_t2_t * l_t2; l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp); if (l_t2 == 00) { return OPJ_FALSE; } if (! opj_t2_encode_packets( l_t2, p_tcd->tcd_tileno, p_tcd->tcd_image->tiles, p_tcd->tcp->numlayers, p_dest_data, p_data_written, p_max_dest_size, p_cstr_info, p_tcd->tp_num, p_tcd->tp_pos, p_tcd->cur_pino, FINAL_PASS)) { opj_t2_destroy(l_t2); return OPJ_FALSE; } opj_t2_destroy(l_t2); /*---------------CLEAN-------------------*/ return OPJ_TRUE; } OPJ_BOOL opj_tcd_rate_allocate_encode( opj_tcd_t *p_tcd, OPJ_BYTE * p_dest_data, OPJ_UINT32 p_max_dest_size, opj_codestream_info_t *p_cstr_info ) { opj_cp_t * l_cp = p_tcd->cp; OPJ_UINT32 l_nb_written = 0; if (p_cstr_info) { p_cstr_info->index_write = 0; } if (l_cp->m_specific_param.m_enc.m_disto_alloc|| l_cp->m_specific_param.m_enc.m_fixed_quality) { /* fixed_quality */ /* Normal Rate/distortion allocation */ if (! opj_tcd_rateallocate(p_tcd, p_dest_data,&l_nb_written, p_max_dest_size, p_cstr_info)) { return OPJ_FALSE; } } else { /* Fixed layer allocation */ opj_tcd_rateallocate_fixed(p_tcd); } return OPJ_TRUE; } OPJ_BOOL opj_tcd_copy_tile_data ( opj_tcd_t *p_tcd, OPJ_BYTE * p_src, OPJ_UINT32 p_src_length ) { OPJ_UINT32 i,j,l_data_size = 0; opj_image_comp_t * l_img_comp = 00; opj_tcd_tilecomp_t * l_tilec = 00; OPJ_UINT32 l_size_comp, l_remaining; OPJ_UINT32 l_nb_elem; l_data_size = opj_tcd_get_encoded_tile_size(p_tcd); if (l_data_size != p_src_length) { return OPJ_FALSE; } l_tilec = p_tcd->tcd_image->tiles->comps; l_img_comp = p_tcd->image->comps; for (i=0;i<p_tcd->image->numcomps;++i) { l_size_comp = l_img_comp->prec >> 3; /*(/ 8)*/ l_remaining = l_img_comp->prec & 7; /* (%8) */ l_nb_elem = (OPJ_UINT32)((l_tilec->x1 - l_tilec->x0) * (l_tilec->y1 - l_tilec->y0)); if (l_remaining) { ++l_size_comp; } if (l_size_comp == 3) { l_size_comp = 4; } switch (l_size_comp) { case 1: { OPJ_CHAR * l_src_ptr = (OPJ_CHAR *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 2: { OPJ_INT32 * l_dest_ptr = l_tilec->data; OPJ_INT16 * l_src_ptr = (OPJ_INT16 *) p_src; if (l_img_comp->sgnd) { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } } else { for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (*(l_src_ptr++))&0xffff; } } p_src = (OPJ_BYTE*) l_src_ptr; } break; case 4: { OPJ_INT32 * l_src_ptr = (OPJ_INT32 *) p_src; OPJ_INT32 * l_dest_ptr = l_tilec->data; for (j=0;j<l_nb_elem;++j) { *(l_dest_ptr++) = (OPJ_INT32) (*(l_src_ptr++)); } p_src = (OPJ_BYTE*) l_src_ptr; } break; } ++l_img_comp; ++l_tilec; } return OPJ_TRUE; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_540_1
crossvul-cpp_data_bad_3983_3
/* * Copyright 2009-2012 10gen, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Portions Copyright 2001 Unicode, Inc. * * Disclaimer * * This source code is provided as is by Unicode, Inc. No claims are * made as to fitness for any particular purpose. No warranties of any * kind are expressed or implied. The recipient agrees to determine * applicability of information provided. If this file has been * purchased on magnetic or optical media from Unicode, Inc., the * sole remedy for any claim will be exchange of defective media * within 90 days of receipt. * * Limitations on Rights to Redistribute This Code * * Unicode, Inc. hereby grants the right to freely use the information * supplied in this file in the creation of products supporting the * Unicode Standard, and to make copies of this file in any form * for internal or external distribution as long as this notice * remains attached. */ #include "bson.h" #include "encoding.h" /* * 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. */ 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 }; /* --------------------------------------------------------------------- */ /* * 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. * 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 0. The Unicode * definition of UTF-8 goes up to 4-byte sequences. */ static int isLegalUTF8( const unsigned char *source, int length ) { unsigned char a; const unsigned char *srcptr = source + length; switch ( length ) { default: return 0; /* Everything else falls through when "true"... */ case 4: if ( ( a = ( *--srcptr ) ) < 0x80 || a > 0xBF ) return 0; case 3: if ( ( a = ( *--srcptr ) ) < 0x80 || a > 0xBF ) return 0; case 2: if ( ( a = ( *--srcptr ) ) > 0xBF ) return 0; switch ( *source ) { /* no fall-through in this inner switch */ case 0xE0: if ( a < 0xA0 ) return 0; break; case 0xF0: if ( a < 0x90 ) return 0; break; case 0xF4: if ( a > 0x8F ) return 0; break; default: if ( a < 0x80 ) return 0; } case 1: if ( *source >= 0x80 && *source < 0xC2 ) return 0; if ( *source > 0xF4 ) return 0; } return 1; } /* If the name is part of a db ref ($ref, $db, or $id), then return true. */ static int bson_string_is_db_ref( const unsigned char *string, const int length ) { int result = 0; if( length >= 4 ) { if( string[1] == 'r' && string[2] == 'e' && string[3] == 'f' ) result = 1; } else if( length >= 3 ) { if( string[1] == 'i' && string[2] == 'd' ) result = 1; else if( string[1] == 'd' && string[2] == 'b' ) result = 1; } return result; } static int bson_validate_string( bson *b, const unsigned char *string, const int length, const char check_utf8, const char check_dot, const char check_dollar ) { int position = 0; int sequence_length = 1; if( check_dollar && string[0] == '$' ) { if( !bson_string_is_db_ref( string, length ) ) b->err |= BSON_FIELD_INIT_DOLLAR; } while ( position < length ) { if ( check_dot && *( string + position ) == '.' ) { b->err |= BSON_FIELD_HAS_DOT; } if ( check_utf8 ) { sequence_length = trailingBytesForUTF8[*( string + position )] + 1; if ( ( position + sequence_length ) > length ) { b->err |= BSON_NOT_UTF8; return BSON_ERROR; } if ( !isLegalUTF8( string + position, sequence_length ) ) { b->err |= BSON_NOT_UTF8; return BSON_ERROR; } } position += sequence_length; } return BSON_OK; } int bson_check_string( bson *b, const char *string, const int length ) { return bson_validate_string( b, ( const unsigned char * )string, length, 1, 0, 0 ); } int bson_check_field_name( bson *b, const char *string, const int length ) { return bson_validate_string( b, ( const unsigned char * )string, length, 1, 1, 1 ); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3983_3
crossvul-cpp_data_bad_3221_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3221_0
crossvul-cpp_data_good_35_0
/** * miniSphere JavaScript game engine * Copyright (c) 2015-2018, Fat Cerberus * All rights reserved. * * 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 miniSphere 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 HOLDER 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. **/ #include "minisphere.h" #include "map_engine.h" #include "api.h" #include "audio.h" #include "color.h" #include "dispatch.h" #include "geometry.h" #include "image.h" #include "input.h" #include "jsal.h" #include "obstruction.h" #include "script.h" #include "spriteset.h" #include "tileset.h" #include "vanilla.h" #include "vector.h" static const person_t* s_acting_person; static mixer_t* s_bgm_mixer = NULL; static person_t* s_camera_person = NULL; static int s_camera_x = 0; static int s_camera_y = 0; static color_t s_color_mask; static const person_t* s_current_person = NULL; static int s_current_trigger = -1; static int s_current_zone = -1; static script_t* s_def_map_scripts[MAP_SCRIPT_MAX]; static script_t* s_def_person_scripts[PERSON_SCRIPT_MAX]; static bool s_exiting = false; static color_t s_fade_color_from; static color_t s_fade_color_to; static int s_fade_frames; static int s_fade_progress; static int s_frame_rate = 0; static unsigned int s_frames = 0; static bool s_is_map_running = false; static lstring_t* s_last_bgm_file = NULL; static struct map* s_map = NULL; static sound_t* s_map_bgm_stream = NULL; static char* s_map_filename = NULL; static int s_max_deferreds = 0; static int s_max_persons = 0; static unsigned int s_next_person_id = 0; static int s_num_deferreds = 0; static int s_num_persons = 0; static struct map_trigger* s_on_trigger = NULL; static unsigned int s_queued_id = 0; static vector_t* s_person_list = NULL; static struct player* s_players; static script_t* s_render_script = NULL; static int s_talk_button = 0; static int s_talk_distance = 8; static script_t* s_update_script = NULL; static struct deferred *s_deferreds = NULL; static person_t* *s_persons = NULL; struct deferred { script_t* script; int frames_left; }; struct map { int width, height; bool is_repeating; point3_t origin; lstring_t* bgm_file; script_t* scripts[MAP_SCRIPT_MAX]; tileset_t* tileset; vector_t* triggers; vector_t* zones; int num_layers; int num_persons; struct map_layer *layers; struct map_person *persons; }; struct map_layer { lstring_t* name; bool is_parallax; bool is_reflective; bool is_visible; float autoscroll_x; float autoscroll_y; color_t color_mask; int height; obsmap_t* obsmap; float parallax_x; float parallax_y; script_t* render_script; struct map_tile* tilemap; int width; }; struct map_person { lstring_t* name; lstring_t* spriteset; int x, y, z; lstring_t* create_script; lstring_t* destroy_script; lstring_t* command_script; lstring_t* talk_script; lstring_t* touch_script; }; struct map_tile { int tile_index; int frames_left; }; struct map_trigger { script_t* script; int x, y, z; }; struct map_zone { bool is_active; rect_t bounds; int interval; int steps_left; int layer; script_t* script; }; struct person { unsigned int id; char* name; int anim_frames; char* direction; int follow_distance; int frame; bool ignore_all_persons; bool ignore_all_tiles; vector_t* ignore_list; bool is_persistent; bool is_visible; int layer; person_t* leader; color_t mask; int mv_x, mv_y; int revert_delay; int revert_frames; double scale_x; double scale_y; script_t* scripts[PERSON_SCRIPT_MAX]; double speed_x, speed_y; spriteset_t* sprite; double theta; double x, y; int x_offset, y_offset; int max_commands; int max_history; int num_commands; int num_ignores; struct command *commands; char* *ignores; struct step *steps; }; struct step { double x, y; }; struct command { int type; bool is_immediate; script_t* script; }; struct player { bool is_talk_allowed; person_t* person; int talk_key; }; #pragma pack(push, 1) struct rmp_header { char signature[4]; int16_t version; uint8_t type; int8_t num_layers; uint8_t reserved_1; int16_t num_entities; int16_t start_x; int16_t start_y; int8_t start_layer; int8_t start_direction; int16_t num_strings; int16_t num_zones; uint8_t repeat_map; uint8_t reserved[234]; }; struct rmp_entity_header { uint16_t x; uint16_t y; uint16_t z; uint16_t type; uint8_t reserved[8]; }; struct rmp_layer_header { int16_t width; int16_t height; uint16_t flags; float parallax_x; float parallax_y; float scrolling_x; float scrolling_y; int32_t num_segments; uint8_t is_reflective; uint8_t reserved[3]; }; struct rmp_zone_header { uint16_t x1; uint16_t y1; uint16_t x2; uint16_t y2; uint16_t layer; uint16_t interval; uint8_t reserved[4]; }; #pragma pack(pop) static bool change_map (const char* filename, bool preserve_persons); static void command_person (person_t* person, int command); static int compare_persons (const void* a, const void* b); static void detach_person (const person_t* person); static bool does_person_exist (const person_t* person); static void draw_persons (int layer, bool is_flipped, int cam_x, int cam_y); static bool enlarge_step_history (person_t* person, int new_size); static void free_map (struct map* map); static void free_person (person_t* person); static struct map_trigger* get_trigger_at (int x, int y, int layer, int* out_index); static struct map_zone* get_zone_at (int x, int y, int layer, int which, int* out_index); static struct map* load_map (const char* path); static void map_screen_to_layer (int layer, int camera_x, int camera_y, int* inout_x, int* inout_y); static void map_screen_to_map (int camera_x, int camera_y, int* inout_x, int* inout_y); static void process_map_input (void); static void record_step (person_t* person); static void reset_persons (bool keep_existing); static void set_person_name (person_t* person, const char* name); static void sort_persons (void); static void update_map_engine (bool is_main_loop); static void update_person (person_t* person, bool* out_has_moved); void map_engine_init(void) { int i; console_log(1, "initializing map engine subsystem"); audio_init(); s_bgm_mixer = mixer_new(44100, 16, 2); memset(s_def_map_scripts, 0, MAP_SCRIPT_MAX * sizeof(int)); memset(s_def_person_scripts, 0, PERSON_SCRIPT_MAX * sizeof(int)); s_map = NULL; s_map_filename = NULL; s_camera_person = NULL; s_players = calloc(PLAYER_MAX, sizeof(struct player)); for (i = 0; i < PLAYER_MAX; ++i) s_players[i].is_talk_allowed = true; s_current_trigger = -1; s_current_zone = -1; s_render_script = NULL; s_update_script = NULL; s_num_deferreds = s_max_deferreds = 0; s_deferreds = NULL; s_talk_button = 0; s_is_map_running = false; s_color_mask = mk_color(0, 0, 0, 0); s_on_trigger = NULL; s_num_persons = s_max_persons = 0; s_persons = NULL; s_talk_distance = 8; s_acting_person = NULL; s_current_person = NULL; } void map_engine_uninit(void) { int i; console_log(1, "shutting down map engine subsystem"); vector_free(s_person_list); for (i = 0; i < s_num_deferreds; ++i) script_unref(s_deferreds[i].script); free(s_deferreds); for (i = 0; i < MAP_SCRIPT_MAX; ++i) script_unref(s_def_map_scripts[i]); script_unref(s_update_script); script_unref(s_render_script); free_map(s_map); free(s_players); for (i = 0; i < s_num_persons; ++i) free_person(s_persons[i]); for (i = 0; i < PERSON_SCRIPT_MAX; ++i) script_unref(s_def_person_scripts[i]); free(s_persons); mixer_unref(s_bgm_mixer); audio_uninit(); } void map_engine_on_map_event(map_op_t op, script_t* script) { script_t* old_script; old_script = s_def_map_scripts[op]; s_def_map_scripts[op] = script_ref(script); script_unref(old_script); } void map_engine_on_person_event(person_op_t op, script_t* script) { script_t* old_script; old_script = s_def_person_scripts[op]; s_def_person_scripts[op] = script_ref(script); script_unref(old_script); } void map_engine_on_render(script_t* script) { script_unref(s_render_script); s_render_script = script_ref(script); } void map_engine_on_update(script_t* script) { script_unref(s_update_script); s_update_script = script_ref(script); } const person_t* map_engine_acting_person(void) { return s_acting_person; } const person_t* map_engine_active_person(void) { return s_current_person; } int map_engine_active_trigger(void) { return s_current_trigger; } int map_engine_active_zone(void) { return s_current_zone; } vector_t* map_engine_persons(void) { int i; if (s_person_list == NULL) s_person_list = vector_new(sizeof(person_t*)); vector_clear(s_person_list); for (i = 0; i < s_num_persons; ++i) vector_push(s_person_list, &s_persons[i]); return s_person_list; } bool map_engine_running(void) { return s_is_map_running; } int map_engine_get_framerate(void) { return s_frame_rate; } person_t* map_engine_get_player(player_id_t player_id) { return s_players[player_id].person; } person_t* map_engine_get_subject(void) { return s_camera_person; } int map_engine_get_talk_button(void) { return s_talk_button; } int map_engine_get_talk_distance(void) { return s_talk_distance; } int map_engine_get_talk_key(player_id_t player_id) { return s_players[player_id].talk_key; } void map_engine_set_framerate(int framerate) { s_frame_rate = framerate; } void map_engine_set_player(player_id_t player_id, person_t* person) { int i; // detach person from any other players for (i = 0; i < PLAYER_MAX; ++i) { if (s_players[i].person == person) s_players[i].person = NULL; } s_players[player_id].person = person; } void map_engine_set_subject(person_t* person) { s_camera_person = person; } void map_engine_set_talk_button(int button_id) { s_talk_button = button_id; } void map_engine_set_talk_distance(int distance) { s_talk_distance = distance; } void map_engine_set_talk_key(player_id_t player_id, int key) { s_players[player_id].talk_key = key; } bool map_engine_change_map(const char* filename) { return change_map(filename, false); } void map_engine_defer(script_t* script, int num_frames) { struct deferred* deferred; if (++s_num_deferreds > s_max_deferreds) { s_max_deferreds = s_num_deferreds * 2; s_deferreds = realloc(s_deferreds, s_max_deferreds * sizeof(struct deferred)); } deferred = &s_deferreds[s_num_deferreds - 1]; deferred->script = script; deferred->frames_left = num_frames; } void map_engine_draw_map(void) { bool is_repeating; int cell_x; int cell_y; int first_cell_x; int first_cell_y; struct map_layer* layer; int layer_height; int layer_width; size2_t resolution; int tile_height; int tile_index; int tile_width; int off_x; int off_y; int x, y, z; if (screen_skipping_frame(g_screen)) return; resolution = screen_size(g_screen); tileset_get_size(s_map->tileset, &tile_width, &tile_height); // render map layers from bottom to top (+Z = up) for (z = 0; z < s_map->num_layers; ++z) { layer = &s_map->layers[z]; is_repeating = s_map->is_repeating || layer->is_parallax; layer_width = layer->width * tile_width; layer_height = layer->height * tile_height; off_x = 0; off_y = 0; map_screen_to_layer(z, s_camera_x, s_camera_y, &off_x, &off_y); // render person reflections if layer is reflective al_hold_bitmap_drawing(true); if (layer->is_reflective) { if (is_repeating) { // for small repeating maps, persons need to be repeated as well for (y = 0; y < resolution.height / layer_height + 2; ++y) for (x = 0; x < resolution.width / layer_width + 2; ++x) draw_persons(z, true, off_x - x * layer_width, off_y - y * layer_height); } else { draw_persons(z, true, off_x, off_y); } } // render tiles, but only if the layer is visible if (layer->is_visible) { first_cell_x = off_x / tile_width; first_cell_y = off_y / tile_height; for (y = 0; y < resolution.height / tile_height + 2; ++y) for (x = 0; x < resolution.width / tile_width + 2; ++x) { cell_x = is_repeating ? (x + first_cell_x) % layer->width : x + first_cell_x; cell_y = is_repeating ? (y + first_cell_y) % layer->height : y + first_cell_y; if (cell_x < 0 || cell_x >= layer->width || cell_y < 0 || cell_y >= layer->height) continue; tile_index = layer->tilemap[cell_x + cell_y * layer->width].tile_index; tileset_draw(s_map->tileset, layer->color_mask, x * tile_width - off_x % tile_width, y * tile_height - off_y % tile_height, tile_index); } } // render persons if (is_repeating) { // for small repeating maps, persons need to be repeated as well for (y = 0; y < resolution.height / layer_height + 2; ++y) for (x = 0; x < resolution.width / layer_width + 2; ++x) draw_persons(z, false, off_x - x * layer_width, off_y - y * layer_height); } else { draw_persons(z, false, off_x, off_y); } al_hold_bitmap_drawing(false); script_run(layer->render_script, false); } al_draw_filled_rectangle(0, 0, resolution.width, resolution.height, nativecolor(s_color_mask)); script_run(s_render_script, false); } void map_engine_exit(void) { s_exiting = true; } void map_engine_fade_to(color_t color_mask, int num_frames) { if (num_frames > 0) { s_fade_color_to = color_mask; s_fade_color_from = s_color_mask; s_fade_frames = num_frames; s_fade_progress = 0; } else { s_color_mask = color_mask; s_fade_color_to = s_fade_color_from = color_mask; s_fade_progress = s_fade_frames = 0; } } bool map_engine_start(const char* filename, int framerate) { s_is_map_running = true; s_exiting = false; s_color_mask = mk_color(0, 0, 0, 0); s_fade_color_to = s_fade_color_from = s_color_mask; s_fade_progress = s_fade_frames = 0; al_clear_to_color(al_map_rgba(0, 0, 0, 255)); s_frame_rate = framerate; if (!change_map(filename, true)) goto on_error; while (!s_exiting && jsal_vm_enabled()) { sphere_heartbeat(true, 1); // order of operations matches Sphere 1.x. not sure why, but Sphere 1.x // checks for input AFTER an update for some reason... update_map_engine(true); process_map_input(); map_engine_draw_map(); // don't clear the backbuffer. the Sphere 1.x map engine has a bug where it doesn't // clear the backbuffer between frames; as it turns out, a good deal of of v1 code relies // on that behavior. sphere_tick(1, false, s_frame_rate); } reset_persons(false); s_is_map_running = false; return true; on_error: s_is_map_running = false; return false; } void map_engine_update(void) { update_map_engine(false); } rect_t map_bounds(void) { rect_t bounds; int tile_w, tile_h; tileset_get_size(s_map->tileset, &tile_w, &tile_h); bounds.x1 = 0; bounds.y1 = 0; bounds.x2 = s_map->width * tile_w; bounds.y2 = s_map->height * tile_h; return bounds; } int map_layer_by_name(const char* name) { int i; for (i = 0; i < s_map->num_layers; ++i) { if (strcmp(name, lstr_cstr(s_map->layers[0].name)) == 0) return i; } return -1; } int map_num_layers(void) { return s_map->num_layers; } int map_num_persons(void) { return s_num_persons; } int map_num_triggers(void) { return vector_len(s_map->triggers); } int map_num_zones(void) { return vector_len(s_map->zones); } point3_t map_origin(void) { return s_map != NULL ? s_map->origin : mk_point3(0, 0, 0); } const char* map_pathname(void) { return s_map ? s_map_filename : NULL; } person_t* map_person_by_name(const char* name) { int i; for (i = 0; i < s_num_persons; ++i) { if (strcmp(name, s_persons[i]->name) == 0) return s_persons[i]; } return NULL; } int map_tile_at(int x, int y, int layer) { int layer_h; int layer_w; layer_w = s_map->layers[layer].width; layer_h = s_map->layers[layer].height; if (s_map->is_repeating || s_map->layers[layer].is_parallax) { x = (x % layer_w + layer_w) % layer_w; y = (y % layer_h + layer_h) % layer_h; } if (x < 0 || y < 0 || x >= layer_w || y >= layer_h) return -1; return layer_get_tile(layer, x, y); } tileset_t* map_tileset(void) { return s_map->tileset; } int map_trigger_at(int x, int y, int layer) { rect_t bounds; int tile_w, tile_h; struct map_trigger* trigger; iter_t iter; tileset_get_size(s_map->tileset, &tile_w, &tile_h); iter = vector_enum(s_map->triggers); while ((trigger = iter_next(&iter))) { if (trigger->z != layer && false) // layer ignored for compatibility continue; bounds.x1 = trigger->x - tile_w / 2; bounds.y1 = trigger->y - tile_h / 2; bounds.x2 = bounds.x1 + tile_w; bounds.y2 = bounds.y1 + tile_h; if (is_point_in_rect(x, y, bounds)) return iter.index; } return -1; } point2_t map_xy_from_screen(point2_t screen_xy) { int x; int y; x = screen_xy.x; y = screen_xy.y; map_screen_to_map(s_camera_x, s_camera_y, &x, &y); return mk_point2(x, y); } int map_zone_at(int x, int y, int layer, int which) { struct map_zone* zone; iter_t iter; iter = vector_enum(s_map->zones); while ((zone = iter_next(&iter))) { if (zone->layer != layer && false) // layer ignored for compatibility continue; if (is_point_in_rect(x, y, zone->bounds) && --which < 0) return iter.index; } return -1; } point2_t map_get_camera_xy(void) { return mk_point2(s_camera_x, s_camera_y); } void map_set_camera_xy(point2_t where) { s_camera_x = where.x; s_camera_y = where.y; } void map_activate(map_op_t op, bool use_default) { if (use_default) script_run(s_def_map_scripts[op], false); script_run(s_map->scripts[op], false); } bool map_add_trigger(int x, int y, int layer, script_t* script) { struct map_trigger trigger; console_log(2, "creating trigger #%d on map '%s'", vector_len(s_map->triggers), s_map_filename); console_log(3, " location: '%s' @ (%d,%d)", lstr_cstr(s_map->layers[layer].name), x, y); trigger.x = x; trigger.y = y; trigger.z = layer; trigger.script = script_ref(script); if (!vector_push(s_map->triggers, &trigger)) return false; return true; } bool map_add_zone(rect_t bounds, int layer, script_t* script, int steps) { struct map_zone zone; console_log(2, "creating %u-step zone #%d on map '%s'", steps, vector_len(s_map->zones), s_map_filename); console_log(3, " bounds: (%d,%d)-(%d,%d)", bounds.x1, bounds.y1, bounds.x2, bounds.y2); memset(&zone, 0, sizeof(struct map_zone)); zone.bounds = bounds; zone.layer = layer; zone.script = script_ref(script); zone.interval = steps; zone.steps_left = 0; if (!vector_push(s_map->zones, &zone)) return false; return true; } void map_call_default(map_op_t op) { script_run(s_def_map_scripts[op], false); } void map_normalize_xy(double* inout_x, double* inout_y, int layer) { int tile_w, tile_h; int layer_w, layer_h; if (s_map == NULL) return; // can't normalize if no map loaded if (!s_map->is_repeating && !s_map->layers[layer].is_parallax) return; tileset_get_size(s_map->tileset, &tile_w, &tile_h); layer_w = s_map->layers[layer].width * tile_w; layer_h = s_map->layers[layer].height * tile_h; if (inout_x) *inout_x = fmod(fmod(*inout_x, layer_w) + layer_w, layer_w); if (inout_y) *inout_y = fmod(fmod(*inout_y, layer_h) + layer_h, layer_h); } void map_remove_trigger(int trigger_index) { vector_remove(s_map->triggers, trigger_index); } void map_remove_zone(int zone_index) { vector_remove(s_map->zones, zone_index); } void layer_on_render(int layer, script_t* script) { script_unref(s_map->layers[layer].render_script); s_map->layers[layer].render_script = script_ref(script); } const char* layer_name(int layer) { return lstr_cstr(s_map->layers[layer].name); } const obsmap_t* layer_obsmap(int layer) { return s_map->layers[layer].obsmap; } size2_t layer_size(int layer) { struct map_layer* layer_data; layer_data = &s_map->layers[layer]; return mk_size2(layer_data->width, layer_data->height); } color_t layer_get_color_mask(int layer) { return s_map->layers[layer].color_mask; } bool layer_get_reflective(int layer) { return s_map->layers[layer].is_reflective; } int layer_get_tile(int layer, int x, int y) { struct map_tile* tile; int width; width = s_map->layers[layer].width; tile = &s_map->layers[layer].tilemap[x + y * width]; return tile->tile_index; } bool layer_get_visible(int layer) { return s_map->layers[layer].is_visible; } void layer_set_color_mask(int layer, color_t color) { s_map->layers[layer].color_mask = color; } void layer_set_reflective(int layer, bool reflective) { s_map->layers[layer].is_reflective = reflective; } void layer_set_tile(int layer, int x, int y, int tile_index) { struct map_tile* tile; int width; width = s_map->layers[layer].width; tile = &s_map->layers[layer].tilemap[x + y * width]; tile->tile_index = tile_index; tile->frames_left = tileset_get_delay(s_map->tileset, tile_index); } void layer_set_visible(int layer, bool visible) { s_map->layers[layer].is_visible = visible; } void layer_replace_tiles(int layer, int old_index, int new_index) { int layer_h; int layer_w; struct map_tile* tile; int i_x, i_y; layer_w = s_map->layers[layer].width; layer_h = s_map->layers[layer].height; for (i_x = 0; i_x < layer_w; ++i_x) for (i_y = 0; i_y < layer_h; ++i_y) { tile = &s_map->layers[layer].tilemap[i_x + i_y * layer_w]; if (tile->tile_index == old_index) tile->tile_index = new_index; } } bool layer_resize(int layer, int x_size, int y_size) { int old_height; int old_width; struct map_tile* tile; int tile_width; int tile_height; struct map_tile* tilemap; struct map_trigger* trigger; struct map_zone* zone; size_t tilemap_size; int x, y, i; old_width = s_map->layers[layer].width; old_height = s_map->layers[layer].height; // allocate a new tilemap and copy the old layer tiles into it. we can't simply realloc // because the tilemap is a 2D array. tilemap_size = x_size * y_size * sizeof(struct map_tile); if (x_size == 0 || tilemap_size / x_size / sizeof(struct map_tile) != y_size || !(tilemap = malloc(tilemap_size))) return false; for (x = 0; x < x_size; ++x) { for (y = 0; y < y_size; ++y) { if (x < old_width && y < old_height) { tilemap[x + y * x_size] = s_map->layers[layer].tilemap[x + y * old_width]; } else { tile = &tilemap[x + y * x_size]; tile->frames_left = tileset_get_delay(s_map->tileset, 0); tile->tile_index = 0; } } } // free the old tilemap and substitute the new one free(s_map->layers[layer].tilemap); s_map->layers[layer].tilemap = tilemap; s_map->layers[layer].width = x_size; s_map->layers[layer].height = y_size; // if we resize the largest layer, the overall map size will change. // recalcuate it. tileset_get_size(s_map->tileset, &tile_width, &tile_height); s_map->width = 0; s_map->height = 0; for (i = 0; i < s_map->num_layers; ++i) { if (!s_map->layers[i].is_parallax) { s_map->width = fmax(s_map->width, s_map->layers[i].width * tile_width); s_map->height = fmax(s_map->height, s_map->layers[i].height * tile_height); } } // ensure zones and triggers remain in-bounds. if any are completely // out-of-bounds, delete them. for (i = (int)vector_len(s_map->zones) - 1; i >= 0; --i) { zone = vector_get(s_map->zones, i); if (zone->bounds.x1 >= s_map->width || zone->bounds.y1 >= s_map->height) vector_remove(s_map->zones, i); else { if (zone->bounds.x2 > s_map->width) zone->bounds.x2 = s_map->width; if (zone->bounds.y2 > s_map->height) zone->bounds.y2 = s_map->height; } } for (i = (int)vector_len(s_map->triggers) - 1; i >= 0; --i) { trigger = vector_get(s_map->triggers, i); if (trigger->x >= s_map->width || trigger->y >= s_map->height) vector_remove(s_map->triggers, i); } return true; } person_t* person_new(const char* name, spriteset_t* spriteset, bool is_persistent, script_t* create_script) { point3_t origin = map_origin(); person_t* person; if (++s_num_persons > s_max_persons) { s_max_persons = s_num_persons * 2; s_persons = realloc(s_persons, s_max_persons * sizeof(person_t*)); } person = s_persons[s_num_persons - 1] = calloc(1, sizeof(person_t)); person->id = s_next_person_id++; person->sprite = spriteset_ref(spriteset); set_person_name(person, name); person_set_pose(person, spriteset_pose_name(spriteset, 0)); person->is_persistent = is_persistent; person->is_visible = true; person->x = origin.x; person->y = origin.y; person->layer = origin.z; person->speed_x = 1.0; person->speed_y = 1.0; person->anim_frames = spriteset_frame_delay(person->sprite, person->direction, 0); person->mask = mk_color(255, 255, 255, 255); person->scale_x = person->scale_y = 1.0; person->scripts[PERSON_SCRIPT_ON_CREATE] = create_script; person_activate(person, PERSON_SCRIPT_ON_CREATE, NULL, true); sort_persons(); return person; } void person_free(person_t* person) { int i, j; // call the person's destroy script *before* renouncing leadership. // the destroy script may want to reassign followers (they will be orphaned otherwise), so // we want to give it a chance to do so. person_activate(person, PERSON_SCRIPT_ON_DESTROY, NULL, true); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader == person) s_persons[i]->leader = NULL; } // remove the person from the engine detach_person(person); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i] == person) { for (j = i; j < s_num_persons - 1; ++j) s_persons[j] = s_persons[j + 1]; --s_num_persons; --i; } } vector_free(person->ignore_list); free_person(person); sort_persons(); } rect_t person_base(const person_t* person) { rect_t base_rect; int base_x; int base_y; double x; double y; base_rect = rect_zoom(spriteset_get_base(person->sprite), person->scale_x, person->scale_y); person_get_xy(person, &x, &y, true); base_x = x - (base_rect.x1 + (base_rect.x2 - base_rect.x1) / 2); base_y = y - (base_rect.y1 + (base_rect.y2 - base_rect.y1) / 2); base_rect.x1 += base_x; base_rect.x2 += base_x; base_rect.y1 += base_y; base_rect.y2 += base_y; return base_rect; } bool person_following(const person_t* person, const person_t* leader) { const person_t* node; node = person; while ((node = node->leader)) if (node == leader) return true; return false; } bool person_has_moved(const person_t* person) { return person->mv_x != 0 || person->mv_y != 0; } vector_t* person_ignore_list(person_t* person) { // note: the returned vector is an array of C strings. these should be treated // as const char*; in other words, don't free them! int i; if (person->ignore_list == NULL) person->ignore_list = vector_new(sizeof(const char*)); vector_clear(person->ignore_list); for (i = 0; i < person->num_ignores; ++i) vector_push(person->ignore_list, &person->ignores[i]); return person->ignore_list; } bool person_ignored_by(const person_t* person, const person_t* other) { // note: commutative; if either person ignores the other, the function will return true int i; if (other->ignore_all_persons || person->ignore_all_persons) return true; for (i = 0; i < other->num_ignores; ++i) if (strcmp(other->ignores[i], person->name) == 0) return true; for (i = 0; i < person->num_ignores; ++i) if (strcmp(person->ignores[i], other->name) == 0) return true; return false; } bool person_moving(const person_t* person) { return person->num_commands > 0; } const char* person_name(const person_t* person) { return person != NULL ? person->name : ""; } bool person_obstructed_at(const person_t* person, double x, double y, person_t** out_obstructing_person, int* out_tile_index) { rect_t area; rect_t base, my_base; double cur_x, cur_y; bool is_obstructed = false; int layer; const obsmap_t* obsmap; int tile_w, tile_h; const tileset_t* tileset; int i, i_x, i_y; map_normalize_xy(&x, &y, person->layer); person_get_xyz(person, &cur_x, &cur_y, &layer, true); my_base = rect_translate(person_base(person), x - cur_x, y - cur_y); if (out_obstructing_person != NULL) *out_obstructing_person = NULL; if (out_tile_index != NULL) *out_tile_index = -1; // check for obstructing persons if (!person->ignore_all_persons) { for (i = 0; i < s_num_persons; ++i) { if (s_persons[i] == person) // these persons aren't going to obstruct themselves! continue; if (s_persons[i]->layer != layer) continue; // ignore persons not on the same layer if (person_following(s_persons[i], person)) continue; // ignore own followers base = person_base(s_persons[i]); if (do_rects_overlap(my_base, base) && !person_ignored_by(person, s_persons[i])) { is_obstructed = true; if (out_obstructing_person) *out_obstructing_person = s_persons[i]; break; } } } // no obstructing person, check map-defined obstructions obsmap = layer_obsmap(layer); if (obsmap_test_rect(obsmap, my_base)) is_obstructed = true; // check for obstructing tiles // for performance reasons, the search is constrained to the immediate vicinity // of the person's sprite base. if (!person->ignore_all_tiles) { tileset = map_tileset(); tileset_get_size(tileset, &tile_w, &tile_h); area.x1 = my_base.x1 / tile_w; area.y1 = my_base.y1 / tile_h; area.x2 = area.x1 + (my_base.x2 - my_base.x1) / tile_w + 2; area.y2 = area.y1 + (my_base.y2 - my_base.y1) / tile_h + 2; for (i_x = area.x1; i_x < area.x2; ++i_x) for (i_y = area.y1; i_y < area.y2; ++i_y) { base = rect_translate(my_base, -(i_x * tile_w), -(i_y * tile_h)); obsmap = tileset_obsmap(tileset, map_tile_at(i_x, i_y, layer)); if (obsmap != NULL && obsmap_test_rect(obsmap, base)) { is_obstructed = true; if (out_tile_index) *out_tile_index = map_tile_at(i_x, i_y, layer); break; } } } return is_obstructed; } double person_get_angle(const person_t* person) { return person->theta; } color_t person_get_color(const person_t* person) { return person->mask; } int person_get_frame(const person_t* person) { int num_frames; num_frames = spriteset_num_frames(person->sprite, person->direction); return person->frame % num_frames; } int person_get_frame_delay(const person_t* person) { return person->anim_frames; } bool person_get_ignore_persons(const person_t* person) { return person->ignore_all_persons; } bool person_get_ignore_tiles(const person_t* person) { return person->ignore_all_tiles; } int person_get_layer(const person_t* person) { return person->layer; } person_t* person_get_leader(const person_t* person) { return person->leader; } point2_t person_get_offset(const person_t* person) { return mk_point2(person->x_offset, person->y_offset); } const char* person_get_pose(const person_t* person) { return person->direction; } int person_get_revert_delay(const person_t* person) { return person->revert_delay; } void person_get_scale(const person_t* person, double* out_scale_x, double* out_scale_y) { *out_scale_x = person->scale_x; *out_scale_y = person->scale_y; } void person_get_speed(const person_t* person, double* out_x_speed, double* out_y_speed) { if (out_x_speed) *out_x_speed = person->speed_x; if (out_y_speed) *out_y_speed = person->speed_y; } spriteset_t* person_get_spriteset(const person_t* person) { return person->sprite; } int person_get_trailing(const person_t* person) { return person->follow_distance; } bool person_get_visible(const person_t* person) { return person->is_visible; } void person_get_xy(const person_t* person, double* out_x, double* out_y, bool normalize) { *out_x = person->x; *out_y = person->y; if (normalize) map_normalize_xy(out_x, out_y, person->layer); } void person_get_xyz(const person_t* person, double* out_x, double* out_y, int* out_layer, bool normalize) { *out_x = person->x; *out_y = person->y; *out_layer = person->layer; if (normalize) map_normalize_xy(out_x, out_y, *out_layer); } void person_set_angle(person_t* person, double theta) { person->theta = theta; } void person_set_color(person_t* person, color_t mask) { person->mask = mask; } void person_set_frame(person_t* person, int frame_index) { int num_frames; num_frames = spriteset_num_frames(person->sprite, person->direction); person->frame = (frame_index % num_frames + num_frames) % num_frames; person->anim_frames = spriteset_frame_delay(person->sprite, person->direction, person->frame); person->revert_frames = person->revert_delay; } void person_set_frame_delay(person_t* person, int num_frames) { person->anim_frames = num_frames; person->revert_frames = person->revert_delay; } void person_set_ignore_persons(person_t* person, bool ignoring) { person->ignore_all_persons = ignoring; } void person_set_ignore_tiles (person_t* person, bool ignoring) { person->ignore_all_tiles = ignoring; } void person_set_layer(person_t* person, int layer) { person->layer = layer; } bool person_set_leader(person_t* person, person_t* leader, int distance) { const person_t* node; // prevent circular follower chains from forming if (leader != NULL) { node = leader; do { if (node == person) return false; } while ((node = node->leader)); } // add the person as a follower (or sever existing link if leader==NULL) if (leader != NULL) { if (!enlarge_step_history(leader, distance)) return false; person->leader = leader; person->follow_distance = distance; } person->leader = leader; return true; } void person_set_offset(person_t* person, point2_t offset) { person->x_offset = offset.x; person->y_offset = offset.y; } void person_set_pose(person_t* person, const char* pose_name) { person->direction = realloc(person->direction, (strlen(pose_name) + 1) * sizeof(char)); strcpy(person->direction, pose_name); } void person_set_revert_delay(person_t* person, int num_frames) { person->revert_delay = num_frames; person->revert_frames = num_frames; } void person_set_scale(person_t* person, double scale_x, double scale_y) { person->scale_x = scale_x; person->scale_y = scale_y; } void person_set_speed(person_t* person, double x_speed, double y_speed) { person->speed_x = x_speed; person->speed_y = y_speed; } void person_set_spriteset(person_t* person, spriteset_t* spriteset) { spriteset_t* old_spriteset; old_spriteset = person->sprite; person->sprite = spriteset_ref(spriteset); person->anim_frames = spriteset_frame_delay(person->sprite, person->direction, 0); person->frame = 0; spriteset_unref(old_spriteset); } void person_set_trailing(person_t* person, int distance) { enlarge_step_history(person->leader, distance); person->follow_distance = distance; } void person_set_visible(person_t* person, bool visible) { person->is_visible = visible; } void person_set_xyz(person_t* person, double x, double y, int layer) { person->x = x; person->y = y; person->layer = layer; sort_persons(); } void person_on_event(person_t* person, int type, script_t* script) { script_unref(person->scripts[type]); person->scripts[type] = script; } void person_activate(const person_t* person, person_op_t op, const person_t* acting_person, bool use_default) { const person_t* last_acting; const person_t* last_current; last_acting = s_acting_person; last_current = s_current_person; s_acting_person = acting_person; s_current_person = person; if (use_default) script_run(s_def_person_scripts[op], false); if (does_person_exist(person)) script_run(person->scripts[op], false); s_acting_person = last_acting; s_current_person = last_current; } void person_call_default(const person_t* person, person_op_t op, const person_t* acting_person) { const person_t* last_acting; const person_t* last_current; last_acting = s_acting_person; last_current = s_current_person; s_acting_person = acting_person; s_current_person = person; script_run(s_def_person_scripts[op], false); s_acting_person = last_acting; s_current_person = last_current; } void person_clear_ignores(person_t* person) { int i; for (i = 0; i < person->num_ignores; ++i) free(person->ignores[i]); person->num_ignores = 0; } void person_clear_queue(person_t* person) { person->num_commands = 0; } bool person_compile_script(person_t* person, int type, const lstring_t* codestring) { script_t* script; const char* script_name; script_name = type == PERSON_SCRIPT_ON_CREATE ? "onCreate" : type == PERSON_SCRIPT_ON_DESTROY ? "onDestroy" : type == PERSON_SCRIPT_ON_TOUCH ? "onTouch" : type == PERSON_SCRIPT_ON_TALK ? "onTalk" : type == PERSON_SCRIPT_GENERATOR ? "genCommands" : NULL; if (script_name == NULL) return false; script = script_new(codestring, "%s/%s/%s.js", map_pathname(), person->name, script_name); person_on_event(person, type, script); return true; } void person_ignore_name(person_t* person, const char* name) { int index; index = person->num_ignores++; person->ignores = realloc(person->ignores, person->num_ignores * sizeof(char*)); person->ignores[index] = strdup(name); // ignore list changed, delete cache vector_free(person->ignore_list); person->ignore_list = NULL; } bool person_queue_command(person_t* person, int command, bool is_immediate) { struct command* commands; bool is_aok = true; switch (command) { case COMMAND_MOVE_NORTHEAST: is_aok &= person_queue_command(person, COMMAND_MOVE_NORTH, true); is_aok &= person_queue_command(person, COMMAND_MOVE_EAST, is_immediate); return is_aok; case COMMAND_MOVE_SOUTHEAST: is_aok &= person_queue_command(person, COMMAND_MOVE_SOUTH, true); is_aok &= person_queue_command(person, COMMAND_MOVE_EAST, is_immediate); return is_aok; case COMMAND_MOVE_SOUTHWEST: is_aok &= person_queue_command(person, COMMAND_MOVE_SOUTH, true); is_aok &= person_queue_command(person, COMMAND_MOVE_WEST, is_immediate); return is_aok; case COMMAND_MOVE_NORTHWEST: is_aok &= person_queue_command(person, COMMAND_MOVE_NORTH, true); is_aok &= person_queue_command(person, COMMAND_MOVE_WEST, is_immediate); return is_aok; default: ++person->num_commands; if (person->num_commands > person->max_commands) { if (!(commands = realloc(person->commands, person->num_commands * 2 * sizeof(struct command)))) return false; person->max_commands = person->num_commands * 2; person->commands = commands; } person->commands[person->num_commands - 1].type = command; person->commands[person->num_commands - 1].is_immediate = is_immediate; person->commands[person->num_commands - 1].script = NULL; return true; } } bool person_queue_script(person_t* person, script_t* script, bool is_immediate) { ++person->num_commands; if (person->num_commands > person->max_commands) { person->max_commands = person->num_commands * 2; if (!(person->commands = realloc(person->commands, person->max_commands * sizeof(struct command)))) return false; } person->commands[person->num_commands - 1].type = COMMAND_RUN_SCRIPT; person->commands[person->num_commands - 1].is_immediate = is_immediate; person->commands[person->num_commands - 1].script = script; return true; } void person_talk(const person_t* person) { rect_t map_rect; person_t* target_person; double talk_x, talk_y; map_rect = map_bounds(); // check if anyone else is within earshot person_get_xy(person, &talk_x, &talk_y, true); if (strstr(person->direction, "north")) talk_y -= s_talk_distance; if (strstr(person->direction, "east")) talk_x += s_talk_distance; if (strstr(person->direction, "south")) talk_y += s_talk_distance; if (strstr(person->direction, "west")) talk_x -= s_talk_distance; person_obstructed_at(person, talk_x, talk_y, &target_person, NULL); // if so, call their talk script if (target_person != NULL) person_activate(target_person, PERSON_SCRIPT_ON_TALK, person, true); } void trigger_get_xyz(int trigger_index, int* out_x, int* out_y, int* out_layer) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); if (out_x != NULL) *out_x = trigger->x; if (out_y != NULL) *out_y = trigger->y; if (out_layer) *out_layer = trigger->z; } void trigger_set_layer(int trigger_index, int layer) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); trigger->z = layer; } void trigger_set_script(int trigger_index, script_t* script) { script_t* old_script; struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); old_script = trigger->script; trigger->script = script_ref(script); script_unref(old_script); } void trigger_set_xy(int trigger_index, int x, int y) { struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); trigger->x = x; trigger->y = y; } void trigger_activate(int trigger_index) { int last_trigger; struct map_trigger* trigger; trigger = vector_get(s_map->triggers, trigger_index); last_trigger = s_current_trigger; s_current_trigger = trigger_index; script_run(trigger->script, true); s_current_trigger = last_trigger; } rect_t zone_get_bounds(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->bounds; } int zone_get_layer(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->layer; } int zone_get_steps(int zone_index) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); return zone->interval; } void zone_set_bounds(int zone_index, rect_t bounds) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); rect_normalize(&bounds); zone->bounds = bounds; } void zone_set_layer(int zone_index, int layer) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); zone->layer = layer; } void zone_set_script(int zone_index, script_t* script) { script_t* old_script; struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); old_script = zone->script; zone->script = script_ref(script); script_unref(old_script); } void zone_set_steps(int zone_index, int interval) { struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); zone->interval = interval; zone->steps_left = 0; } void zone_activate(int zone_index) { int last_zone; struct map_zone* zone; zone = vector_get(s_map->zones, zone_index); last_zone = s_current_zone; s_current_zone = zone_index; script_run(zone->script, true); s_current_zone = last_zone; } static bool change_map(const char* filename, bool preserve_persons) { // note: if an error is detected during a map change, change_map() will return false, but // the map engine may be left in an inconsistent state. it is therefore probably wise // to consider such a situation unrecoverable. struct map* map; person_t* person; struct map_person* person_info; path_t* path; spriteset_t* spriteset = NULL; int i; console_log(2, "changing current map to '%s'", filename); map = load_map(filename); if (map == NULL) return false; if (s_map != NULL) { // run map exit scripts first, before loading new map map_activate(MAP_SCRIPT_ON_LEAVE, true); } // close out old map and prep for new one free_map(s_map); free(s_map_filename); for (i = 0; i < s_num_deferreds; ++i) script_unref(s_deferreds[i].script); s_num_deferreds = 0; s_map = map; s_map_filename = strdup(filename); reset_persons(preserve_persons); // populate persons for (i = 0; i < s_map->num_persons; ++i) { person_info = &s_map->persons[i]; path = game_full_path(g_game, lstr_cstr(person_info->spriteset), "spritesets", true); spriteset = spriteset_load(path_cstr(path)); path_free(path); if (spriteset == NULL) goto on_error; if (!(person = person_new(lstr_cstr(person_info->name), spriteset, false, NULL))) goto on_error; spriteset_unref(spriteset); person_set_xyz(person, person_info->x, person_info->y, person_info->z); person_compile_script(person, PERSON_SCRIPT_ON_CREATE, person_info->create_script); person_compile_script(person, PERSON_SCRIPT_ON_DESTROY, person_info->destroy_script); person_compile_script(person, PERSON_SCRIPT_ON_TOUCH, person_info->touch_script); person_compile_script(person, PERSON_SCRIPT_ON_TALK, person_info->talk_script); person_compile_script(person, PERSON_SCRIPT_GENERATOR, person_info->command_script); // normally this is handled by person_new(), but since in this case the // person-specific create script isn't compiled until after the person is created, // the map engine gets the responsibility. person_activate(person, PERSON_SCRIPT_ON_CREATE, NULL, false); } // set camera over starting position s_camera_x = s_map->origin.x; s_camera_y = s_map->origin.y; // start up map BGM (if same as previous, leave alone) if (s_map->bgm_file == NULL && s_map_bgm_stream != NULL) { sound_unref(s_map_bgm_stream); lstr_free(s_last_bgm_file); s_map_bgm_stream = NULL; s_last_bgm_file = NULL; } else if (s_map->bgm_file != NULL && (s_last_bgm_file == NULL || lstr_cmp(s_map->bgm_file, s_last_bgm_file) != 0)) { sound_unref(s_map_bgm_stream); lstr_free(s_last_bgm_file); s_last_bgm_file = lstr_dup(s_map->bgm_file); path = game_full_path(g_game, lstr_cstr(s_map->bgm_file), "sounds", true); if ((s_map_bgm_stream = sound_new(path_cstr(path)))) { sound_set_repeat(s_map_bgm_stream, true); sound_play(s_map_bgm_stream, s_bgm_mixer); } path_free(path); } // run map entry scripts map_activate(MAP_SCRIPT_ON_ENTER, true); s_frames = 0; return true; on_error: spriteset_unref(spriteset); free_map(s_map); return false; } static void command_person(person_t* person, int command) { double new_x; double new_y; person_t* person_to_touch; new_x = person->x; new_y = person->y; switch (command) { case COMMAND_ANIMATE: person->revert_frames = person->revert_delay; if (person->anim_frames > 0 && --person->anim_frames == 0) { ++person->frame; person->anim_frames = spriteset_frame_delay(person->sprite, person->direction, person->frame); } break; case COMMAND_FACE_NORTH: person_set_pose(person, "north"); break; case COMMAND_FACE_NORTHEAST: person_set_pose(person, "northeast"); break; case COMMAND_FACE_EAST: person_set_pose(person, "east"); break; case COMMAND_FACE_SOUTHEAST: person_set_pose(person, "southeast"); break; case COMMAND_FACE_SOUTH: person_set_pose(person, "south"); break; case COMMAND_FACE_SOUTHWEST: person_set_pose(person, "southwest"); break; case COMMAND_FACE_WEST: person_set_pose(person, "west"); break; case COMMAND_FACE_NORTHWEST: person_set_pose(person, "northwest"); break; case COMMAND_MOVE_NORTH: new_y = person->y - person->speed_y; break; case COMMAND_MOVE_EAST: new_x = person->x + person->speed_x; break; case COMMAND_MOVE_SOUTH: new_y = person->y + person->speed_y; break; case COMMAND_MOVE_WEST: new_x = person->x - person->speed_x; break; } if (new_x != person->x || new_y != person->y) { // person is trying to move, make sure the path is clear of obstructions if (!person_obstructed_at(person, new_x, new_y, &person_to_touch, NULL)) { if (new_x != person->x) person->mv_x = new_x > person->x ? 1 : -1; if (new_y != person->y) person->mv_y = new_y > person->y ? 1 : -1; person->x = new_x; person->y = new_y; } else { // if not, and we collided with a person, call that person's touch script if (person_to_touch != NULL) person_activate(person_to_touch, PERSON_SCRIPT_ON_TOUCH, person, true); } } } static int compare_persons(const void* a, const void* b) { person_t* p1 = *(person_t**)a; person_t* p2 = *(person_t**)b; double x, y_p1, y_p2; int y_delta; person_get_xy(p1, &x, &y_p1, true); person_get_xy(p2, &x, &y_p2, true); y_delta = y_p1 - y_p2; if (y_delta != 0) return y_delta; else if (person_following(p1, p2)) return -1; else if (person_following(p2, p1)) return 1; else return p1->id - p2->id; } static void detach_person(const person_t* person) { int i; if (s_camera_person == person) s_camera_person = NULL; for (i = 0; i < PLAYER_MAX; ++i) { if (s_players[i].person == person) s_players[i].person = NULL; } } static bool does_person_exist(const person_t* person) { int i; for (i = 0; i < s_num_persons; ++i) if (person == s_persons[i]) return true; return false; } void draw_persons(int layer, bool is_flipped, int cam_x, int cam_y) { person_t* person; spriteset_t* sprite; int w, h; double x, y; int i; for (i = 0; i < s_num_persons; ++i) { person = s_persons[i]; if (!person->is_visible || person->layer != layer) continue; sprite = person->sprite; w = spriteset_width(sprite); h = spriteset_height(sprite); person_get_xy(person, &x, &y, true); x -= cam_x - person->x_offset; y -= cam_y - person->y_offset; spriteset_draw(sprite, person->mask, is_flipped, person->theta, person->scale_x, person->scale_y, person->direction, trunc(x), trunc(y), person->frame); } } static bool enlarge_step_history(person_t* person, int new_size) { struct step *new_steps; size_t pastmost; double last_x; double last_y; int i; if (new_size > person->max_history) { if (!(new_steps = realloc(person->steps, new_size * sizeof(struct step)))) return false; // when enlarging the history buffer, fill new slots with pastmost values // (kind of like sign extension) pastmost = person->max_history - 1; last_x = person->steps != NULL ? person->steps[pastmost].x : person->x; last_y = person->steps != NULL ? person->steps[pastmost].y : person->y; for (i = person->max_history; i < new_size; ++i) { new_steps[i].x = last_x; new_steps[i].y = last_y; } person->steps = new_steps; person->max_history = new_size; } return true; } static void free_map(struct map* map) { struct map_trigger* trigger; struct map_zone* zone; iter_t iter; int i; if (map == NULL) return; for (i = 0; i < MAP_SCRIPT_MAX; ++i) script_unref(map->scripts[i]); for (i = 0; i < map->num_layers; ++i) { script_unref(map->layers[i].render_script); lstr_free(map->layers[i].name); free(map->layers[i].tilemap); obsmap_free(map->layers[i].obsmap); } for (i = 0; i < map->num_persons; ++i) { lstr_free(map->persons[i].name); lstr_free(map->persons[i].spriteset); lstr_free(map->persons[i].create_script); lstr_free(map->persons[i].destroy_script); lstr_free(map->persons[i].command_script); lstr_free(map->persons[i].talk_script); lstr_free(map->persons[i].touch_script); } iter = vector_enum(s_map->triggers); while ((trigger = iter_next(&iter))) script_unref(trigger->script); iter = vector_enum(s_map->zones); while ((zone = iter_next(&iter))) script_unref(zone->script); lstr_free(s_map->bgm_file); tileset_free(map->tileset); free(map->layers); free(map->persons); vector_free(map->triggers); vector_free(map->zones); free(map); } static void free_person(person_t* person) { int i; free(person->steps); for (i = 0; i < PERSON_SCRIPT_MAX; ++i) script_unref(person->scripts[i]); spriteset_unref(person->sprite); free(person->commands); free(person->name); free(person->direction); free(person); } static struct map_trigger* get_trigger_at(int x, int y, int layer, int* out_index) { rect_t bounds; struct map_trigger* found_item = NULL; int tile_w, tile_h; struct map_trigger* trigger; iter_t iter; tileset_get_size(s_map->tileset, &tile_w, &tile_h); iter = vector_enum(s_map->triggers); while ((trigger = iter_next(&iter))) { if (trigger->z != layer && false) // layer ignored for compatibility reasons continue; bounds.x1 = trigger->x - tile_w / 2; bounds.y1 = trigger->y - tile_h / 2; bounds.x2 = bounds.x1 + tile_w; bounds.y2 = bounds.y1 + tile_h; if (is_point_in_rect(x, y, bounds)) { found_item = trigger; if (out_index != NULL) *out_index = (int)iter.index; break; } } return found_item; } static struct map_zone* get_zone_at(int x, int y, int layer, int which, int* out_index) { struct map_zone* found_item = NULL; struct map_zone* zone; iter_t iter; int i; iter = vector_enum(s_map->zones); i = -1; while ((zone = iter_next(&iter))) { if (zone->layer != layer && false) // layer ignored for compatibility continue; if (is_point_in_rect(x, y, zone->bounds) && which-- == 0) { found_item = zone; if (out_index) *out_index = (int)iter.index; break; } } return found_item; } static struct map* load_map(const char* filename) { // strings: 0 - tileset filename // 1 - music filename // 2 - script filename (obsolete, not used) // 3 - entry script // 4 - exit script // 5 - exit north script // 6 - exit east script // 7 - exit south script // 8 - exit west script uint16_t count; struct rmp_entity_header entity_hdr; file_t* file = NULL; bool has_failed; struct map_layer* layer; struct rmp_layer_header layer_hdr; struct map* map = NULL; int num_tiles; struct map_person* person; struct rmp_header rmp; lstring_t* script; rect_t segment; int16_t* tile_data = NULL; path_t* tileset_path; tileset_t* tileset; struct map_trigger trigger; struct map_zone zone; struct rmp_zone_header zone_hdr; lstring_t* *strings = NULL; int i, j, x, y, z; console_log(2, "constructing new map from '%s'", filename); memset(&rmp, 0, sizeof(struct rmp_header)); if (!(file = file_open(g_game, filename, "rb"))) goto on_error; map = calloc(1, sizeof(struct map)); if (file_read(file, &rmp, 1, sizeof(struct rmp_header)) != 1) goto on_error; if (memcmp(rmp.signature, ".rmp", 4) != 0) goto on_error; if (rmp.num_strings != 3 && rmp.num_strings != 5 && rmp.num_strings < 9) goto on_error; if (rmp.start_layer < 0 || rmp.start_layer >= rmp.num_layers) rmp.start_layer = 0; // being nice here, this really should fail outright switch (rmp.version) { case 1: // load strings (resource filenames, scripts, etc.) strings = calloc(rmp.num_strings, sizeof(lstring_t*)); has_failed = false; for (i = 0; i < rmp.num_strings; ++i) has_failed = has_failed || ((strings[i] = read_lstring(file, true)) == NULL); if (has_failed) goto on_error; // pre-allocate map structures map->layers = calloc(rmp.num_layers, sizeof(struct map_layer)); map->persons = calloc(rmp.num_entities, sizeof(struct map_person)); map->triggers = vector_new(sizeof(struct map_trigger)); map->zones = vector_new(sizeof(struct map_zone)); // load layers for (i = 0; i < rmp.num_layers; ++i) { if (file_read(file, &layer_hdr, 1, sizeof(struct rmp_layer_header)) != 1) goto on_error; layer = &map->layers[i]; layer->is_parallax = (layer_hdr.flags & 2) != 0x0; layer->is_reflective = layer_hdr.is_reflective; layer->is_visible = (layer_hdr.flags & 1) == 0x0; layer->color_mask = mk_color(255, 255, 255, 255); layer->width = layer_hdr.width; layer->height = layer_hdr.height; layer->autoscroll_x = layer->is_parallax ? layer_hdr.scrolling_x : 0.0; layer->autoscroll_y = layer->is_parallax ? layer_hdr.scrolling_y : 0.0; layer->parallax_x = layer->is_parallax ? layer_hdr.parallax_x : 1.0; layer->parallax_y = layer->is_parallax ? layer_hdr.parallax_y : 1.0; if (!layer->is_parallax) { map->width = fmax(map->width, layer->width); map->height = fmax(map->height, layer->height); } if (!(layer->tilemap = malloc(layer_hdr.width * layer_hdr.height * sizeof(struct map_tile)))) goto on_error; layer->name = read_lstring(file, true); layer->obsmap = obsmap_new(); num_tiles = layer_hdr.width * layer_hdr.height; if ((tile_data = malloc(num_tiles * 2)) == NULL) goto on_error; if (file_read(file, tile_data, num_tiles, 2) != num_tiles) goto on_error; for (j = 0; j < num_tiles; ++j) layer->tilemap[j].tile_index = tile_data[j]; for (j = 0; j < layer_hdr.num_segments; ++j) { if (!fread_rect32(file, &segment)) goto on_error; obsmap_add_line(layer->obsmap, segment); } free(tile_data); tile_data = NULL; } // if either dimension is zero, the map has no non-parallax layers and is thus malformed if (map->width == 0 || map->height == 0) goto on_error; // load entities map->num_persons = 0; for (i = 0; i < rmp.num_entities; ++i) { if (file_read(file, &entity_hdr, 1, sizeof(struct rmp_entity_header)) != 1) goto on_error; if (entity_hdr.z < 0 || entity_hdr.z >= rmp.num_layers) entity_hdr.z = 0; switch (entity_hdr.type) { case 1: // person ++map->num_persons; person = &map->persons[map->num_persons - 1]; memset(person, 0, sizeof(struct map_person)); if (!(person->name = read_lstring(file, true))) goto on_error; if (!(person->spriteset = read_lstring(file, true))) goto on_error; person->x = entity_hdr.x; person->y = entity_hdr.y; person->z = entity_hdr.z; if (file_read(file, &count, 1, 2) != 1 || count < 5) goto on_error; person->create_script = read_lstring(file, false); person->destroy_script = read_lstring(file, false); person->touch_script = read_lstring(file, false); person->talk_script = read_lstring(file, false); person->command_script = read_lstring(file, false); for (j = 5; j < count; ++j) lstr_free(read_lstring(file, true)); file_seek(file, 16, WHENCE_CUR); break; case 2: // trigger if ((script = read_lstring(file, false)) == NULL) goto on_error; memset(&trigger, 0, sizeof(struct map_trigger)); trigger.x = entity_hdr.x; trigger.y = entity_hdr.y; trigger.z = entity_hdr.z; trigger.script = script_new(script, "%s/trig%d", filename, vector_len(map->triggers)); if (!vector_push(map->triggers, &trigger)) return false; lstr_free(script); break; default: goto on_error; } } // load zones for (i = 0; i < rmp.num_zones; ++i) { if (file_read(file, &zone_hdr, 1, sizeof(struct rmp_zone_header)) != 1) goto on_error; if ((script = read_lstring(file, false)) == NULL) goto on_error; if (zone_hdr.layer < 0 || zone_hdr.layer >= rmp.num_layers) zone_hdr.layer = 0; zone.layer = zone_hdr.layer; zone.bounds = mk_rect(zone_hdr.x1, zone_hdr.y1, zone_hdr.x2, zone_hdr.y2); zone.interval = zone_hdr.interval; zone.steps_left = 0; zone.script = script_new(script, "%s/zone%d", filename, vector_len(map->zones)); rect_normalize(&zone.bounds); if (!vector_push(map->zones, &zone)) return false; lstr_free(script); } // load tileset if (strcmp(lstr_cstr(strings[0]), "") != 0) { tileset_path = path_strip(path_new(filename)); path_append(tileset_path, lstr_cstr(strings[0])); tileset = tileset_new(path_cstr(tileset_path)); path_free(tileset_path); } else { tileset = tileset_read(file); } if (tileset == NULL) goto on_error; // initialize tile animation for (z = 0; z < rmp.num_layers; ++z) { layer = &map->layers[z]; for (x = 0; x < layer->width; ++x) for (y = 0; y < layer->height; ++y) { i = x + y * layer->width; map->layers[z].tilemap[i].frames_left = tileset_get_delay(tileset, map->layers[z].tilemap[i].tile_index); } } // wrap things up map->bgm_file = strcmp(lstr_cstr(strings[1]), "") != 0 ? lstr_dup(strings[1]) : NULL; map->num_layers = rmp.num_layers; map->is_repeating = rmp.repeat_map; map->origin.x = rmp.start_x; map->origin.y = rmp.start_y; map->origin.z = rmp.start_layer; map->tileset = tileset; if (rmp.num_strings >= 5) { map->scripts[MAP_SCRIPT_ON_ENTER] = script_new(strings[3], "%s/onEnter", filename); map->scripts[MAP_SCRIPT_ON_LEAVE] = script_new(strings[4], "%s/onLeave", filename); } if (rmp.num_strings >= 9) { map->scripts[MAP_SCRIPT_ON_LEAVE_NORTH] = script_new(strings[5], "%s/onLeave", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_EAST] = script_new(strings[6], "%s/onLeaveEast", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_SOUTH] = script_new(strings[7], "%s/onLeaveSouth", filename); map->scripts[MAP_SCRIPT_ON_LEAVE_WEST] = script_new(strings[8], "%s/onLeaveWest", filename); } for (i = 0; i < rmp.num_strings; ++i) lstr_free(strings[i]); free(strings); break; default: goto on_error; } file_close(file); return map; on_error: if (file != NULL) file_close(file); free(tile_data); if (strings != NULL) { for (i = 0; i < rmp.num_strings; ++i) lstr_free(strings[i]); free(strings); } if (map != NULL) { if (map->layers != NULL) { for (i = 0; i < rmp.num_layers; ++i) { lstr_free(map->layers[i].name); free(map->layers[i].tilemap); obsmap_free(map->layers[i].obsmap); } free(map->layers); } if (map->persons != NULL) { for (i = 0; i < map->num_persons; ++i) { lstr_free(map->persons[i].name); lstr_free(map->persons[i].spriteset); lstr_free(map->persons[i].create_script); lstr_free(map->persons[i].destroy_script); lstr_free(map->persons[i].command_script); lstr_free(map->persons[i].talk_script); lstr_free(map->persons[i].touch_script); } free(map->persons); } vector_free(map->triggers); vector_free(map->zones); free(map); } return NULL; } void map_screen_to_layer(int layer, int camera_x, int camera_y, int* inout_x, int* inout_y) { rect_t bounds; int center_x; int center_y; int layer_h; int layer_w; float plx_offset_x = 0.0; int plx_offset_y = 0.0; size2_t resolution; int tile_w; int tile_h; int x_offset; int y_offset; // get layer and screen metrics resolution = screen_size(g_screen); tileset_get_size(s_map->tileset, &tile_w, &tile_h); layer_w = s_map->layers[layer].width * tile_w; layer_h = s_map->layers[layer].height * tile_h; center_x = resolution.width / 2; center_y = resolution.height / 2; // initial camera correction if (!s_map->is_repeating) { bounds = map_bounds(); camera_x = fmin(fmax(camera_x, bounds.x1 + center_x), bounds.x2 - center_x); camera_y = fmin(fmax(camera_y, bounds.y1 + center_y), bounds.y2 - center_y); } // remap screen coordinates to layer coordinates plx_offset_x = s_frames * s_map->layers[layer].autoscroll_x - camera_x * (s_map->layers[layer].parallax_x - 1.0); plx_offset_y = s_frames * s_map->layers[layer].autoscroll_y - camera_y * (s_map->layers[layer].parallax_y - 1.0); x_offset = camera_x - center_x - plx_offset_x; y_offset = camera_y - center_y - plx_offset_y; if (!s_map->is_repeating && !s_map->layers[layer].is_parallax) { // if the map is smaller than the screen, align to top left. centering // would be better aesthetically, but there are a couple Sphere 1.x games // that depend on top-left justification. if (layer_w < resolution.width) x_offset = 0; if (layer_h < resolution.height) y_offset = 0; } if (inout_x != NULL) *inout_x += x_offset; if (inout_y != NULL) *inout_y += y_offset; // normalize coordinates. this simplifies rendering calculations. if (s_map->is_repeating || s_map->layers[layer].is_parallax) { if (inout_x) *inout_x = (*inout_x % layer_w + layer_w) % layer_w; if (inout_y) *inout_y = (*inout_y % layer_h + layer_h) % layer_h; } } static void map_screen_to_map(int camera_x, int camera_y, int* inout_x, int* inout_y) { rect_t bounds; int center_x; int center_y; int map_h; int map_w; size2_t resolution; int tile_h; int tile_w; int x_offset; int y_offset; // get layer and screen metrics resolution = screen_size(g_screen); tileset_get_size(s_map->tileset, &tile_w, &tile_h); map_w = s_map->width * tile_w; map_h = s_map->height * tile_h; center_x = resolution.width / 2; center_y = resolution.height / 2; // initial camera correction if (!s_map->is_repeating) { bounds = map_bounds(); camera_x = fmin(fmax(camera_x, bounds.x1 + center_x), bounds.x2 - center_x); camera_y = fmin(fmax(camera_y, bounds.y1 + center_y), bounds.y2 - center_y); } // remap screen coordinates to map coordinates x_offset = camera_x - center_x; y_offset = camera_y - center_y; if (!s_map->is_repeating) { // if the map is smaller than the screen, align to top left. centering // would be better aesthetically, but there are a couple Sphere 1.x games // that depend on top-left justification. if (map_w < resolution.width) x_offset = 0; if (map_h < resolution.height) y_offset = 0; } if (inout_x != NULL) *inout_x += x_offset; if (inout_y != NULL) *inout_y += y_offset; // normalize coordinates if (s_map->is_repeating) { if (inout_x) *inout_x = (*inout_x % map_w + map_w) % map_w; if (inout_y) *inout_y = (*inout_y % map_h + map_h) % map_h; } } static void process_map_input(void) { int mv_x, mv_y; person_t* person; int i; // clear out excess keys from key queue kb_clear_queue(); // check for player control of input persons, if there are any for (i = 0; i < PLAYER_MAX; ++i) { person = s_players[i].person; if (person != NULL) { if (kb_is_key_down(get_player_key(i, PLAYER_KEY_A)) || kb_is_key_down(s_players[i].talk_key) || joy_is_button_down(i, s_talk_button)) { if (s_players[i].is_talk_allowed) person_talk(person); s_players[i].is_talk_allowed = false; } else { // allow talking again only after key is released s_players[i].is_talk_allowed = true; } mv_x = 0; mv_y = 0; if (person->num_commands == 0 && person->leader == NULL) { // allow player control only if the input person is idle and not being led around // by someone else. if (kb_is_key_down(get_player_key(i, PLAYER_KEY_UP)) || joy_position(i, 1) <= -0.5) mv_y = -1; if (kb_is_key_down(get_player_key(i, PLAYER_KEY_RIGHT)) || joy_position(i, 0) >= 0.5) mv_x = 1; if (kb_is_key_down(get_player_key(i, PLAYER_KEY_DOWN)) || joy_position(i, 1) >= 0.5) mv_y = 1; if (kb_is_key_down(get_player_key(i, PLAYER_KEY_LEFT)) || joy_position(i, 0) <= -0.5) mv_x = -1; } switch (mv_x + mv_y * 3) { case -3: // north person_queue_command(person, COMMAND_MOVE_NORTH, true); person_queue_command(person, COMMAND_FACE_NORTH, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case -2: // northeast person_queue_command(person, COMMAND_MOVE_NORTHEAST, true); person_queue_command(person, COMMAND_FACE_NORTHEAST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case 1: // east person_queue_command(person, COMMAND_MOVE_EAST, true); person_queue_command(person, COMMAND_FACE_EAST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case 4: // southeast person_queue_command(person, COMMAND_MOVE_SOUTHEAST, true); person_queue_command(person, COMMAND_FACE_SOUTHEAST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case 3: // south person_queue_command(person, COMMAND_MOVE_SOUTH, true); person_queue_command(person, COMMAND_FACE_SOUTH, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case 2: // southwest person_queue_command(person, COMMAND_MOVE_SOUTHWEST, true); person_queue_command(person, COMMAND_FACE_SOUTHWEST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case -1: // west person_queue_command(person, COMMAND_MOVE_WEST, true); person_queue_command(person, COMMAND_FACE_WEST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; case -4: // northwest person_queue_command(person, COMMAND_MOVE_NORTHWEST, true); person_queue_command(person, COMMAND_FACE_NORTHWEST, true); person_queue_command(person, COMMAND_ANIMATE, false); break; } } } update_bound_keys(true); } static void record_step(person_t* person) { struct step* p_step; if (person->max_history <= 0) return; memmove(&person->steps[1], &person->steps[0], (person->max_history - 1) * sizeof(struct step)); p_step = &person->steps[0]; p_step->x = person->x; p_step->y = person->y; } void reset_persons(bool keep_existing) { unsigned int id; point3_t origin; person_t* person; int i, j; origin = map_origin(); for (i = 0; i < s_num_persons; ++i) { person = s_persons[i]; id = person->id; if (!keep_existing) person->num_commands = 0; if (person->is_persistent || keep_existing) { person->x = origin.x; person->y = origin.y; person->layer = origin.z; } else { person_activate(person, PERSON_SCRIPT_ON_DESTROY, NULL, true); free_person(person); --s_num_persons; for (j = i; j < s_num_persons; ++j) s_persons[j] = s_persons[j + 1]; --i; } } sort_persons(); } static void set_person_name(person_t* person, const char* name) { person->name = realloc(person->name, (strlen(name) + 1) * sizeof(char)); strcpy(person->name, name); } static void sort_persons(void) { qsort(s_persons, s_num_persons, sizeof(person_t*), compare_persons); } static void update_map_engine(bool in_main_loop) { bool has_moved; int index; bool is_sort_needed = false; int last_trigger; int last_zone; int layer; int map_w, map_h; int num_zone_steps; script_t* script_to_run; int script_type; double start_x[PLAYER_MAX]; double start_y[PLAYER_MAX]; int tile_w, tile_h; struct map_trigger* trigger; double x, y, px, py; struct map_zone* zone; int i, j, k; ++s_frames; tileset_get_size(s_map->tileset, &tile_w, &tile_h); map_w = s_map->width * tile_w; map_h = s_map->height * tile_h; tileset_update(s_map->tileset); for (i = 0; i < PLAYER_MAX; ++i) if (s_players[i].person != NULL) person_get_xy(s_players[i].person, &start_x[i], &start_y[i], false); for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader != NULL) continue; // skip followers for now update_person(s_persons[i], &has_moved); is_sort_needed |= has_moved; } if (is_sort_needed) sort_persons(); // update color mask fade level if (s_fade_progress < s_fade_frames) { ++s_fade_progress; s_color_mask = color_mix(s_fade_color_to, s_fade_color_from, s_fade_progress, s_fade_frames - s_fade_progress); } // update camera if (s_camera_person != NULL) { person_get_xy(s_camera_person, &x, &y, true); s_camera_x = x; s_camera_y = y; } // run edge script if the camera has moved past the edge of the map // note: only applies for non-repeating maps if (in_main_loop && !s_map->is_repeating) { script_type = s_camera_y < 0 ? MAP_SCRIPT_ON_LEAVE_NORTH : s_camera_x >= map_w ? MAP_SCRIPT_ON_LEAVE_EAST : s_camera_y >= map_h ? MAP_SCRIPT_ON_LEAVE_SOUTH : s_camera_x < 0 ? MAP_SCRIPT_ON_LEAVE_WEST : MAP_SCRIPT_MAX; if (script_type < MAP_SCRIPT_MAX) map_activate(script_type, true); } // if there are any input persons, check for trigger activation for (i = 0; i < PLAYER_MAX; ++i) if (s_players[i].person != NULL) { // did we step on a trigger or move to a new one? person_get_xyz(s_players[i].person, &x, &y, &layer, true); trigger = get_trigger_at(x, y, layer, &index); if (trigger != s_on_trigger) { last_trigger = s_current_trigger; s_current_trigger = index; s_on_trigger = trigger; if (trigger != NULL) script_run(trigger->script, false); s_current_trigger = last_trigger; } } // update any zones occupied by the input person // note: a zone's step count is in reality a pixel count, so a zone // may be updated multiple times in a single frame. for (k = 0; k < PLAYER_MAX; ++k) if (s_players[k].person != NULL) { person_get_xy(s_players[k].person, &x, &y, false); px = fabs(x - start_x[k]); py = fabs(y - start_y[k]); num_zone_steps = px > py ? px : py; for (i = 0; i < num_zone_steps; ++i) { j = 0; while ((zone = get_zone_at(x, y, layer, j++, &index))) { if (zone->steps_left-- <= 0) { last_zone = s_current_zone; s_current_zone = index; zone->steps_left = zone->interval; script_run(zone->script, true); s_current_zone = last_zone; } } } } // check if there are any deferred scripts due to run this frame // and run the ones that are for (i = 0; i < s_num_deferreds; ++i) { if (s_deferreds[i].frames_left-- <= 0) { script_to_run = s_deferreds[i].script; for (j = i; j < s_num_deferreds - 1; ++j) s_deferreds[j] = s_deferreds[j + 1]; --s_num_deferreds; script_run(script_to_run, false); script_unref(script_to_run); --i; } } // now that everything else is in order, we can run the // update script! script_run(s_update_script, false); } static void update_person(person_t* person, bool* out_has_moved) { struct command command; double delta_x, delta_y; int facing; bool has_moved; bool is_finished; const person_t* last_person; struct step step; int vector; int i; person->mv_x = 0; person->mv_y = 0; if (person->revert_frames > 0 && --person->revert_frames <= 0) person->frame = 0; if (person->leader == NULL) { // no leader; use command queue // call the command generator if the queue is empty if (person->num_commands == 0) person_activate(person, PERSON_SCRIPT_GENERATOR, NULL, true); // run through the queue, stopping after the first non-immediate command is_finished = !does_person_exist(person) || person->num_commands == 0; while (!is_finished) { command = person->commands[0]; --person->num_commands; for (i = 0; i < person->num_commands; ++i) person->commands[i] = person->commands[i + 1]; last_person = s_current_person; s_current_person = person; if (command.type != COMMAND_RUN_SCRIPT) command_person(person, command.type); else script_run(command.script, false); s_current_person = last_person; script_unref(command.script); is_finished = !does_person_exist(person) // stop if person was destroyed || !command.is_immediate || person->num_commands == 0; } } else { // leader set; follow the leader! step = person->leader->steps[person->follow_distance - 1]; delta_x = step.x - person->x; delta_y = step.y - person->y; if (fabs(delta_x) > person->speed_x) command_person(person, delta_x > 0 ? COMMAND_MOVE_EAST : COMMAND_MOVE_WEST); if (!does_person_exist(person)) return; if (fabs(delta_y) > person->speed_y) command_person(person, delta_y > 0 ? COMMAND_MOVE_SOUTH : COMMAND_MOVE_NORTH); if (!does_person_exist(person)) return; vector = person->mv_x + person->mv_y * 3; facing = vector == -3 ? COMMAND_FACE_NORTH : vector == -2 ? COMMAND_FACE_NORTHEAST : vector == 1 ? COMMAND_FACE_EAST : vector == 4 ? COMMAND_FACE_SOUTHEAST : vector == 3 ? COMMAND_FACE_SOUTH : vector == 2 ? COMMAND_FACE_SOUTHWEST : vector == -1 ? COMMAND_FACE_WEST : vector == -4 ? COMMAND_FACE_NORTHWEST : COMMAND_WAIT; if (facing != COMMAND_WAIT) command_person(person, COMMAND_ANIMATE); if (!does_person_exist(person)) return; command_person(person, facing); } // check that the person didn't mysteriously disappear... if (!does_person_exist(person)) return; // they probably got eaten by a pig. // if the person's position changed, record it in their step history *out_has_moved = person_has_moved(person); if (*out_has_moved) record_step(person); // recursively update the follower chain for (i = 0; i < s_num_persons; ++i) { if (s_persons[i]->leader != person) continue; update_person(s_persons[i], &has_moved); *out_has_moved |= has_moved; } }
./CrossVul/dataset_final_sorted/CWE-190/c/good_35_0
crossvul-cpp_data_bad_664_0
/* * 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. */ #include "index.h" #include <stddef.h> #include "repository.h" #include "tree.h" #include "tree-cache.h" #include "hash.h" #include "iterator.h" #include "pathspec.h" #include "ignore.h" #include "blob.h" #include "idxmap.h" #include "diff.h" #include "varint.h" #include "git2/odb.h" #include "git2/oid.h" #include "git2/blob.h" #include "git2/config.h" #include "git2/sys/index.h" #define INSERT_IN_MAP_EX(idx, map, e, err) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_insert((khash_t(idxicase) *) (map), (e), (e), (err)); \ else \ git_idxmap_insert((map), (e), (e), (err)); \ } while (0) #define INSERT_IN_MAP(idx, e, err) INSERT_IN_MAP_EX(idx, (idx)->entries_map, e, err) #define LOOKUP_IN_MAP(p, idx, k) do { \ if ((idx)->ignore_case) \ (p) = git_idxmap_icase_lookup_index((khash_t(idxicase) *) index->entries_map, (k)); \ else \ (p) = git_idxmap_lookup_index(index->entries_map, (k)); \ } while (0) #define DELETE_IN_MAP(idx, e) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_delete((khash_t(idxicase) *) (idx)->entries_map, (e)); \ else \ git_idxmap_delete((idx)->entries_map, (e)); \ } while (0) static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload); #define minimal_entry_size (offsetof(struct entry_short, path)) static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ; static const size_t INDEX_HEADER_SIZE = 12; static const unsigned int INDEX_VERSION_NUMBER_DEFAULT = 2; static const unsigned int INDEX_VERSION_NUMBER_LB = 2; static const unsigned int INDEX_VERSION_NUMBER_EXT = 3; static const unsigned int INDEX_VERSION_NUMBER_COMP = 4; static const unsigned int INDEX_VERSION_NUMBER_UB = 4; static const unsigned int INDEX_HEADER_SIG = 0x44495243; static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'}; static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'}; static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'}; #define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx))) struct index_header { uint32_t signature; uint32_t version; uint32_t entry_count; }; struct index_extension { char signature[4]; uint32_t extension_size; }; struct entry_time { uint32_t seconds; uint32_t nanoseconds; }; struct entry_short { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; char path[1]; /* arbitrary length */ }; struct entry_long { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; uint16_t flags_extended; char path[1]; /* arbitrary length */ }; struct entry_srch_key { const char *path; size_t pathlen; int stage; }; struct entry_internal { git_index_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; struct reuc_entry_internal { git_index_reuc_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; /* local declarations */ static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size); static int read_header(struct index_header *dest, const void *buffer); static int parse_index(git_index *index, const char *buffer, size_t buffer_size); static bool is_index_extended(git_index *index); static int write_index(git_oid *checksum, git_index *index, git_filebuf *file); static void index_entry_free(git_index_entry *entry); static void index_entry_reuc_free(git_index_reuc_entry *reuc); int git_index_entry_srch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = memcmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } int git_index_entry_isrch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = strncasecmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } static int index_entry_srch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcmp((const char *)path, entry->path); } static int index_entry_isrch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcasecmp((const char *)path, entry->path); } int git_index_entry_cmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } int git_index_entry_icmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcasecmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } static int conflict_name_cmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcmp(name_a->ours, name_b->ours); } /** * TODO: enable this when resolving case insensitive conflicts */ #if 0 static int conflict_name_icmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcasecmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcasecmp(name_a->ours, name_b->ours); } #endif static int reuc_srch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcmp(key, reuc->path); } static int reuc_isrch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcasecmp(key, reuc->path); } static int reuc_cmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcmp(info_a->path, info_b->path); } static int reuc_icmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcasecmp(info_a->path, info_b->path); } static void index_entry_reuc_free(git_index_reuc_entry *reuc) { git__free(reuc); } static void index_entry_free(git_index_entry *entry) { if (!entry) return; memset(&entry->id, 0, sizeof(entry->id)); git__free(entry); } unsigned int git_index__create_mode(unsigned int mode) { if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR)) return (S_IFLNK | S_IFDIR); return S_IFREG | GIT_PERMS_CANONICAL(mode); } static unsigned int index_merge_mode( git_index *index, git_index_entry *existing, unsigned int mode) { if (index->no_symlinks && S_ISREG(mode) && existing && S_ISLNK(existing->mode)) return existing->mode; if (index->distrust_filemode && S_ISREG(mode)) return (existing && S_ISREG(existing->mode)) ? existing->mode : git_index__create_mode(0666); return git_index__create_mode(mode); } GIT_INLINE(int) index_find_in_entries( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { struct entry_srch_key srch_key; srch_key.path = path; srch_key.pathlen = !path_len ? strlen(path) : path_len; srch_key.stage = stage; return git_vector_bsearch2(out, entries, entry_srch, &srch_key); } GIT_INLINE(int) index_find( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { git_vector_sort(&index->entries); return index_find_in_entries( out, &index->entries, index->entries_search, path, path_len, stage); } void git_index__set_ignore_case(git_index *index, bool ignore_case) { index->ignore_case = ignore_case; if (ignore_case) { index->entries_cmp_path = git__strcasecmp_cb; index->entries_search = git_index_entry_isrch; index->entries_search_path = index_entry_isrch_path; index->reuc_search = reuc_isrch; } else { index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; } git_vector_set_cmp(&index->entries, ignore_case ? git_index_entry_icmp : git_index_entry_cmp); git_vector_sort(&index->entries); git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp); git_vector_sort(&index->reuc); } int git_index_open(git_index **index_out, const char *index_path) { git_index *index; int error = -1; assert(index_out); index = git__calloc(1, sizeof(git_index)); GITERR_CHECK_ALLOC(index); git_pool_init(&index->tree_pool, 1); if (index_path != NULL) { index->index_file_path = git__strdup(index_path); if (!index->index_file_path) goto fail; /* Check if index file is stored on disk already */ if (git_path_exists(index->index_file_path) == true) index->on_disk = 1; } if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 || git_idxmap_alloc(&index->entries_map) < 0 || git_vector_init(&index->names, 8, conflict_name_cmp) < 0 || git_vector_init(&index->reuc, 8, reuc_cmp) < 0 || git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0) goto fail; index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; index->version = INDEX_VERSION_NUMBER_DEFAULT; if (index_path != NULL && (error = git_index_read(index, true)) < 0) goto fail; *index_out = index; GIT_REFCOUNT_INC(index); return 0; fail: git_pool_clear(&index->tree_pool); git_index_free(index); return error; } int git_index_new(git_index **out) { return git_index_open(out, NULL); } static void index_free(git_index *index) { /* index iterators increment the refcount of the index, so if we * get here then there should be no outstanding iterators. */ assert(!git_atomic_get(&index->readers)); git_index_clear(index); git_idxmap_free(index->entries_map); git_vector_free(&index->entries); git_vector_free(&index->names); git_vector_free(&index->reuc); git_vector_free(&index->deleted); git__free(index->index_file_path); git__memzero(index, sizeof(*index)); git__free(index); } void git_index_free(git_index *index) { if (index == NULL) return; GIT_REFCOUNT_DEC(index, index_free); } /* call with locked index */ static void index_free_deleted(git_index *index) { int readers = (int)git_atomic_get(&index->readers); size_t i; if (readers > 0 || !index->deleted.length) return; for (i = 0; i < index->deleted.length; ++i) { git_index_entry *ie = git__swap(index->deleted.contents[i], NULL); index_entry_free(ie); } git_vector_clear(&index->deleted); } /* call with locked index */ static int index_remove_entry(git_index *index, size_t pos) { int error = 0; git_index_entry *entry = git_vector_get(&index->entries, pos); if (entry != NULL) { git_tree_cache_invalidate_path(index->tree, entry->path); DELETE_IN_MAP(index, entry); } error = git_vector_remove(&index->entries, pos); if (!error) { if (git_atomic_get(&index->readers) > 0) { error = git_vector_insert(&index->deleted, entry); } else { index_entry_free(entry); } } return error; } int git_index_clear(git_index *index) { int error = 0; assert(index); index->tree = NULL; git_pool_clear(&index->tree_pool); git_idxmap_clear(index->entries_map); while (!error && index->entries.length > 0) error = index_remove_entry(index, index->entries.length - 1); index_free_deleted(index); git_index_reuc_clear(index); git_index_name_clear(index); git_futils_filestamp_set(&index->stamp, NULL); return error; } static int create_index_error(int error, const char *msg) { giterr_set_str(GITERR_INDEX, msg); return error; } int git_index_set_caps(git_index *index, int caps) { unsigned int old_ignore_case; assert(index); old_ignore_case = index->ignore_case; if (caps == GIT_INDEXCAP_FROM_OWNER) { git_repository *repo = INDEX_OWNER(index); int val; if (!repo) return create_index_error( -1, "cannot access repository to set index caps"); if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE)) index->ignore_case = (val != 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE)) index->distrust_filemode = (val == 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS)) index->no_symlinks = (val == 0); } else { index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0); index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0); index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0); } if (old_ignore_case != index->ignore_case) { git_index__set_ignore_case(index, (bool)index->ignore_case); } return 0; } int git_index_caps(const git_index *index) { return ((index->ignore_case ? GIT_INDEXCAP_IGNORE_CASE : 0) | (index->distrust_filemode ? GIT_INDEXCAP_NO_FILEMODE : 0) | (index->no_symlinks ? GIT_INDEXCAP_NO_SYMLINKS : 0)); } const git_oid *git_index_checksum(git_index *index) { return &index->checksum; } /** * Returns 1 for changed, 0 for not changed and <0 for errors */ static int compare_checksum(git_index *index) { int fd; ssize_t bytes_read; git_oid checksum = {{ 0 }}; if ((fd = p_open(index->index_file_path, O_RDONLY)) < 0) return fd; if (p_lseek(fd, -20, SEEK_END) < 0) { p_close(fd); giterr_set(GITERR_OS, "failed to seek to end of file"); return -1; } bytes_read = p_read(fd, &checksum, GIT_OID_RAWSZ); p_close(fd); if (bytes_read < 0) return -1; return !!git_oid_cmp(&checksum, &index->checksum); } int git_index_read(git_index *index, int force) { int error = 0, updated; git_buf buffer = GIT_BUF_INIT; git_futils_filestamp stamp = index->stamp; if (!index->index_file_path) return create_index_error(-1, "failed to read index: The index is in-memory only"); index->on_disk = git_path_exists(index->index_file_path); if (!index->on_disk) { if (force) return git_index_clear(index); return 0; } if ((updated = git_futils_filestamp_check(&stamp, index->index_file_path) < 0) || ((updated = compare_checksum(index)) < 0)) { giterr_set( GITERR_INDEX, "failed to read index: '%s' no longer exists", index->index_file_path); return updated; } if (!updated && !force) return 0; error = git_futils_readbuffer(&buffer, index->index_file_path); if (error < 0) return error; index->tree = NULL; git_pool_clear(&index->tree_pool); error = git_index_clear(index); if (!error) error = parse_index(index, buffer.ptr, buffer.size); if (!error) git_futils_filestamp_set(&index->stamp, &stamp); git_buf_free(&buffer); return error; } int git_index__changed_relative_to( git_index *index, const git_oid *checksum) { /* attempt to update index (ignoring errors) */ if (git_index_read(index, false) < 0) giterr_clear(); return !!git_oid_cmp(&index->checksum, checksum); } static bool is_racy_entry(git_index *index, const git_index_entry *entry) { /* Git special-cases submodules in the check */ if (S_ISGITLINK(entry->mode)) return false; return git_index_entry_newer_than_index(entry, index); } /* * Force the next diff to take a look at those entries which have the * same timestamp as the current index. */ static int truncate_racily_clean(git_index *index) { size_t i; int error; git_index_entry *entry; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; git_diff *diff = NULL; git_vector paths = GIT_VECTOR_INIT; git_diff_delta *delta; /* Nothing to do if there's no repo to talk about */ if (!INDEX_OWNER(index)) return 0; /* If there's no workdir, we can't know where to even check */ if (!git_repository_workdir(INDEX_OWNER(index))) return 0; diff_opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE | GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_DISABLE_PATHSPEC_MATCH; git_vector_foreach(&index->entries, i, entry) { if ((entry->flags_extended & GIT_IDXENTRY_UPTODATE) == 0 && is_racy_entry(index, entry)) git_vector_insert(&paths, (char *)entry->path); } if (paths.length == 0) goto done; diff_opts.pathspec.count = paths.length; diff_opts.pathspec.strings = (char **)paths.contents; if ((error = git_diff_index_to_workdir(&diff, INDEX_OWNER(index), index, &diff_opts)) < 0) return error; git_vector_foreach(&diff->deltas, i, delta) { entry = (git_index_entry *)git_index_get_bypath(index, delta->old_file.path, 0); /* Ensure that we have a stage 0 for this file (ie, it's not a * conflict), otherwise smudging it is quite pointless. */ if (entry) entry->file_size = 0; } done: git_diff_free(diff); git_vector_free(&paths); return 0; } unsigned git_index_version(git_index *index) { assert(index); return index->version; } int git_index_set_version(git_index *index, unsigned int version) { assert(index); if (version < INDEX_VERSION_NUMBER_LB || version > INDEX_VERSION_NUMBER_UB) { giterr_set(GITERR_INDEX, "invalid version number"); return -1; } index->version = version; return 0; } int git_index_write(git_index *index) { git_indexwriter writer = GIT_INDEXWRITER_INIT; int error; truncate_racily_clean(index); if ((error = git_indexwriter_init(&writer, index)) == 0) error = git_indexwriter_commit(&writer); git_indexwriter_cleanup(&writer); return error; } const char * git_index_path(const git_index *index) { assert(index); return index->index_file_path; } int git_index_write_tree(git_oid *oid, git_index *index) { git_repository *repo; assert(oid && index); repo = INDEX_OWNER(index); if (repo == NULL) return create_index_error(-1, "Failed to write tree. " "the index file is not backed up by an existing repository"); return git_tree__write_index(oid, index, repo); } int git_index_write_tree_to( git_oid *oid, git_index *index, git_repository *repo) { assert(oid && index && repo); return git_tree__write_index(oid, index, repo); } size_t git_index_entrycount(const git_index *index) { assert(index); return index->entries.length; } const git_index_entry *git_index_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->entries); return git_vector_get(&index->entries, n); } const git_index_entry *git_index_get_bypath( git_index *index, const char *path, int stage) { khiter_t pos; git_index_entry key = {{ 0 }}; assert(index); key.path = path; GIT_IDXENTRY_STAGE_SET(&key, stage); LOOKUP_IN_MAP(pos, index, &key); if (git_idxmap_valid_index(index->entries_map, pos)) return git_idxmap_value_at(index->entries_map, pos); giterr_set(GITERR_INDEX, "index does not contain '%s'", path); return NULL; } void git_index_entry__init_from_stat( git_index_entry *entry, struct stat *st, bool trust_mode) { entry->ctime.seconds = (int32_t)st->st_ctime; entry->mtime.seconds = (int32_t)st->st_mtime; #if defined(GIT_USE_NSEC) entry->mtime.nanoseconds = st->st_mtime_nsec; entry->ctime.nanoseconds = st->st_ctime_nsec; #endif entry->dev = st->st_rdev; entry->ino = st->st_ino; entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ? git_index__create_mode(0666) : git_index__create_mode(st->st_mode); entry->uid = st->st_uid; entry->gid = st->st_gid; entry->file_size = (uint32_t)st->st_size; } static void index_entry_adjust_namemask( git_index_entry *entry, size_t path_length) { entry->flags &= ~GIT_IDXENTRY_NAMEMASK; if (path_length < GIT_IDXENTRY_NAMEMASK) entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK; else entry->flags |= GIT_IDXENTRY_NAMEMASK; } /* When `from_workdir` is true, we will validate the paths to avoid placing * paths that are invalid for the working directory on the current filesystem * (eg, on Windows, we will disallow `GIT~1`, `AUX`, `COM1`, etc). This * function will *always* prevent `.git` and directory traversal `../` from * being added to the index. */ static int index_entry_create( git_index_entry **out, git_repository *repo, const char *path, bool from_workdir) { size_t pathlen = strlen(path), alloclen; struct entry_internal *entry; unsigned int path_valid_flags = GIT_PATH_REJECT_INDEX_DEFAULTS; /* always reject placing `.git` in the index and directory traversal. * when requested, disallow platform-specific filenames and upgrade to * the platform-specific `.git` tests (eg, `git~1`, etc). */ if (from_workdir) path_valid_flags |= GIT_PATH_REJECT_WORKDIR_DEFAULTS; if (!git_path_isvalid(repo, path, path_valid_flags)) { giterr_set(GITERR_INDEX, "invalid path: '%s'", path); return -1; } GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); entry = git__calloc(1, alloclen); GITERR_CHECK_ALLOC(entry); entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; *out = (git_index_entry *)entry; return 0; } static int index_entry_init( git_index_entry **entry_out, git_index *index, const char *rel_path) { int error = 0; git_index_entry *entry = NULL; struct stat st; git_oid oid; if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (index_entry_create(&entry, INDEX_OWNER(index), rel_path, true) < 0) return -1; /* write the blob to disk and get the oid and stat info */ error = git_blob__create_from_paths( &oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true); if (error < 0) { index_entry_free(entry); return error; } entry->id = oid; git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); *entry_out = (git_index_entry *)entry; return 0; } static git_index_reuc_entry *reuc_entry_alloc(const char *path) { size_t pathlen = strlen(path), structlen = sizeof(struct reuc_entry_internal), alloclen; struct reuc_entry_internal *entry; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) || GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1)) return NULL; entry = git__calloc(1, alloclen); if (!entry) return NULL; entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; return (git_index_reuc_entry *)entry; } static int index_entry_reuc_init(git_index_reuc_entry **reuc_out, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; assert(reuc_out && path); *reuc_out = reuc = reuc_entry_alloc(path); GITERR_CHECK_ALLOC(reuc); if ((reuc->mode[0] = ancestor_mode) > 0) { assert(ancestor_oid); git_oid_cpy(&reuc->oid[0], ancestor_oid); } if ((reuc->mode[1] = our_mode) > 0) { assert(our_oid); git_oid_cpy(&reuc->oid[1], our_oid); } if ((reuc->mode[2] = their_mode) > 0) { assert(their_oid); git_oid_cpy(&reuc->oid[2], their_oid); } return 0; } static void index_entry_cpy( git_index_entry *tgt, const git_index_entry *src) { const char *tgt_path = tgt->path; memcpy(tgt, src, sizeof(*tgt)); tgt->path = tgt_path; } static int index_entry_dup( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy(*out, src); return 0; } static void index_entry_cpy_nocache( git_index_entry *tgt, const git_index_entry *src) { git_oid_cpy(&tgt->id, &src->id); tgt->mode = src->mode; tgt->flags = src->flags; tgt->flags_extended = (src->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); } static int index_entry_dup_nocache( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy_nocache(*out, src); return 0; } static int has_file_name(git_index *index, const git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = 0; size_t len = strlen(entry->path); int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; while (pos < index->entries.length) { struct entry_internal *p = index->entries.contents[pos++]; if (len >= p->pathlen) break; if (memcmp(name, p->path, len)) break; if (GIT_IDXENTRY_STAGE(&p->entry) != stage) continue; if (p->path[len] != '/') continue; retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, --pos) < 0) break; } return retval; } /* * Do we have another file with a pathname that is a proper * subset of the name we're trying to add? */ static int has_dir_name(git_index *index, const git_index_entry *entry, int ok_to_replace) { int retval = 0; int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; const char *slash = name + strlen(name); for (;;) { size_t len, pos; for (;;) { if (*--slash == '/') break; if (slash <= entry->path) return retval; } len = slash - name; if (!index_find(&pos, index, name, len, stage)) { retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, pos) < 0) break; continue; } /* * Trivial optimization: if we find an entry that * already matches the sub-directory, then we know * we're ok, and we can exit. */ for (; pos < index->entries.length; ++pos) { struct entry_internal *p = index->entries.contents[pos]; if (p->pathlen <= len || p->path[len] != '/' || memcmp(p->path, name, len)) break; /* not our subdirectory */ if (GIT_IDXENTRY_STAGE(&p->entry) == stage) return retval; } } return retval; } static int check_file_directory_collision(git_index *index, git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = has_file_name(index, entry, pos, ok_to_replace); retval = retval + has_dir_name(index, entry, ok_to_replace); if (retval) { giterr_set(GITERR_INDEX, "'%s' appears as both a file and a directory", entry->path); return -1; } return 0; } static int canonicalize_directory_path( git_index *index, git_index_entry *entry, git_index_entry *existing) { const git_index_entry *match, *best = NULL; char *search, *sep; size_t pos, search_len, best_len; if (!index->ignore_case) return 0; /* item already exists in the index, simply re-use the existing case */ if (existing) { memcpy((char *)entry->path, existing->path, strlen(existing->path)); return 0; } /* nothing to do */ if (strchr(entry->path, '/') == NULL) return 0; if ((search = git__strdup(entry->path)) == NULL) return -1; /* starting at the parent directory and descending to the root, find the * common parent directory. */ while (!best && (sep = strrchr(search, '/'))) { sep[1] = '\0'; search_len = strlen(search); git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, search); while ((match = git_vector_get(&index->entries, pos))) { if (GIT_IDXENTRY_STAGE(match) != 0) { /* conflicts do not contribute to canonical paths */ } else if (strncmp(search, match->path, search_len) == 0) { /* prefer an exact match to the input filename */ best = match; best_len = search_len; break; } else if (strncasecmp(search, match->path, search_len) == 0) { /* continue walking, there may be a path with an exact * (case sensitive) match later in the index, but use this * as the best match until that happens. */ if (!best) { best = match; best_len = search_len; } } else { break; } pos++; } sep[0] = '\0'; } if (best) memcpy((char *)entry->path, best->path, best_len); git__free(search); return 0; } static int index_no_dups(void **old, void *new) { const git_index_entry *entry = new; GIT_UNUSED(old); giterr_set(GITERR_INDEX, "'%s' appears multiple times at stage %d", entry->path, GIT_IDXENTRY_STAGE(entry)); return GIT_EEXISTS; } static void index_existing_and_best( git_index_entry **existing, size_t *existing_position, git_index_entry **best, git_index *index, const git_index_entry *entry) { git_index_entry *e; size_t pos; int error; error = index_find(&pos, index, entry->path, 0, GIT_IDXENTRY_STAGE(entry)); if (error == 0) { *existing = index->entries.contents[pos]; *existing_position = pos; *best = index->entries.contents[pos]; return; } *existing = NULL; *existing_position = 0; *best = NULL; if (GIT_IDXENTRY_STAGE(entry) == 0) { for (; pos < index->entries.length; pos++) { int (*strcomp)(const char *a, const char *b) = index->ignore_case ? git__strcasecmp : git__strcmp; e = index->entries.contents[pos]; if (strcomp(entry->path, e->path) != 0) break; if (GIT_IDXENTRY_STAGE(e) == GIT_INDEX_STAGE_ANCESTOR) { *best = e; continue; } else { *best = e; break; } } } } /* index_insert takes ownership of the new entry - if it can't insert * it, then it will return an error **and also free the entry**. When * it replaces an existing entry, it will update the entry_ptr with the * actual entry in the index (and free the passed in one). * * trust_path is whether we use the given path, or whether (on case * insensitive systems only) we try to canonicalize the given path to * be within an existing directory. * * trust_mode is whether we trust the mode in entry_ptr. * * trust_id is whether we trust the id or it should be validated. */ static int index_insert( git_index *index, git_index_entry **entry_ptr, int replace, bool trust_path, bool trust_mode, bool trust_id) { int error = 0; size_t path_length, position; git_index_entry *existing, *best, *entry; assert(index && entry_ptr); entry = *entry_ptr; /* make sure that the path length flag is correct */ path_length = ((struct entry_internal *)entry)->pathlen; index_entry_adjust_namemask(entry, path_length); /* this entry is now up-to-date and should not be checked for raciness */ entry->flags_extended |= GIT_IDXENTRY_UPTODATE; git_vector_sort(&index->entries); /* look if an entry with this path already exists, either staged, or (if * this entry is a regular staged item) as the "ours" side of a conflict. */ index_existing_and_best(&existing, &position, &best, index, entry); /* update the file mode */ entry->mode = trust_mode ? git_index__create_mode(entry->mode) : index_merge_mode(index, best, entry->mode); /* canonicalize the directory name */ if (!trust_path) error = canonicalize_directory_path(index, entry, best); /* ensure that the given id exists (unless it's a submodule) */ if (!error && !trust_id && INDEX_OWNER(index) && (entry->mode & GIT_FILEMODE_COMMIT) != GIT_FILEMODE_COMMIT) { if (!git_object__is_valid(INDEX_OWNER(index), &entry->id, git_object__type_from_filemode(entry->mode))) error = -1; } /* look for tree / blob name collisions, removing conflicts if requested */ if (!error) error = check_file_directory_collision(index, entry, position, replace); if (error < 0) /* skip changes */; /* if we are replacing an existing item, overwrite the existing entry * and return it in place of the passed in one. */ else if (existing) { if (replace) { index_entry_cpy(existing, entry); if (trust_path) memcpy((char *)existing->path, entry->path, strlen(entry->path)); } index_entry_free(entry); *entry_ptr = entry = existing; } else { /* if replace is not requested or no existing entry exists, insert * at the sorted position. (Since we re-sort after each insert to * check for dups, this is actually cheaper in the long run.) */ error = git_vector_insert_sorted(&index->entries, entry, index_no_dups); if (error == 0) { INSERT_IN_MAP(index, entry, &error); } } if (error < 0) { index_entry_free(*entry_ptr); *entry_ptr = NULL; } return error; } static int index_conflict_to_reuc(git_index *index, const char *path) { const git_index_entry *conflict_entries[3]; int ancestor_mode, our_mode, their_mode; git_oid const *ancestor_oid, *our_oid, *their_oid; int ret; if ((ret = git_index_conflict_get(&conflict_entries[0], &conflict_entries[1], &conflict_entries[2], index, path)) < 0) return ret; ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode; our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode; their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode; ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id; our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id; their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id; if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) >= 0) ret = git_index_conflict_remove(index, path); return ret; } GIT_INLINE(bool) is_file_or_link(const int filemode) { return (filemode == GIT_FILEMODE_BLOB || filemode == GIT_FILEMODE_BLOB_EXECUTABLE || filemode == GIT_FILEMODE_LINK); } GIT_INLINE(bool) valid_filemode(const int filemode) { return (is_file_or_link(filemode) || filemode == GIT_FILEMODE_COMMIT); } int git_index_add_frombuffer( git_index *index, const git_index_entry *source_entry, const void *buffer, size_t len) { git_index_entry *entry = NULL; int error = 0; git_oid id; assert(index && source_entry->path); if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (!is_file_or_link(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid filemode"); return -1; } if (index_entry_dup(&entry, index, source_entry) < 0) return -1; error = git_blob_create_frombuffer(&id, INDEX_OWNER(index), buffer, len); if (error < 0) { index_entry_free(entry); return error; } git_oid_cpy(&entry->id, &id); entry->file_size = len; if ((error = index_insert(index, &entry, 1, true, true, true)) < 0) return error; /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND) return error; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } static int add_repo_as_submodule(git_index_entry **out, git_index *index, const char *path) { git_repository *sub; git_buf abspath = GIT_BUF_INIT; git_repository *repo = INDEX_OWNER(index); git_reference *head; git_index_entry *entry; struct stat st; int error; if (index_entry_create(&entry, INDEX_OWNER(index), path, true) < 0) return -1; if ((error = git_buf_joinpath(&abspath, git_repository_workdir(repo), path)) < 0) return error; if ((error = p_stat(abspath.ptr, &st)) < 0) { giterr_set(GITERR_OS, "failed to stat repository dir"); return -1; } git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); if ((error = git_repository_open(&sub, abspath.ptr)) < 0) return error; if ((error = git_repository_head(&head, sub)) < 0) return error; git_oid_cpy(&entry->id, git_reference_target(head)); entry->mode = GIT_FILEMODE_COMMIT; git_reference_free(head); git_repository_free(sub); git_buf_free(&abspath); *out = entry; return 0; } int git_index_add_bypath(git_index *index, const char *path) { git_index_entry *entry = NULL; int ret; assert(index && path); if ((ret = index_entry_init(&entry, index, path)) == 0) ret = index_insert(index, &entry, 1, false, false, true); /* If we were given a directory, let's see if it's a submodule */ if (ret < 0 && ret != GIT_EDIRECTORY) return ret; if (ret == GIT_EDIRECTORY) { git_submodule *sm; git_error_state err; giterr_state_capture(&err, ret); ret = git_submodule_lookup(&sm, INDEX_OWNER(index), path); if (ret == GIT_ENOTFOUND) return giterr_state_restore(&err); giterr_state_free(&err); /* * EEXISTS means that there is a repository at that path, but it's not known * as a submodule. We add its HEAD as an entry and don't register it. */ if (ret == GIT_EEXISTS) { if ((ret = add_repo_as_submodule(&entry, index, path)) < 0) return ret; if ((ret = index_insert(index, &entry, 1, false, false, true)) < 0) return ret; } else if (ret < 0) { return ret; } else { ret = git_submodule_add_to_index(sm, false); git_submodule_free(sm); return ret; } } /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove_bypath(git_index *index, const char *path) { int ret; assert(index && path); if (((ret = git_index_remove(index, path, 0)) < 0 && ret != GIT_ENOTFOUND) || ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)) return ret; if (ret == GIT_ENOTFOUND) giterr_clear(); return 0; } int git_index__fill(git_index *index, const git_vector *source_entries) { const git_index_entry *source_entry = NULL; size_t i; int ret = 0; assert(index); if (!source_entries->length) return 0; git_vector_size_hint(&index->entries, source_entries->length); git_idxmap_resize(index->entries_map, (khint_t)(source_entries->length * 1.3)); git_vector_foreach(source_entries, i, source_entry) { git_index_entry *entry = NULL; if ((ret = index_entry_dup(&entry, index, source_entry)) < 0) break; index_entry_adjust_namemask(entry, ((struct entry_internal *)entry)->pathlen); entry->flags_extended |= GIT_IDXENTRY_UPTODATE; entry->mode = git_index__create_mode(entry->mode); if ((ret = git_vector_insert(&index->entries, entry)) < 0) break; INSERT_IN_MAP(index, entry, &ret); if (ret < 0) break; } if (!ret) git_vector_sort(&index->entries); return ret; } int git_index_add(git_index *index, const git_index_entry *source_entry) { git_index_entry *entry = NULL; int ret; assert(index && source_entry && source_entry->path); if (!valid_filemode(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid entry mode"); return -1; } if ((ret = index_entry_dup(&entry, index, source_entry)) < 0 || (ret = index_insert(index, &entry, 1, true, true, false)) < 0) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove(git_index *index, const char *path, int stage) { int error; size_t position; git_index_entry remove_key = {{ 0 }}; remove_key.path = path; GIT_IDXENTRY_STAGE_SET(&remove_key, stage); DELETE_IN_MAP(index, &remove_key); if (index_find(&position, index, path, 0, stage) < 0) { giterr_set( GITERR_INDEX, "index does not contain %s at stage %d", path, stage); error = GIT_ENOTFOUND; } else { error = index_remove_entry(index, position); } return error; } int git_index_remove_directory(git_index *index, const char *dir, int stage) { git_buf pfx = GIT_BUF_INIT; int error = 0; size_t pos; git_index_entry *entry; if (!(error = git_buf_sets(&pfx, dir)) && !(error = git_path_to_dir(&pfx))) index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY); while (!error) { entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0) break; if (GIT_IDXENTRY_STAGE(entry) != stage) { ++pos; continue; } error = index_remove_entry(index, pos); /* removed entry at 'pos' so we don't need to increment */ } git_buf_free(&pfx); return error; } int git_index_find_prefix(size_t *at_pos, git_index *index, const char *prefix) { int error = 0; size_t pos; const git_index_entry *entry; index_find(&pos, index, prefix, strlen(prefix), GIT_INDEX_STAGE_ANY); entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, prefix) != 0) error = GIT_ENOTFOUND; if (!error && at_pos) *at_pos = pos; return error; } int git_index__find_pos( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { assert(index && path); return index_find(out, index, path, path_len, stage); } int git_index_find(size_t *at_pos, git_index *index, const char *path) { size_t pos; assert(index && path); if (git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, path) < 0) { giterr_set(GITERR_INDEX, "index does not contain %s", path); return GIT_ENOTFOUND; } /* Since our binary search only looked at path, we may be in the * middle of a list of stages. */ for (; pos > 0; --pos) { const git_index_entry *prev = git_vector_get(&index->entries, pos - 1); if (index->entries_cmp_path(prev->path, path) != 0) break; } if (at_pos) *at_pos = pos; return 0; } int git_index_conflict_add(git_index *index, const git_index_entry *ancestor_entry, const git_index_entry *our_entry, const git_index_entry *their_entry) { git_index_entry *entries[3] = { 0 }; unsigned short i; int ret = 0; assert (index); if ((ancestor_entry && (ret = index_entry_dup(&entries[0], index, ancestor_entry)) < 0) || (our_entry && (ret = index_entry_dup(&entries[1], index, our_entry)) < 0) || (their_entry && (ret = index_entry_dup(&entries[2], index, their_entry)) < 0)) goto on_error; /* Validate entries */ for (i = 0; i < 3; i++) { if (entries[i] && !valid_filemode(entries[i]->mode)) { giterr_set(GITERR_INDEX, "invalid filemode for stage %d entry", i + 1); return -1; } } /* Remove existing index entries for each path */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; if ((ret = git_index_remove(index, entries[i]->path, 0)) != 0) { if (ret != GIT_ENOTFOUND) goto on_error; giterr_clear(); ret = 0; } } /* Add the conflict entries */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; /* Make sure stage is correct */ GIT_IDXENTRY_STAGE_SET(entries[i], i + 1); if ((ret = index_insert(index, &entries[i], 1, true, true, false)) < 0) goto on_error; entries[i] = NULL; /* don't free if later entry fails */ } return 0; on_error: for (i = 0; i < 3; i++) { if (entries[i] != NULL) index_entry_free(entries[i]); } return ret; } static int index_conflict__get_byindex( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, size_t n) { const git_index_entry *conflict_entry; const char *path = NULL; size_t count; int stage, len = 0; assert(ancestor_out && our_out && their_out && index); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; for (count = git_index_entrycount(index); n < count; ++n) { conflict_entry = git_vector_get(&index->entries, n); if (path && index->entries_cmp_path(conflict_entry->path, path) != 0) break; stage = GIT_IDXENTRY_STAGE(conflict_entry); path = conflict_entry->path; switch (stage) { case 3: *their_out = conflict_entry; len++; break; case 2: *our_out = conflict_entry; len++; break; case 1: *ancestor_out = conflict_entry; len++; break; default: break; }; } return len; } int git_index_conflict_get( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, const char *path) { size_t pos; int len = 0; assert(ancestor_out && our_out && their_out && index && path); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; if (git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, index, pos)) < 0) return len; else if (len == 0) return GIT_ENOTFOUND; return 0; } static int index_conflict_remove(git_index *index, const char *path) { size_t pos = 0; git_index_entry *conflict_entry; int error = 0; if (path != NULL && git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) { if (path != NULL && index->entries_cmp_path(conflict_entry->path, path) != 0) break; if (GIT_IDXENTRY_STAGE(conflict_entry) == 0) { pos++; continue; } if ((error = index_remove_entry(index, pos)) < 0) break; } return error; } int git_index_conflict_remove(git_index *index, const char *path) { assert(index && path); return index_conflict_remove(index, path); } int git_index_conflict_cleanup(git_index *index) { assert(index); return index_conflict_remove(index, NULL); } int git_index_has_conflicts(const git_index *index) { size_t i; git_index_entry *entry; assert(index); git_vector_foreach(&index->entries, i, entry) { if (GIT_IDXENTRY_STAGE(entry) > 0) return 1; } return 0; } int git_index_conflict_iterator_new( git_index_conflict_iterator **iterator_out, git_index *index) { git_index_conflict_iterator *it = NULL; assert(iterator_out && index); it = git__calloc(1, sizeof(git_index_conflict_iterator)); GITERR_CHECK_ALLOC(it); it->index = index; *iterator_out = it; return 0; } int git_index_conflict_next( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index_conflict_iterator *iterator) { const git_index_entry *entry; int len; assert(ancestor_out && our_out && their_out && iterator); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; while (iterator->cur < iterator->index->entries.length) { entry = git_index_get_byindex(iterator->index, iterator->cur); if (git_index_entry_is_conflict(entry)) { if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, iterator->index, iterator->cur)) < 0) return len; iterator->cur += len; return 0; } iterator->cur++; } return GIT_ITEROVER; } void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator) { if (iterator == NULL) return; git__free(iterator); } size_t git_index_name_entrycount(git_index *index) { assert(index); return index->names.length; } const git_index_name_entry *git_index_name_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->names); return git_vector_get(&index->names, n); } static void index_name_entry_free(git_index_name_entry *ne) { if (!ne) return; git__free(ne->ancestor); git__free(ne->ours); git__free(ne->theirs); git__free(ne); } int git_index_name_add(git_index *index, const char *ancestor, const char *ours, const char *theirs) { git_index_name_entry *conflict_name; assert((ancestor && ours) || (ancestor && theirs) || (ours && theirs)); conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) || (ours && !(conflict_name->ours = git__strdup(ours))) || (theirs && !(conflict_name->theirs = git__strdup(theirs))) || git_vector_insert(&index->names, conflict_name) < 0) { index_name_entry_free(conflict_name); return -1; } return 0; } void git_index_name_clear(git_index *index) { size_t i; git_index_name_entry *conflict_name; assert(index); git_vector_foreach(&index->names, i, conflict_name) index_name_entry_free(conflict_name); git_vector_clear(&index->names); } size_t git_index_reuc_entrycount(git_index *index) { assert(index); return index->reuc.length; } static int index_reuc_on_dup(void **old, void *new) { index_entry_reuc_free(*old); *old = new; return GIT_EEXISTS; } static int index_reuc_insert( git_index *index, git_index_reuc_entry *reuc) { int res; assert(index && reuc && reuc->path != NULL); assert(git_vector_is_sorted(&index->reuc)); res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup); return res == GIT_EEXISTS ? 0 : res; } int git_index_reuc_add(git_index *index, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; int error = 0; assert(index && path); if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 || (error = index_reuc_insert(index, reuc)) < 0) index_entry_reuc_free(reuc); return error; } int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path) { return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path); } const git_index_reuc_entry *git_index_reuc_get_bypath( git_index *index, const char *path) { size_t pos; assert(index && path); if (!index->reuc.length) return NULL; assert(git_vector_is_sorted(&index->reuc)); if (git_index_reuc_find(&pos, index, path) < 0) return NULL; return git_vector_get(&index->reuc, pos); } const git_index_reuc_entry *git_index_reuc_get_byindex( git_index *index, size_t n) { assert(index); assert(git_vector_is_sorted(&index->reuc)); return git_vector_get(&index->reuc, n); } int git_index_reuc_remove(git_index *index, size_t position) { int error; git_index_reuc_entry *reuc; assert(git_vector_is_sorted(&index->reuc)); reuc = git_vector_get(&index->reuc, position); error = git_vector_remove(&index->reuc, position); if (!error) index_entry_reuc_free(reuc); return error; } void git_index_reuc_clear(git_index *index) { size_t i; assert(index); for (i = 0; i < index->reuc.length; ++i) index_entry_reuc_free(git__swap(index->reuc.contents[i], NULL)); git_vector_clear(&index->reuc); } static int index_error_invalid(const char *message) { giterr_set(GITERR_INDEX, "invalid data in index - %s", message); return -1; } static int read_reuc(git_index *index, const char *buffer, size_t size) { const char *endptr; size_t len; int i; /* If called multiple times, the vector might already be initialized */ if (index->reuc._alloc_size == 0 && git_vector_init(&index->reuc, 16, reuc_cmp) < 0) return -1; while (size) { git_index_reuc_entry *lost; len = p_strnlen(buffer, size) + 1; if (size <= len) return index_error_invalid("reading reuc entries"); lost = reuc_entry_alloc(buffer); GITERR_CHECK_ALLOC(lost); size -= len; buffer += len; /* read 3 ASCII octal numbers for stage entries */ for (i = 0; i < 3; i++) { int64_t tmp; if (git__strtol64(&tmp, buffer, &endptr, 8) < 0 || !endptr || endptr == buffer || *endptr || tmp < 0 || tmp > UINT32_MAX) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } lost->mode[i] = (uint32_t)tmp; len = (endptr + 1) - buffer; if (size <= len) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } size -= len; buffer += len; } /* read up to 3 OIDs for stage entries */ for (i = 0; i < 3; i++) { if (!lost->mode[i]) continue; if (size < 20) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry oid"); } git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer); size -= 20; buffer += 20; } /* entry was read successfully - insert into reuc vector */ if (git_vector_insert(&index->reuc, lost) < 0) return -1; } /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->reuc, true); return 0; } static int read_conflict_names(git_index *index, const char *buffer, size_t size) { size_t len; /* This gets called multiple times, the vector might already be initialized */ if (index->names._alloc_size == 0 && git_vector_init(&index->names, 16, conflict_name_cmp) < 0) return -1; #define read_conflict_name(ptr) \ len = p_strnlen(buffer, size) + 1; \ if (size < len) { \ index_error_invalid("reading conflict name entries"); \ goto out_err; \ } \ if (len == 1) \ ptr = NULL; \ else { \ ptr = git__malloc(len); \ GITERR_CHECK_ALLOC(ptr); \ memcpy(ptr, buffer, len); \ } \ \ buffer += len; \ size -= len; while (size) { git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); read_conflict_name(conflict_name->ancestor); read_conflict_name(conflict_name->ours); read_conflict_name(conflict_name->theirs); if (git_vector_insert(&index->names, conflict_name) < 0) goto out_err; continue; out_err: git__free(conflict_name->ancestor); git__free(conflict_name->ours); git__free(conflict_name->theirs); git__free(conflict_name); return -1; } #undef read_conflict_name /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->names, true); return 0; } static size_t index_entry_size(size_t path_len, size_t varint_len, uint32_t flags) { if (varint_len) { if (flags & GIT_IDXENTRY_EXTENDED) return offsetof(struct entry_long, path) + path_len + 1 + varint_len; else return offsetof(struct entry_short, path) + path_len + 1 + varint_len; } else { #define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7) if (flags & GIT_IDXENTRY_EXTENDED) return entry_size(struct entry_long, path_len); else return entry_size(struct entry_short, path_len); #undef entry_size } } static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len; size_t strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); size_t last_len = strlen(last); size_t prefix_len = last_len - strip_len; size_t suffix_len = strlen(path_ptr + varint_len); size_t path_len; if (varint_len == 0) return index_error_invalid("incorrect prefix length"); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } static int read_header(struct index_header *dest, const void *buffer) { const struct index_header *source = buffer; dest->signature = ntohl(source->signature); if (dest->signature != INDEX_HEADER_SIG) return index_error_invalid("incorrect header signature"); dest->version = ntohl(source->version); if (dest->version < INDEX_VERSION_NUMBER_LB || dest->version > INDEX_VERSION_NUMBER_UB) return index_error_invalid("incorrect header version"); dest->entry_count = ntohl(source->entry_count); return 0; } static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size) { struct index_extension dest; size_t total_size; /* buffer is not guaranteed to be aligned */ memcpy(&dest, buffer, sizeof(struct index_extension)); dest.extension_size = ntohl(dest.extension_size); total_size = dest.extension_size + sizeof(struct index_extension); if (dest.extension_size > total_size || buffer_size < total_size || buffer_size - total_size < INDEX_FOOTER_SIZE) return 0; /* optional extension */ if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') { /* tree cache */ if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) { if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) { if (read_reuc(index, buffer + 8, dest.extension_size) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) { if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0) return 0; } /* else, unsupported extension. We cannot parse this, but we can skip * it by returning `total_size */ } else { /* we cannot handle non-ignorable extensions; * in fact they aren't even defined in the standard */ return 0; } return total_size; } static int parse_index(git_index *index, const char *buffer, size_t buffer_size) { int error = 0; unsigned int i; struct index_header header = { 0 }; git_oid checksum_calculated, checksum_expected; const char *last = NULL; const char *empty = ""; #define seek_forward(_increase) { \ if (_increase >= buffer_size) { \ error = index_error_invalid("ran out of data while parsing"); \ goto done; } \ buffer += _increase; \ buffer_size -= _increase;\ } if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE) return index_error_invalid("insufficient buffer space"); /* Precalculate the SHA1 of the files's contents -- we'll match it to * the provided SHA1 in the footer */ git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE); /* Parse header */ if ((error = read_header(&header, buffer)) < 0) return error; index->version = header.version; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = empty; seek_forward(INDEX_HEADER_SIZE); assert(!index->entries.length); if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count); else git_idxmap_resize(index->entries_map, header.entry_count); /* Parse all the entries */ for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) { git_index_entry *entry = NULL; size_t entry_size; if ((error = read_entry(&entry, &entry_size, index, buffer, buffer_size, last)) < 0) { error = index_error_invalid("invalid entry"); goto done; } if ((error = git_vector_insert(&index->entries, entry)) < 0) { index_entry_free(entry); goto done; } INSERT_IN_MAP(index, entry, &error); if (error < 0) { index_entry_free(entry); goto done; } error = 0; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; seek_forward(entry_size); } if (i != header.entry_count) { error = index_error_invalid("header entries changed while parsing"); goto done; } /* There's still space for some extensions! */ while (buffer_size > INDEX_FOOTER_SIZE) { size_t extension_size; extension_size = read_extension(index, buffer, buffer_size); /* see if we have read any bytes from the extension */ if (extension_size == 0) { error = index_error_invalid("extension is truncated"); goto done; } seek_forward(extension_size); } if (buffer_size != INDEX_FOOTER_SIZE) { error = index_error_invalid( "buffer size does not match index footer size"); goto done; } /* 160-bit SHA-1 over the content of the index file before this checksum. */ git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer); if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) { error = index_error_invalid( "calculated checksum does not match expected"); goto done; } git_oid_cpy(&index->checksum, &checksum_calculated); #undef seek_forward /* Entries are stored case-sensitively on disk, so re-sort now if * in-memory index is supposed to be case-insensitive */ git_vector_set_sorted(&index->entries, !index->ignore_case); git_vector_sort(&index->entries); done: return error; } static bool is_index_extended(git_index *index) { size_t i, extended; git_index_entry *entry; extended = 0; git_vector_foreach(&index->entries, i, entry) { entry->flags &= ~GIT_IDXENTRY_EXTENDED; if (entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS) { extended++; entry->flags |= GIT_IDXENTRY_EXTENDED; } } return (extended > 0); } static int write_disk_entry(git_filebuf *file, git_index_entry *entry, const char *last) { void *mem = NULL; struct entry_short *ondisk; size_t path_len, disk_size; int varint_len = 0; char *path; const char *path_start = entry->path; size_t same_len = 0; path_len = ((struct entry_internal *)entry)->pathlen; if (last) { const char *last_c = last; while (*path_start == *last_c) { if (!*path_start || !*last_c) break; ++path_start; ++last_c; ++same_len; } path_len -= same_len; varint_len = git_encode_varint(NULL, 0, same_len); } disk_size = index_entry_size(path_len, varint_len, entry->flags); if (git_filebuf_reserve(file, &mem, disk_size) < 0) return -1; ondisk = (struct entry_short *)mem; memset(ondisk, 0x0, disk_size); /** * Yes, we have to truncate. * * The on-disk format for Index entries clearly defines * the time and size fields to be 4 bytes each -- so even if * we store these values with 8 bytes on-memory, they must * be truncated to 4 bytes before writing to disk. * * In 2038 I will be either too dead or too rich to care about this */ ondisk->ctime.seconds = htonl((uint32_t)entry->ctime.seconds); ondisk->mtime.seconds = htonl((uint32_t)entry->mtime.seconds); ondisk->ctime.nanoseconds = htonl(entry->ctime.nanoseconds); ondisk->mtime.nanoseconds = htonl(entry->mtime.nanoseconds); ondisk->dev = htonl(entry->dev); ondisk->ino = htonl(entry->ino); ondisk->mode = htonl(entry->mode); ondisk->uid = htonl(entry->uid); ondisk->gid = htonl(entry->gid); ondisk->file_size = htonl((uint32_t)entry->file_size); git_oid_cpy(&ondisk->oid, &entry->id); ondisk->flags = htons(entry->flags); if (entry->flags & GIT_IDXENTRY_EXTENDED) { struct entry_long *ondisk_ext; ondisk_ext = (struct entry_long *)ondisk; ondisk_ext->flags_extended = htons(entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); path = ondisk_ext->path; disk_size -= offsetof(struct entry_long, path); } else { path = ondisk->path; disk_size -= offsetof(struct entry_short, path); } if (last) { varint_len = git_encode_varint((unsigned char *) path, disk_size, same_len); assert(varint_len > 0); path += varint_len; disk_size -= varint_len; /* * If using path compression, we are not allowed * to have additional trailing NULs. */ assert(disk_size == path_len + 1); } else { /* * If no path compression is used, we do have * NULs as padding. As such, simply assert that * we have enough space left to write the path. */ assert(disk_size > path_len); } memcpy(path, path_start, path_len + 1); return 0; } static int write_entries(git_index *index, git_filebuf *file) { int error = 0; size_t i; git_vector case_sorted, *entries; git_index_entry *entry; const char *last = NULL; /* If index->entries is sorted case-insensitively, then we need * to re-sort it case-sensitively before writing */ if (index->ignore_case) { git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp); git_vector_sort(&case_sorted); entries = &case_sorted; } else { entries = &index->entries; } if (index->version >= INDEX_VERSION_NUMBER_COMP) last = ""; git_vector_foreach(entries, i, entry) { if ((error = write_disk_entry(file, entry, last)) < 0) break; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; } if (index->ignore_case) git_vector_free(&case_sorted); return error; } static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data) { struct index_extension ondisk; memset(&ondisk, 0x0, sizeof(struct index_extension)); memcpy(&ondisk, header, 4); ondisk.extension_size = htonl(header->extension_size); git_filebuf_write(file, &ondisk, sizeof(struct index_extension)); return git_filebuf_write(file, data->ptr, data->size); } static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name) { int error = 0; if (conflict_name->ancestor == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1); if (error != 0) goto on_error; if (conflict_name->ours == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1); if (error != 0) goto on_error; if (conflict_name->theirs == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1); on_error: return error; } static int write_name_extension(git_index *index, git_filebuf *file) { git_buf name_buf = GIT_BUF_INIT; git_vector *out = &index->names; git_index_name_entry *conflict_name; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, conflict_name) { if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4); extension.extension_size = (uint32_t)name_buf.size; error = write_extension(file, &extension, &name_buf); git_buf_free(&name_buf); done: return error; } static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc) { int i; int error = 0; if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0) return error; for (i = 0; i < 3; i++) { if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 || (error = git_buf_put(reuc_buf, "\0", 1)) < 0) return error; } for (i = 0; i < 3; i++) { if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0) return error; } return 0; } static int write_reuc_extension(git_index *index, git_filebuf *file) { git_buf reuc_buf = GIT_BUF_INIT; git_vector *out = &index->reuc; git_index_reuc_entry *reuc; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, reuc) { if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4); extension.extension_size = (uint32_t)reuc_buf.size; error = write_extension(file, &extension, &reuc_buf); git_buf_free(&reuc_buf); done: return error; } static int write_tree_extension(git_index *index, git_filebuf *file) { struct index_extension extension; git_buf buf = GIT_BUF_INIT; int error; if (index->tree == NULL) return 0; if ((error = git_tree_cache_write(&buf, index->tree)) < 0) return error; memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4); extension.extension_size = (uint32_t)buf.size; error = write_extension(file, &extension, &buf); git_buf_free(&buf); return error; } static void clear_uptodate(git_index *index) { git_index_entry *entry; size_t i; git_vector_foreach(&index->entries, i, entry) entry->flags_extended &= ~GIT_IDXENTRY_UPTODATE; } static int write_index(git_oid *checksum, git_index *index, git_filebuf *file) { git_oid hash_final; struct index_header header; bool is_extended; uint32_t index_version_number; assert(index && file); if (index->version <= INDEX_VERSION_NUMBER_EXT) { is_extended = is_index_extended(index); index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER_LB; } else { index_version_number = index->version; } header.signature = htonl(INDEX_HEADER_SIG); header.version = htonl(index_version_number); header.entry_count = htonl((uint32_t)index->entries.length); if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0) return -1; if (write_entries(index, file) < 0) return -1; /* write the tree cache extension */ if (index->tree != NULL && write_tree_extension(index, file) < 0) return -1; /* write the rename conflict extension */ if (index->names.length > 0 && write_name_extension(index, file) < 0) return -1; /* write the reuc extension */ if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0) return -1; /* get out the hash for all the contents we've appended to the file */ git_filebuf_hash(&hash_final, file); git_oid_cpy(checksum, &hash_final); /* write it at the end of the file */ if (git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ) < 0) return -1; /* file entries are no longer up to date */ clear_uptodate(index); return 0; } int git_index_entry_stage(const git_index_entry *entry) { return GIT_IDXENTRY_STAGE(entry); } int git_index_entry_is_conflict(const git_index_entry *entry) { return (GIT_IDXENTRY_STAGE(entry) > 0); } typedef struct read_tree_data { git_index *index; git_vector *old_entries; git_vector *new_entries; git_vector_cmp entry_cmp; git_tree_cache *tree; } read_tree_data; static int read_tree_cb( const char *root, const git_tree_entry *tentry, void *payload) { read_tree_data *data = payload; git_index_entry *entry = NULL, *old_entry; git_buf path = GIT_BUF_INIT; size_t pos; if (git_tree_entry__is_tree(tentry)) return 0; if (git_buf_joinpath(&path, root, tentry->filename) < 0) return -1; if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr, false) < 0) return -1; entry->mode = tentry->attr; git_oid_cpy(&entry->id, git_tree_entry_id(tentry)); /* look for corresponding old entry and copy data to new entry */ if (data->old_entries != NULL && !index_find_in_entries( &pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) && (old_entry = git_vector_get(data->old_entries, pos)) != NULL && entry->mode == old_entry->mode && git_oid_equal(&entry->id, &old_entry->id)) { index_entry_cpy(entry, old_entry); entry->flags_extended = 0; } index_entry_adjust_namemask(entry, path.size); git_buf_free(&path); if (git_vector_insert(data->new_entries, entry) < 0) { index_entry_free(entry); return -1; } return 0; } int git_index_read_tree(git_index *index, const git_tree *tree) { int error = 0; git_vector entries = GIT_VECTOR_INIT; git_idxmap *entries_map; read_tree_data data; size_t i; git_index_entry *e; if (git_idxmap_alloc(&entries_map) < 0) return -1; git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */ data.index = index; data.old_entries = &index->entries; data.new_entries = &entries; data.entry_cmp = index->entries_search; index->tree = NULL; git_pool_clear(&index->tree_pool); git_vector_sort(&index->entries); if ((error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data)) < 0) goto cleanup; if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) entries_map, entries.length); else git_idxmap_resize(entries_map, entries.length); git_vector_foreach(&entries, i, e) { INSERT_IN_MAP_EX(index, entries_map, e, &error); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry into map"); return error; } } error = 0; git_vector_sort(&entries); if ((error = git_index_clear(index)) < 0) { /* well, this isn't good */; } else { git_vector_swap(&entries, &index->entries); entries_map = git__swap(index->entries_map, entries_map); } cleanup: git_vector_free(&entries); git_idxmap_free(entries_map); if (error < 0) return error; error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool); return error; } static int git_index_read_iterator( git_index *index, git_iterator *new_iterator, size_t new_length_hint) { git_vector new_entries = GIT_VECTOR_INIT, remove_entries = GIT_VECTOR_INIT; git_idxmap *new_entries_map = NULL; git_iterator *index_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *old_entry, *new_entry; git_index_entry *entry; size_t i; int error; assert((new_iterator->flags & GIT_ITERATOR_DONT_IGNORE_CASE)); if ((error = git_vector_init(&new_entries, new_length_hint, index->entries._cmp)) < 0 || (error = git_vector_init(&remove_entries, index->entries.length, NULL)) < 0 || (error = git_idxmap_alloc(&new_entries_map)) < 0) goto done; if (index->ignore_case && new_length_hint) git_idxmap_icase_resize((khash_t(idxicase) *) new_entries_map, new_length_hint); else if (new_length_hint) git_idxmap_resize(new_entries_map, new_length_hint); opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&index_iterator, git_index_owner(index), index, &opts)) < 0 || ((error = git_iterator_current(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) || ((error = git_iterator_current(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER)) goto done; while (true) { git_index_entry *dup_entry = NULL, *add_entry = NULL, *remove_entry = NULL; int diff; error = 0; if (old_entry && new_entry) diff = git_index_entry_cmp(old_entry, new_entry); else if (!old_entry && new_entry) diff = 1; else if (old_entry && !new_entry) diff = -1; else break; if (diff < 0) { remove_entry = (git_index_entry *)old_entry; } else if (diff > 0) { dup_entry = (git_index_entry *)new_entry; } else { /* Path and stage are equal, if the OID is equal, keep it to * keep the stat cache data. */ if (git_oid_equal(&old_entry->id, &new_entry->id) && old_entry->mode == new_entry->mode) { add_entry = (git_index_entry *)old_entry; } else { dup_entry = (git_index_entry *)new_entry; remove_entry = (git_index_entry *)old_entry; } } if (dup_entry) { if ((error = index_entry_dup_nocache(&add_entry, index, dup_entry)) < 0) goto done; index_entry_adjust_namemask(add_entry, ((struct entry_internal *)add_entry)->pathlen); } /* invalidate this path in the tree cache if this is new (to * invalidate the parent trees) */ if (dup_entry && !remove_entry && index->tree) git_tree_cache_invalidate_path(index->tree, dup_entry->path); if (add_entry) { if ((error = git_vector_insert(&new_entries, add_entry)) == 0) INSERT_IN_MAP_EX(index, new_entries_map, add_entry, &error); } if (remove_entry && error >= 0) error = git_vector_insert(&remove_entries, remove_entry); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry"); goto done; } if (diff <= 0) { if ((error = git_iterator_advance(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) goto done; } if (diff >= 0) { if ((error = git_iterator_advance(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER) goto done; } } git_index_name_clear(index); git_index_reuc_clear(index); git_vector_swap(&new_entries, &index->entries); new_entries_map = git__swap(index->entries_map, new_entries_map); git_vector_foreach(&remove_entries, i, entry) { if (index->tree) git_tree_cache_invalidate_path(index->tree, entry->path); index_entry_free(entry); } clear_uptodate(index); error = 0; done: git_idxmap_free(new_entries_map); git_vector_free(&new_entries); git_vector_free(&remove_entries); git_iterator_free(index_iterator); return error; } int git_index_read_index( git_index *index, const git_index *new_index) { git_iterator *new_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; int error; opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&new_iterator, git_index_owner(new_index), (git_index *)new_index, &opts)) < 0 || (error = git_index_read_iterator(index, new_iterator, new_index->entries.length)) < 0) goto done; done: git_iterator_free(new_iterator); return error; } git_repository *git_index_owner(const git_index *index) { return INDEX_OWNER(index); } enum { INDEX_ACTION_NONE = 0, INDEX_ACTION_UPDATE = 1, INDEX_ACTION_REMOVE = 2, INDEX_ACTION_ADDALL = 3, }; int git_index_add_all( git_index *index, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_repository *repo; git_iterator *wditer = NULL; git_pathspec ps; bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0; assert(index); repo = INDEX_OWNER(index); if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0) return error; if ((error = git_pathspec__init(&ps, paths)) < 0) return error; /* optionally check that pathspec doesn't mention any ignored files */ if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 && (flags & GIT_INDEX_ADD_FORCE) == 0 && (error = git_ignore__check_pathspec_for_exact_ignores( repo, &ps.pathspec, no_fnmatch)) < 0) goto cleanup; error = index_apply_to_wd_diff(index, INDEX_ACTION_ADDALL, paths, flags, cb, payload); if (error) giterr_set_after_callback(error); cleanup: git_iterator_free(wditer); git_pathspec__clear(&ps); return error; } struct foreach_diff_data { git_index *index; const git_pathspec *pathspec; unsigned int flags; git_index_matched_path_cb cb; void *payload; }; static int apply_each_file(const git_diff_delta *delta, float progress, void *payload) { struct foreach_diff_data *data = payload; const char *match, *path; int error = 0; GIT_UNUSED(progress); path = delta->old_file.path; /* We only want those which match the pathspecs */ if (!git_pathspec__match( &data->pathspec->pathspec, path, false, (bool)data->index->ignore_case, &match, NULL)) return 0; if (data->cb) error = data->cb(path, match, data->payload); if (error > 0) /* skip this entry */ return 0; if (error < 0) /* actual error */ return error; /* If the workdir item does not exist, remove it from the index. */ if ((delta->new_file.flags & GIT_DIFF_FLAG_EXISTS) == 0) error = git_index_remove_bypath(data->index, path); else error = git_index_add_bypath(data->index, delta->new_file.path); return error; } static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_diff *diff; git_pathspec ps; git_repository *repo; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct foreach_diff_data data = { index, NULL, flags, cb, payload, }; assert(index); assert(action == INDEX_ACTION_UPDATE || action == INDEX_ACTION_ADDALL); repo = INDEX_OWNER(index); if (!repo) { return create_index_error(-1, "cannot run update; the index is not backed up by a repository."); } /* * We do the matching ourselves intead of passing the list to * diff because we want to tell the callback which one * matched, which we do not know if we ask diff to filter for us. */ if ((error = git_pathspec__init(&ps, paths)) < 0) return error; opts.flags = GIT_DIFF_INCLUDE_TYPECHANGE; if (action == INDEX_ACTION_ADDALL) { opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_RECURSE_UNTRACKED_DIRS; if (flags == GIT_INDEX_ADD_FORCE) opts.flags |= GIT_DIFF_INCLUDE_IGNORED; } if ((error = git_diff_index_to_workdir(&diff, repo, index, &opts)) < 0) goto cleanup; data.pathspec = &ps; error = git_diff_foreach(diff, apply_each_file, NULL, NULL, NULL, &data); git_diff_free(diff); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); cleanup: git_pathspec__clear(&ps); return error; } static int index_apply_to_all( git_index *index, int action, const git_strarray *paths, git_index_matched_path_cb cb, void *payload) { int error = 0; size_t i; git_pathspec ps; const char *match; git_buf path = GIT_BUF_INIT; assert(index); if ((error = git_pathspec__init(&ps, paths)) < 0) return error; git_vector_sort(&index->entries); for (i = 0; !error && i < index->entries.length; ++i) { git_index_entry *entry = git_vector_get(&index->entries, i); /* check if path actually matches */ if (!git_pathspec__match( &ps.pathspec, entry->path, false, (bool)index->ignore_case, &match, NULL)) continue; /* issue notification callback if requested */ if (cb && (error = cb(entry->path, match, payload)) != 0) { if (error > 0) { /* return > 0 means skip this one */ error = 0; continue; } if (error < 0) /* return < 0 means abort */ break; } /* index manipulation may alter entry, so don't depend on it */ if ((error = git_buf_sets(&path, entry->path)) < 0) break; switch (action) { case INDEX_ACTION_NONE: break; case INDEX_ACTION_UPDATE: error = git_index_add_bypath(index, path.ptr); if (error == GIT_ENOTFOUND) { giterr_clear(); error = git_index_remove_bypath(index, path.ptr); if (!error) /* back up foreach if we removed this */ i--; } break; case INDEX_ACTION_REMOVE: if (!(error = git_index_remove_bypath(index, path.ptr))) i--; /* back up foreach if we removed this */ break; default: giterr_set(GITERR_INVALID, "unknown index action %d", action); error = -1; break; } } git_buf_free(&path); git_pathspec__clear(&ps); return error; } int git_index_remove_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_all( index, INDEX_ACTION_REMOVE, pathspec, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_update_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_wd_diff(index, INDEX_ACTION_UPDATE, pathspec, 0, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_snapshot_new(git_vector *snap, git_index *index) { int error; GIT_REFCOUNT_INC(index); git_atomic_inc(&index->readers); git_vector_sort(&index->entries); error = git_vector_dup(snap, &index->entries, index->entries._cmp); if (error < 0) git_index_free(index); return error; } void git_index_snapshot_release(git_vector *snap, git_index *index) { git_vector_free(snap); git_atomic_dec(&index->readers); git_index_free(index); } int git_index_snapshot_find( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { return index_find_in_entries(out, entries, entry_srch, path, path_len, stage); } int git_indexwriter_init( git_indexwriter *writer, git_index *index) { int error; GIT_REFCOUNT_INC(index); writer->index = index; if (!index->index_file_path) return create_index_error(-1, "failed to write index: The index is in-memory only"); if ((error = git_filebuf_open( &writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) { if (error == GIT_ELOCKED) giterr_set(GITERR_INDEX, "the index is locked; this might be due to a concurrent or crashed process"); return error; } writer->should_write = 1; return 0; } int git_indexwriter_init_for_operation( git_indexwriter *writer, git_repository *repo, unsigned int *checkout_strategy) { git_index *index; int error; if ((error = git_repository_index__weakptr(&index, repo)) < 0 || (error = git_indexwriter_init(writer, index)) < 0) return error; writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0; *checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX; return 0; } int git_indexwriter_commit(git_indexwriter *writer) { int error; git_oid checksum = {{ 0 }}; if (!writer->should_write) return 0; git_vector_sort(&writer->index->entries); git_vector_sort(&writer->index->reuc); if ((error = write_index(&checksum, writer->index, &writer->file)) < 0) { git_indexwriter_cleanup(writer); return error; } if ((error = git_filebuf_commit(&writer->file)) < 0) return error; if ((error = git_futils_filestamp_check( &writer->index->stamp, writer->index->index_file_path)) < 0) { giterr_set(GITERR_OS, "could not read index timestamp"); return -1; } writer->index->on_disk = 1; git_oid_cpy(&writer->index->checksum, &checksum); git_index_free(writer->index); writer->index = NULL; return 0; } void git_indexwriter_cleanup(git_indexwriter *writer) { git_filebuf_cleanup(&writer->file); git_index_free(writer->index); writer->index = NULL; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_664_0
crossvul-cpp_data_good_5480_2
/* $Id$ */ /* tiffcrop.c -- a port of tiffcp.c extended to include manipulations of * the image data through additional options listed below * * Original code: * Copyright (c) 1988-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * Additions (c) Richard Nolde 2006-2010 * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS OR ANY OTHER COPYRIGHT * HOLDERS BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL * DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND * ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOFTWARE. * * Some portions of the current code are derived from tiffcp, primarly in * the areas of lowlevel reading and writing of TAGS, scanlines and tiles though * some of the original functions have been extended to support arbitrary bit * depths. These functions are presented at the top of this file. * * Add support for the options below to extract sections of image(s) * and to modify the whole image or selected portions of each image by * rotations, mirroring, and colorscale/colormap inversion of selected * types of TIFF images when appropriate. Some color model dependent * functions are restricted to bilevel or 8 bit per sample data. * See the man page for the full explanations. * * New Options: * -h Display the syntax guide. * -v Report the version and last build date for tiffcrop and libtiff. * -z x1,y1,x2,y2:x3,y3,x4,y4:..xN,yN,xN + 1, yN + 1 * Specify a series of coordinates to define rectangular * regions by the top left and lower right corners. * -e c|d|i|m|s export mode for images and selections from input images * combined All images and selections are written to a single file (default) * with multiple selections from one image combined into a single image * divided All images and selections are written to a single file * with each selection from one image written to a new image * image Each input image is written to a new file (numeric filename sequence) * with multiple selections from the image combined into one image * multiple Each input image is written to a new file (numeric filename sequence) * with each selection from the image written to a new image * separated Individual selections from each image are written to separate files * -U units [in, cm, px ] inches, centimeters or pixels * -H # Set horizontal resolution of output images to # * -V # Set vertical resolution of output images to # * -J # Horizontal margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -K # Vertical margin of output page to # expressed in current * units when sectioning image into columns x rows * using the -S cols:rows option. * -X # Horizontal dimension of region to extract expressed in current * units * -Y # Vertical dimension of region to extract expressed in current * units * -O orient Orientation for output image, portrait, landscape, auto * -P page Page size for output image segments, eg letter, legal, tabloid, * etc. * -S cols:rows Divide the image into equal sized segments using cols across * and rows down * -E t|l|r|b Edge to use as origin * -m #,#,#,# Margins from edges for selection: top, left, bottom, right * (commas separated) * -Z #:#,#:# Zones of the image designated as zone X of Y, * eg 1:3 would be first of three equal portions measured * from reference edge * -N odd|even|#,#-#,#|last * Select sequences and/or ranges of images within file * to process. The words odd or even may be used to specify * all odd or even numbered images the word last may be used * in place of a number in the sequence to indicate the final * image in the file without knowing how many images there are. * -R # Rotate image or crop selection by 90,180,or 270 degrees * clockwise * -F h|v Flip (mirror) image or crop selection horizontally * or vertically * -I [black|white|data|both] * Invert color space, eg dark to light for bilevel and grayscale images * If argument is white or black, set the PHOTOMETRIC_INTERPRETATION * tag to MinIsBlack or MinIsWhite without altering the image data * If the argument is data or both, the image data are modified: * both inverts the data and the PHOTOMETRIC_INTERPRETATION tag, * data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag * -D input:<filename1>,output:<filename2>,format:<raw|txt>,level:N,debug:N * Dump raw data for input and/or output images to individual files * in raw (binary) format or text (ASCII) representing binary data * as strings of 1s and 0s. The filename arguments are used as stems * from which individual files are created for each image. Text format * includes annotations for image parameters and scanline info. Level * selects which functions dump data, with higher numbers selecting * lower level, scanline level routines. Debug reports a limited set * of messages to monitor progess without enabling dump logs. */ static char tiffcrop_version_id[] = "2.4"; static char tiffcrop_rev_date[] = "12-13-2010"; #include "tif_config.h" #include "tiffiop.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <ctype.h> #include <limits.h> #include <sys/stat.h> #include <assert.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef HAVE_STDINT_H # include <stdint.h> #endif #ifndef HAVE_GETOPT extern int getopt(int argc, char * const argv[], const char *optstring); #endif #ifdef NEED_LIBPORT # include "libport.h" #endif #include "tiffio.h" #if defined(VMS) # define unlink delete #endif #ifndef PATH_MAX #define PATH_MAX 1024 #endif #ifndef streq #define streq(a,b) (strcmp((a),(b)) == 0) #endif #define strneq(a,b,n) (strncmp((a),(b),(n)) == 0) #define TRUE 1 #define FALSE 0 #ifndef TIFFhowmany #define TIFFhowmany(x, y) ((((uint32)(x))+(((uint32)(y))-1))/((uint32)(y))) #define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) #endif /* * Definitions and data structures required to support cropping and image * manipulations. */ #define EDGE_TOP 1 #define EDGE_LEFT 2 #define EDGE_BOTTOM 3 #define EDGE_RIGHT 4 #define EDGE_CENTER 5 #define MIRROR_HORIZ 1 #define MIRROR_VERT 2 #define MIRROR_BOTH 3 #define ROTATECW_90 8 #define ROTATECW_180 16 #define ROTATECW_270 32 #define ROTATE_ANY (ROTATECW_90 | ROTATECW_180 | ROTATECW_270) #define CROP_NONE 0 #define CROP_MARGINS 1 #define CROP_WIDTH 2 #define CROP_LENGTH 4 #define CROP_ZONES 8 #define CROP_REGIONS 16 #define CROP_ROTATE 32 #define CROP_MIRROR 64 #define CROP_INVERT 128 /* Modes for writing out images and selections */ #define ONE_FILE_COMPOSITE 0 /* One file, sections combined sections */ #define ONE_FILE_SEPARATED 1 /* One file, sections to new IFDs */ #define FILE_PER_IMAGE_COMPOSITE 2 /* One file per image, combined sections */ #define FILE_PER_IMAGE_SEPARATED 3 /* One file per input image */ #define FILE_PER_SELECTION 4 /* One file per selection */ #define COMPOSITE_IMAGES 0 /* Selections combined into one image */ #define SEPARATED_IMAGES 1 /* Selections saved to separate images */ #define STRIP 1 #define TILE 2 #define MAX_REGIONS 8 /* number of regions to extract from a single page */ #define MAX_OUTBUFFS 8 /* must match larger of zones or regions */ #define MAX_SECTIONS 32 /* number of sections per page to write to output */ #define MAX_IMAGES 2048 /* number of images in descrete list, not in the file */ #define MAX_SAMPLES 8 /* maximum number of samples per pixel supported */ #define MAX_BITS_PER_SAMPLE 64 /* maximum bit depth supported */ #define MAX_EXPORT_PAGES 999999 /* maximum number of export pages per file */ #define DUMP_NONE 0 #define DUMP_TEXT 1 #define DUMP_RAW 2 /* Offsets into buffer for margins and fixed width and length segments */ struct offset { uint32 tmargin; uint32 lmargin; uint32 bmargin; uint32 rmargin; uint32 crop_width; uint32 crop_length; uint32 startx; uint32 endx; uint32 starty; uint32 endy; }; /* Description of a zone within the image. Position 1 of 3 zones would be * the first third of the image. These are computed after margins and * width/length requests are applied so that you can extract multiple * zones from within a larger region for OCR or barcode recognition. */ struct buffinfo { uint32 size; /* size of this buffer */ unsigned char *buffer; /* address of the allocated buffer */ }; struct zone { int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ }; struct pageseg { uint32 x1; /* index of left edge */ uint32 x2; /* index of right edge */ uint32 y1; /* index of top edge */ uint32 y2; /* index of bottom edge */ int position; /* ordinal of segment to be extracted */ int total; /* total equal sized divisions of crop area */ uint32 buffsize; /* size of buffer needed to hold the cropped zone */ }; struct coordpairs { double X1; /* index of left edge in current units */ double X2; /* index of right edge in current units */ double Y1; /* index of top edge in current units */ double Y2; /* index of bottom edge in current units */ }; struct region { uint32 x1; /* pixel offset of left edge */ uint32 x2; /* pixel offset of right edge */ uint32 y1; /* pixel offset of top edge */ uint32 y2; /* picel offset of bottom edge */ uint32 width; /* width in pixels */ uint32 length; /* length in pixels */ uint32 buffsize; /* size of buffer needed to hold the cropped region */ unsigned char *buffptr; /* address of start of the region */ }; /* Cropping parameters from command line and image data * Note: This should be renamed to proc_opts and expanded to include all current globals * if possible, but each function that accesses global variables will have to be redone. */ struct crop_mask { double width; /* Selection width for master crop region in requested units */ double length; /* Selection length for master crop region in requesed units */ double margins[4]; /* Top, left, bottom, right margins */ float xres; /* Horizontal resolution read from image*/ float yres; /* Vertical resolution read from image */ uint32 combined_width; /* Width of combined cropped zones */ uint32 combined_length; /* Length of combined cropped zones */ uint32 bufftotal; /* Size of buffer needed to hold all the cropped region */ uint16 img_mode; /* Composite or separate images created from zones or regions */ uint16 exp_mode; /* Export input images or selections to one or more files */ uint16 crop_mode; /* Crop options to be applied */ uint16 res_unit; /* Resolution unit for margins and selections */ uint16 edge_ref; /* Reference edge for sections extraction and combination */ uint16 rotation; /* Clockwise rotation of the extracted region or image */ uint16 mirror; /* Mirror extracted region or image horizontally or vertically */ uint16 invert; /* Invert the color map of image or region */ uint16 photometric; /* Status of photometric interpretation for inverted image */ uint16 selections; /* Number of regions or zones selected */ uint16 regions; /* Number of regions delimited by corner coordinates */ struct region regionlist[MAX_REGIONS]; /* Regions within page or master crop region */ uint16 zones; /* Number of zones delimited by Ordinal:Total requested */ struct zone zonelist[MAX_REGIONS]; /* Zones indices to define a region */ struct coordpairs corners[MAX_REGIONS]; /* Coordinates of upper left and lower right corner */ }; #define MAX_PAPERNAMES 49 #define MAX_PAPERNAME_LENGTH 15 #define DEFAULT_RESUNIT RESUNIT_INCH #define DEFAULT_PAGE_HEIGHT 14.0 #define DEFAULT_PAGE_WIDTH 8.5 #define DEFAULT_RESOLUTION 300 #define DEFAULT_PAPER_SIZE "legal" #define ORIENTATION_NONE 0 #define ORIENTATION_PORTRAIT 1 #define ORIENTATION_LANDSCAPE 2 #define ORIENTATION_SEASCAPE 4 #define ORIENTATION_AUTO 16 #define PAGE_MODE_NONE 0 #define PAGE_MODE_RESOLUTION 1 #define PAGE_MODE_PAPERSIZE 2 #define PAGE_MODE_MARGINS 4 #define PAGE_MODE_ROWSCOLS 8 #define INVERT_DATA_ONLY 10 #define INVERT_DATA_AND_TAG 11 struct paperdef { char name[MAX_PAPERNAME_LENGTH]; double width; double length; double asratio; }; /* European page sizes corrected from update sent by * thomas . jarosch @ intra2net . com on 5/7/2010 * Paper Size Width Length Aspect Ratio */ struct paperdef PaperTable[MAX_PAPERNAMES] = { {"default", 8.500, 14.000, 0.607}, {"pa4", 8.264, 11.000, 0.751}, {"letter", 8.500, 11.000, 0.773}, {"legal", 8.500, 14.000, 0.607}, {"half-letter", 8.500, 5.514, 1.542}, {"executive", 7.264, 10.528, 0.690}, {"tabloid", 11.000, 17.000, 0.647}, {"11x17", 11.000, 17.000, 0.647}, {"ledger", 17.000, 11.000, 1.545}, {"archa", 9.000, 12.000, 0.750}, {"archb", 12.000, 18.000, 0.667}, {"archc", 18.000, 24.000, 0.750}, {"archd", 24.000, 36.000, 0.667}, {"arche", 36.000, 48.000, 0.750}, {"csheet", 17.000, 22.000, 0.773}, {"dsheet", 22.000, 34.000, 0.647}, {"esheet", 34.000, 44.000, 0.773}, {"superb", 11.708, 17.042, 0.687}, {"commercial", 4.139, 9.528, 0.434}, {"monarch", 3.889, 7.528, 0.517}, {"envelope-dl", 4.333, 8.681, 0.499}, {"envelope-c5", 6.389, 9.028, 0.708}, {"europostcard", 4.139, 5.833, 0.710}, {"a0", 33.110, 46.811, 0.707}, {"a1", 23.386, 33.110, 0.706}, {"a2", 16.535, 23.386, 0.707}, {"a3", 11.693, 16.535, 0.707}, {"a4", 8.268, 11.693, 0.707}, {"a5", 5.827, 8.268, 0.705}, {"a6", 4.134, 5.827, 0.709}, {"a7", 2.913, 4.134, 0.705}, {"a8", 2.047, 2.913, 0.703}, {"a9", 1.457, 2.047, 0.712}, {"a10", 1.024, 1.457, 0.703}, {"b0", 39.370, 55.669, 0.707}, {"b1", 27.835, 39.370, 0.707}, {"b2", 19.685, 27.835, 0.707}, {"b3", 13.898, 19.685, 0.706}, {"b4", 9.843, 13.898, 0.708}, {"b5", 6.929, 9.843, 0.704}, {"b6", 4.921, 6.929, 0.710}, {"c0", 36.102, 51.063, 0.707}, {"c1", 25.512, 36.102, 0.707}, {"c2", 18.031, 25.512, 0.707}, {"c3", 12.756, 18.031, 0.707}, {"c4", 9.016, 12.756, 0.707}, {"c5", 6.378, 9.016, 0.707}, {"c6", 4.488, 6.378, 0.704}, {"", 0.000, 0.000, 1.000} }; /* Structure to define input image parameters */ struct image_data { float xres; float yres; uint32 width; uint32 length; uint16 res_unit; uint16 bps; uint16 spp; uint16 planar; uint16 photometric; uint16 orientation; uint16 compression; uint16 adjustments; }; /* Structure to define the output image modifiers */ struct pagedef { char name[16]; double width; /* width in pixels */ double length; /* length in pixels */ double hmargin; /* margins to subtract from width of sections */ double vmargin; /* margins to subtract from height of sections */ double hres; /* horizontal resolution for output */ double vres; /* vertical resolution for output */ uint32 mode; /* bitmask of modifiers to page format */ uint16 res_unit; /* resolution unit for output image */ unsigned int rows; /* number of section rows */ unsigned int cols; /* number of section cols */ unsigned int orient; /* portrait, landscape, seascape, auto */ }; struct dump_opts { int debug; int format; int level; char mode[4]; char infilename[PATH_MAX + 1]; char outfilename[PATH_MAX + 1]; FILE *infile; FILE *outfile; }; /* globals */ static int outtiled = -1; static uint32 tilewidth = 0; static uint32 tilelength = 0; static uint16 config = 0; static uint16 compression = 0; static uint16 predictor = 0; static uint16 fillorder = 0; static uint32 rowsperstrip = 0; static uint32 g3opts = 0; static int ignore = FALSE; /* if true, ignore read errors */ static uint32 defg3opts = (uint32) -1; static int quality = 100; /* JPEG quality */ /* static int jpegcolormode = -1; was JPEGCOLORMODE_RGB; */ static int jpegcolormode = JPEGCOLORMODE_RGB; static uint16 defcompression = (uint16) -1; static uint16 defpredictor = (uint16) -1; static int pageNum = 0; static int little_endian = 1; /* Functions adapted from tiffcp with additions or significant modifications */ static int readContigStripsIntoBuffer (TIFF*, uint8*); static int readSeparateStripsIntoBuffer (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int readContigTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int readSeparateTilesIntoBuffer (TIFF*, uint8*, uint32, uint32, uint32, uint32, tsample_t, uint16); static int writeBufferToContigStrips (TIFF*, uint8*, uint32); static int writeBufferToContigTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateStrips (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int writeBufferToSeparateTiles (TIFF*, uint8*, uint32, uint32, tsample_t, struct dump_opts *); static int extractContigSamplesToBuffer (uint8 *, uint8 *, uint32, uint32, tsample_t, uint16, uint16, struct dump_opts *); static int processCompressOptions(char*); static void usage(void); /* All other functions by Richard Nolde, not found in tiffcp */ static void initImageData (struct image_data *); static void initCropMasks (struct crop_mask *); static void initPageSetup (struct pagedef *, struct pageseg *, struct buffinfo []); static void initDumpOptions(struct dump_opts *); /* Command line and file naming functions */ void process_command_opts (int, char *[], char *, char *, uint32 *, uint16 *, uint16 *, uint32 *, uint32 *, uint32 *, struct crop_mask *, struct pagedef *, struct dump_opts *, unsigned int *, unsigned int *); static int update_output_file (TIFF **, char *, int, char *, unsigned int *); /* * High level functions for whole image manipulation */ static int get_page_geometry (char *, struct pagedef*); static int computeInputPixelOffsets(struct crop_mask *, struct image_data *, struct offset *); static int computeOutputPixelOffsets (struct crop_mask *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *); static int loadImage(TIFF *, struct image_data *, struct dump_opts *, unsigned char **); static int correct_orientation(struct image_data *, unsigned char **); static int getCropOffsets(struct image_data *, struct crop_mask *, struct dump_opts *); static int processCropSelections(struct image_data *, struct crop_mask *, unsigned char **, struct buffinfo []); static int writeSelections(TIFF *, TIFF **, struct crop_mask *, struct image_data *, struct dump_opts *, struct buffinfo [], char *, char *, unsigned int*, unsigned int); /* Section functions */ static int createImageSection(uint32, unsigned char **); static int extractImageSection(struct image_data *, struct pageseg *, unsigned char *, unsigned char *); static int writeSingleSection(TIFF *, TIFF *, struct image_data *, struct dump_opts *, uint32, uint32, double, double, unsigned char *); static int writeImageSections(TIFF *, TIFF *, struct image_data *, struct pagedef *, struct pageseg *, struct dump_opts *, unsigned char *, unsigned char **); /* Whole image functions */ static int createCroppedImage(struct image_data *, struct crop_mask *, unsigned char **, unsigned char **); static int writeCroppedImage(TIFF *, TIFF *, struct image_data *image, struct dump_opts * dump, uint32, uint32, unsigned char *, int, int); /* Image manipulation functions */ static int rotateContigSamples8bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples16bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples24bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateContigSamples32bits(uint16, uint16, uint16, uint32, uint32, uint32, uint8 *, uint8 *); static int rotateImage(uint16, struct image_data *, uint32 *, uint32 *, unsigned char **); static int mirrorImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); static int invertImage(uint16, uint16, uint16, uint32, uint32, unsigned char *); /* Functions to reverse the sequence of samples in a scanline */ static int reverseSamples8bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples16bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples24bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamples32bits (uint16, uint16, uint32, uint8 *, uint8 *); static int reverseSamplesBytes (uint16, uint16, uint32, uint8 *, uint8 *); /* Functions for manipulating individual samples in an image */ static int extractSeparateRegion(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *, int); static int extractCompositeRegions(struct image_data *, struct crop_mask *, unsigned char *, unsigned char *); static int extractContigSamples8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamples32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesBytes (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32); static int extractContigSamplesShifted8bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted16bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted24bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesShifted32bits (uint8 *, uint8 *, uint32, tsample_t, uint16, uint16, tsample_t, uint32, uint32, int); static int extractContigSamplesToTileBuffer(uint8 *, uint8 *, uint32, uint32, uint32, uint32, tsample_t, uint16, uint16, uint16, struct dump_opts *); /* Functions to combine separate planes into interleaved planes */ static int combineSeparateSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, tsample_t, uint16, FILE *, int, int); static int combineSeparateTileSamples8bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples16bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples24bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamples32bits (uint8 *[], uint8 *, uint32, uint32, uint32, uint32, uint16, uint16, FILE *, int, int); static int combineSeparateTileSamplesBytes (unsigned char *[], unsigned char *, uint32, uint32, uint32, uint32, tsample_t, uint16, FILE *, int, int); /* Dump functions for debugging */ static void dump_info (FILE *, int, char *, char *, ...); static int dump_data (FILE *, int, char *, unsigned char *, uint32); static int dump_byte (FILE *, int, char *, unsigned char); static int dump_short (FILE *, int, char *, uint16); static int dump_long (FILE *, int, char *, uint32); static int dump_wide (FILE *, int, char *, uint64); static int dump_buffer (FILE *, int, uint32, uint32, uint32, unsigned char *); /* End function declarations */ /* Functions derived in whole or in part from tiffcp */ /* The following functions are taken largely intact from tiffcp */ static char* usage_info[] = { "usage: tiffcrop [options] source1 ... sourceN destination", "where options are:", " -h Print this syntax listing", " -v Print tiffcrop version identifier and last revision date", " ", " -a Append to output instead of overwriting", " -d offset Set initial directory offset, counting first image as one, not zero", " -p contig Pack samples contiguously (e.g. RGBRGB...)", " -p separate Store samples separately (e.g. RRR...GGG...BBB...)", " -s Write output in strips", " -t Write output in tiles", " -i Ignore read errors", " ", " -r # Make each strip have no more than # rows", " -w # Set output tile width (pixels)", " -l # Set output tile length (pixels)", " ", " -f lsb2msb Force lsb-to-msb FillOrder for output", " -f msb2lsb Force msb-to-lsb FillOrder for output", "", " -c lzw[:opts] Compress output with Lempel-Ziv & Welch encoding", " -c zip[:opts] Compress output with deflate encoding", " -c jpeg[:opts] Compress output with JPEG encoding", " -c packbits Compress output with packbits encoding", " -c g3[:opts] Compress output with CCITT Group 3 encoding", " -c g4 Compress output with CCITT Group 4 encoding", " -c none Use no compression algorithm on output", " ", "Group 3 options:", " 1d Use default CCITT Group 3 1D-encoding", " 2d Use optional CCITT Group 3 2D-encoding", " fill Byte-align EOL codes", "For example, -c g3:2d:fill to get G3-2D-encoded data with byte-aligned EOLs", " ", "JPEG options:", " # Set compression quality level (0-100, default 100)", " raw Output color image as raw YCbCr", " rgb Output color image as RGB", "For example, -c jpeg:rgb:50 to get JPEG-encoded RGB data with 50% comp. quality", " ", "LZW and deflate options:", " # Set predictor value", "For example, -c lzw:2 to get LZW-encoded data with horizontal differencing", " ", "Page and selection options:", " -N odd|even|#,#-#,#|last sequences and ranges of images within file to process", " The words odd or even may be used to specify all odd or even numbered images.", " The word last may be used in place of a number in the sequence to indicate.", " The final image in the file without knowing how many images there are.", " Numbers are counted from one even though TIFF IFDs are counted from zero.", " ", " -E t|l|r|b edge to use as origin for width and length of crop region", " -U units [in, cm, px ] inches, centimeters or pixels", " ", " -m #,#,#,# margins from edges for selection: top, left, bottom, right separated by commas", " -X # horizontal dimension of region to extract expressed in current units", " -Y # vertical dimension of region to extract expressed in current units", " -Z #:#,#:# zones of the image designated as position X of Y,", " eg 1:3 would be first of three equal portions measured from reference edge", " -z x1,y1,x2,y2:...:xN,yN,xN+1,yN+1", " regions of the image designated by upper left and lower right coordinates", "", "Export grouping options:", " -e c|d|i|m|s export mode for images and selections from input images.", " When exporting a composite image from multiple zones or regions", " (combined and image modes), the selections must have equal sizes", " for the axis perpendicular to the edge specified with -E.", " c|combined All images and selections are written to a single file (default).", " with multiple selections from one image combined into a single image.", " d|divided All images and selections are written to a single file", " with each selection from one image written to a new image.", " i|image Each input image is written to a new file (numeric filename sequence)", " with multiple selections from the image combined into one image.", " m|multiple Each input image is written to a new file (numeric filename sequence)", " with each selection from the image written to a new image.", " s|separated Individual selections from each image are written to separate files.", "", "Output options:", " -H # Set horizontal resolution of output images to #", " -V # Set vertical resolution of output images to #", " -J # Set horizontal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " -K # Set verticalal margin of output page to # expressed in current units", " when sectioning image into columns x rows using the -S cols:rows option", " ", " -O orient orientation for output image, portrait, landscape, auto", " -P page page size for output image segments, eg letter, legal, tabloid, etc", " use #.#x#.# to specify a custom page size in the currently defined units", " where #.# represents the width and length", " -S cols:rows Divide the image into equal sized segments using cols across and rows down.", " ", " -F hor|vert|both", " flip (mirror) image or region horizontally, vertically, or both", " -R # [90,180,or 270] degrees clockwise rotation of image or extracted region", " -I [black|white|data|both]", " invert color space, eg dark to light for bilevel and grayscale images", " If argument is white or black, set the PHOTOMETRIC_INTERPRETATION ", " tag to MinIsBlack or MinIsWhite without altering the image data", " If the argument is data or both, the image data are modified:", " both inverts the data and the PHOTOMETRIC_INTERPRETATION tag,", " data inverts the data but not the PHOTOMETRIC_INTERPRETATION tag", " ", "-D opt1:value1,opt2:value2,opt3:value3:opt4:value4", " Debug/dump program progress and/or data to non-TIFF files.", " Options include the following and must be joined as a comma", " separate list. The use of this option is generally limited to", " program debugging and development of future options.", " ", " debug:N Display limited program progress indicators where larger N", " increase the level of detail. Note: Tiffcrop may be compiled with", " -DDEVELMODE to enable additional very low level debug reporting.", "", " Format:txt|raw Format any logged data as ASCII text or raw binary ", " values. ASCII text dumps include strings of ones and zeroes", " representing the binary values in the image data plus identifying headers.", " ", " level:N Specify the level of detail presented in the dump files.", " This can vary from dumps of the entire input or output image data to dumps", " of data processed by specific functions. Current range of levels is 1 to 3.", " ", " input:full-path-to-directory/input-dumpname", " ", " output:full-path-to-directory/output-dumpnaem", " ", " When dump files are being written, each image will be written to a separate", " file with the name built by adding a numeric sequence value to the dumpname", " and an extension of .txt for ASCII dumps or .bin for binary dumps.", " ", " The four debug/dump options are independent, though it makes little sense to", " specify a dump file without specifying a detail level.", " ", NULL }; /* This function could be modified to pass starting sample offset * and number of samples as args to select fewer than spp * from input image. These would then be passed to individual * extractContigSampleXX routines. */ static int readContigTilesIntoBuffer (TIFF* in, uint8* buf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, tsample_t spp, uint16 bps) { int status = 1; tsample_t sample = 0; tsample_t count = spp; uint32 row, col, trow; uint32 nrow, ncol; uint32 dst_rowsize, shift_width; uint32 bytes_per_sample, bytes_per_pixel; uint32 trailing_bits, prev_trailing_bits; uint32 tile_rowsize = TIFFTileRowSize(in); uint32 src_offset, dst_offset; uint32 row_offset, col_offset; uint8 *bufp = (uint8*) buf; unsigned char *src = NULL; unsigned char *dst = NULL; tsize_t tbytes = 0, tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(in); unsigned char *tilebuf = NULL; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } tile_buffsize = tilesize; if (tilesize == 0 || tile_rowsize == 0) { TIFFError("readContigTilesIntoBuffer", "Tile size or tile rowsize is zero"); exit(-1); } if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("readContigTilesIntoBuffer", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != (tile_buffsize / tile_rowsize)) { TIFFError("readContigTilesIntoBuffer", "Integer overflow when calculating buffer size."); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 0; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { tbytes = TIFFReadTile(in, tilebuf, col, row, 0, 0); if (tbytes < tilesize && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile at row %lu col %lu, Read %lu bytes of %lu", (unsigned long) col, (unsigned long) row, (unsigned long)tbytes, (unsigned long)tilesize); status = 0; _TIFFfree(tilebuf); return status; } row_offset = row * dst_rowsize; col_offset = ((col * bps * spp) + 7)/ 8; bufp = buf + row_offset + col_offset; if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; /* Each tile scanline will start on a byte boundary but it * has to be merged into the scanline for the entire * image buffer and the previous segment may not have * ended on a byte boundary */ /* Optimization for common bit depths, all samples */ if (((bps % 8) == 0) && (count == spp)) { for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; _TIFFmemcpy (bufp, tilebuf + src_offset, (ncol * spp * bps) / 8); bufp += (imagewidth * bps * spp) / 8; } } else { /* Bit depths not a multiple of 8 and/or extract fewer than spp samples */ prev_trailing_bits = trailing_bits = 0; trailing_bits = (ncol * bps * spp) % 8; /* for (trow = 0; tl < nrow; trow++) */ for (trow = 0; trow < nrow; trow++) { src_offset = trow * tile_rowsize; src = tilebuf + src_offset; dst_offset = (row + trow) * dst_rowsize; dst = buf + dst_offset + col_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, ncol, sample, spp, bps, count, 0, ncol)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; } else if (extractContigSamplesShifted16bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 2: if (extractContigSamplesShifted24bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, ncol, sample, spp, bps, count, 0, ncol, prev_trailing_bits)) { TIFFError("readContigTilesIntoBuffer", "Unable to extract row %d from tile %lu", row, (unsigned long)TIFFCurrentTile(in)); return 1; } break; default: TIFFError("readContigTilesIntoBuffer", "Unsupported bit depth %d", bps); return 1; } } prev_trailing_bits += trailing_bits; /* if (prev_trailing_bits > 7) */ /* prev_trailing_bits-= 8; */ } } } _TIFFfree(tilebuf); return status; } static int readSeparateTilesIntoBuffer (TIFF* in, uint8 *obuf, uint32 imagelength, uint32 imagewidth, uint32 tw, uint32 tl, uint16 spp, uint16 bps) { int i, status = 1, sample; int shift_width, bytes_per_pixel; uint16 bytes_per_sample; uint32 row, col; /* Current row and col of image */ uint32 nrow, ncol; /* Number of rows and cols in current tile */ uint32 row_offset, col_offset; /* Output buffer offsets */ tsize_t tbytes = 0, tilesize = TIFFTileSize(in); tsample_t s; uint8* bufp = (uint8*)obuf; unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *tbuff = NULL; bytes_per_sample = (bps + 7) / 8; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { srcbuffs[sample] = NULL; tbuff = (unsigned char *)_TIFFmalloc(tilesize + 8); if (!tbuff) { TIFFError ("readSeparateTilesIntoBuffer", "Unable to allocate tile read buffer for sample %d", sample); for (i = 0; i < sample; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[sample] = tbuff; } /* Each tile contains only the data for a single plane * arranged in scanlines of tw * bytes_per_sample bytes. */ for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { for (s = 0; s < spp && s < MAX_SAMPLES; s++) { /* Read each plane of a tile set into srcbuffs[s] */ tbytes = TIFFReadTile(in, srcbuffs[s], col, row, 0, s); if (tbytes < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read tile for row %lu col %lu, " "sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); status = 0; for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } } /* Tiles on the right edge may be padded out to tw * which must be a multiple of 16. * Ncol represents the visible (non padding) portion. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; row_offset = row * (((imagewidth * spp * bps) + 7) / 8); col_offset = ((col * spp * bps) + 7) / 8; bufp = obuf + row_offset + col_offset; if ((bps % 8) == 0) { if (combineSeparateTileSamplesBytes(srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } } else { bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (shift_width) { case 1: if (combineSeparateTileSamples8bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 2: if (combineSeparateTileSamples16bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 3: if (combineSeparateTileSamples24bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateTileSamples32bits (srcbuffs, bufp, ncol, nrow, imagewidth, tw, spp, bps, NULL, 0, 0)) { status = 0; break; } break; default: TIFFError ("readSeparateTilesIntoBuffer", "Unsupported bit depth: %d", bps); status = 0; break; } } } } for (sample = 0; (sample < spp) && (sample < MAX_SAMPLES); sample++) { tbuff = srcbuffs[sample]; if (tbuff != NULL) _TIFFfree(tbuff); } return status; } static int writeBufferToContigStrips(TIFF* out, uint8* buf, uint32 imagelength) { uint32 row, nrows, rowsperstrip; tstrip_t strip = 0; tsize_t stripsize; TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); for (row = 0; row < imagelength; row += rowsperstrip) { nrows = (row + rowsperstrip > imagelength) ? imagelength - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); if (TIFFWriteEncodedStrip(out, strip++, buf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); return 1; } buf += stripsize; } return 0; } /* Abandon plans to modify code so that plannar orientation separate images * do not have all samples for each channel written before all samples * for the next channel have been abandoned. * Libtiff internals seem to depend on all data for a given sample * being contiguous within a strip or tile when PLANAR_CONFIG is * separate. All strips or tiles of a given plane are written * before any strips or tiles of a different plane are stored. */ static int writeBufferToSeparateStrips (TIFF* out, uint8* buf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { uint8 *src; uint16 bps; uint32 row, nrows, rowsize, rowsperstrip; uint32 bytes_per_sample; tsample_t s; tstrip_t strip = 0; tsize_t stripsize = TIFFStripSize(out); tsize_t rowstripsize, scanlinesize = TIFFScanlineSize(out); tsize_t total_bytes = 0; tdata_t obuf; (void) TIFFGetFieldDefaulted(out, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); (void) TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); bytes_per_sample = (bps + 7) / 8; rowsize = ((bps * spp * width) + 7) / 8; /* source has interleaved samples */ rowstripsize = rowsperstrip * bytes_per_sample * (width + 1); obuf = _TIFFmalloc (rowstripsize); if (obuf == NULL) return 1; for (s = 0; s < spp; s++) { for (row = 0; row < length; row += rowsperstrip) { nrows = (row + rowsperstrip > length) ? length - row : rowsperstrip; stripsize = TIFFVStripSize(out, nrows); src = buf + (row * rowsize); total_bytes += stripsize; memset (obuf, '\0', rowstripsize); if (extractContigSamplesToBuffer(obuf, src, nrows, width, s, spp, bps, dump)) { _TIFFfree(obuf); return 1; } if ((dump->outfile != NULL) && (dump->level == 1)) { dump_info(dump->outfile, dump->format,"", "Sample %2d, Strip: %2d, bytes: %4d, Row %4d, bytes: %4d, Input offset: %6d", s + 1, strip + 1, stripsize, row + 1, scanlinesize, src - buf); dump_buffer(dump->outfile, dump->format, nrows, scanlinesize, row, obuf); } if (TIFFWriteEncodedStrip(out, strip++, obuf, stripsize) < 0) { TIFFError(TIFFFileName(out), "Error, can't write strip %u", strip - 1); _TIFFfree(obuf); return 1; } } } _TIFFfree(obuf); return 0; } /* Extract all planes from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToContigTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts* dump) { uint16 bps; uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint32 tile_rowsize = TIFFTileRowSize(out); uint8* bufp = (uint8*) buf; tsize_t tile_buffsize = 0; tsize_t tilesize = TIFFTileSize(out); unsigned char *tilebuf = NULL; if( !TIFFGetField(out, TIFFTAG_TILELENGTH, &tl) || !TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw) || !TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps) ) return 1; if (tilesize == 0 || tile_rowsize == 0 || tl == 0 || tw == 0) { TIFFError("writeBufferToContigTiles", "Tile size, tile row size, tile width, or tile length is zero"); exit(-1); } tile_buffsize = tilesize; if (tilesize < (tsize_t)(tl * tile_rowsize)) { #ifdef DEBUG2 TIFFError("writeBufferToContigTiles", "Tilesize %lu is too small, using alternate calculation %u", tilesize, tl * tile_rowsize); #endif tile_buffsize = tl * tile_rowsize; if (tl != tile_buffsize / tile_rowsize) { TIFFError("writeBufferToContigTiles", "Integer overflow when calculating buffer size"); exit(-1); } } tilebuf = _TIFFmalloc(tile_buffsize); if (tilebuf == 0) return 1; src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; if (extractContigSamplesToTileBuffer(tilebuf, bufp, nrow, ncol, imagewidth, tw, 0, spp, spp, bps, dump) > 0) { TIFFError("writeBufferToContigTiles", "Unable to extract data to tile for row %lu, col %lu", (unsigned long) row, (unsigned long)col); _TIFFfree(tilebuf); return 1; } if (TIFFWriteTile(out, tilebuf, col, row, 0, 0) < 0) { TIFFError("writeBufferToContigTiles", "Cannot write tile at %lu %lu", (unsigned long) col, (unsigned long) row); _TIFFfree(tilebuf); return 1; } } } _TIFFfree(tilebuf); return 0; } /* end writeBufferToContigTiles */ /* Extract each plane from contiguous buffer into a single tile buffer * to be written out as a tile. */ static int writeBufferToSeparateTiles (TIFF* out, uint8* buf, uint32 imagelength, uint32 imagewidth, tsample_t spp, struct dump_opts * dump) { tdata_t obuf = _TIFFmalloc(TIFFTileSize(out)); uint32 tl, tw; uint32 row, col, nrow, ncol; uint32 src_rowsize, col_offset; uint16 bps; tsample_t s; uint8* bufp = (uint8*) buf; if (obuf == NULL) return 1; TIFFGetField(out, TIFFTAG_TILELENGTH, &tl); TIFFGetField(out, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(out, TIFFTAG_BITSPERSAMPLE, &bps); src_rowsize = ((imagewidth * spp * bps) + 7) / 8; for (row = 0; row < imagelength; row += tl) { nrow = (row + tl > imagelength) ? imagelength - row : tl; for (col = 0; col < imagewidth; col += tw) { /* Calculate visible portion of tile. */ if (col + tw > imagewidth) ncol = imagewidth - col; else ncol = tw; col_offset = (((col * bps * spp) + 7) / 8); bufp = buf + (row * src_rowsize) + col_offset; for (s = 0; s < spp; s++) { if (extractContigSamplesToTileBuffer(obuf, bufp, nrow, ncol, imagewidth, tw, s, 1, spp, bps, dump) > 0) { TIFFError("writeBufferToSeparateTiles", "Unable to extract data to tile for row %lu, col %lu sample %d", (unsigned long) row, (unsigned long)col, (int)s); _TIFFfree(obuf); return 1; } if (TIFFWriteTile(out, obuf, col, row, 0, s) < 0) { TIFFError("writeBufferToseparateTiles", "Cannot write tile at %lu %lu sample %lu", (unsigned long) col, (unsigned long) row, (unsigned long) s); _TIFFfree(obuf); return 1; } } } } _TIFFfree(obuf); return 0; } /* end writeBufferToSeparateTiles */ static void processG3Options(char* cp) { if( (cp = strchr(cp, ':')) ) { if (defg3opts == (uint32) -1) defg3opts = 0; do { cp++; if (strneq(cp, "1d", 2)) defg3opts &= ~GROUP3OPT_2DENCODING; else if (strneq(cp, "2d", 2)) defg3opts |= GROUP3OPT_2DENCODING; else if (strneq(cp, "fill", 4)) defg3opts |= GROUP3OPT_FILLBITS; else usage(); } while( (cp = strchr(cp, ':')) ); } } static int processCompressOptions(char* opt) { char* cp = NULL; if (strneq(opt, "none",4)) { defcompression = COMPRESSION_NONE; } else if (streq(opt, "packbits")) { defcompression = COMPRESSION_PACKBITS; } else if (strneq(opt, "jpeg", 4)) { cp = strchr(opt, ':'); defcompression = COMPRESSION_JPEG; while (cp) { if (isdigit((int)cp[1])) quality = atoi(cp + 1); else if (strneq(cp + 1, "raw", 3 )) jpegcolormode = JPEGCOLORMODE_RAW; else if (strneq(cp + 1, "rgb", 3 )) jpegcolormode = JPEGCOLORMODE_RGB; else usage(); cp = strchr(cp + 1, ':'); } } else if (strneq(opt, "g3", 2)) { processG3Options(opt); defcompression = COMPRESSION_CCITTFAX3; } else if (streq(opt, "g4")) { defcompression = COMPRESSION_CCITTFAX4; } else if (strneq(opt, "lzw", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_LZW; } else if (strneq(opt, "zip", 3)) { cp = strchr(opt, ':'); if (cp) defpredictor = atoi(cp+1); defcompression = COMPRESSION_ADOBE_DEFLATE; } else return (0); return (1); } static void usage(void) { int i; fprintf(stderr, "\n%s\n", TIFFGetVersion()); for (i = 0; usage_info[i] != NULL; i++) fprintf(stderr, "%s\n", usage_info[i]); exit(-1); } #define CopyField(tag, v) \ if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) #define CopyField2(tag, v1, v2) \ if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) #define CopyField3(tag, v1, v2, v3) \ if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) #define CopyField4(tag, v1, v2, v3, v4) \ if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) static void cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) { switch (type) { case TIFF_SHORT: if (count == 1) { uint16 shortv; CopyField(tag, shortv); } else if (count == 2) { uint16 shortv1, shortv2; CopyField2(tag, shortv1, shortv2); } else if (count == 4) { uint16 *tr, *tg, *tb, *ta; CopyField4(tag, tr, tg, tb, ta); } else if (count == (uint16) -1) { uint16 shortv1; uint16* shortav; CopyField2(tag, shortv1, shortav); } break; case TIFF_LONG: { uint32 longv; CopyField(tag, longv); } break; case TIFF_RATIONAL: if (count == 1) { float floatv; CopyField(tag, floatv); } else if (count == (uint16) -1) { float* floatav; CopyField(tag, floatav); } break; case TIFF_ASCII: { char* stringv; CopyField(tag, stringv); } break; case TIFF_DOUBLE: if (count == 1) { double doublev; CopyField(tag, doublev); } else if (count == (uint16) -1) { double* doubleav; CopyField(tag, doubleav); } break; default: TIFFError(TIFFFileName(in), "Data type %d is not supported, tag %d skipped", tag, type); } } static struct cpTag { uint16 tag; uint16 count; TIFFDataType type; } tags[] = { { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, { TIFFTAG_MAKE, 1, TIFF_ASCII }, { TIFFTAG_MODEL, 1, TIFF_ASCII }, { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, { TIFFTAG_DATETIME, 1, TIFF_ASCII }, { TIFFTAG_ARTIST, 1, TIFF_ASCII }, { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, { TIFFTAG_WHITEPOINT, (uint16) -1, TIFF_RATIONAL }, { TIFFTAG_PRIMARYCHROMATICITIES,(uint16) -1,TIFF_RATIONAL }, { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, { TIFFTAG_INKSET, 1, TIFF_SHORT }, { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, { TIFFTAG_SMINSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_SMAXSAMPLEVALUE, 1, TIFF_DOUBLE }, { TIFFTAG_STONITS, 1, TIFF_DOUBLE }, }; #define NTAGS (sizeof (tags) / sizeof (tags[0])) #define CopyTag(tag, count, type) cpTag(in, out, tag, count, type) /* Functions written by Richard Nolde, with exceptions noted. */ void process_command_opts (int argc, char *argv[], char *mp, char *mode, uint32 *dirnum, uint16 *defconfig, uint16 *deffillorder, uint32 *deftilewidth, uint32 *deftilelength, uint32 *defrowsperstrip, struct crop_mask *crop_data, struct pagedef *page, struct dump_opts *dump, unsigned int *imagelist, unsigned int *image_count ) { int c, good_args = 0; char *opt_offset = NULL; /* Position in string of value sought */ char *opt_ptr = NULL; /* Pointer to next token in option set */ char *sep = NULL; /* Pointer to a token separator */ unsigned int i, j, start, end; #if !HAVE_DECL_OPTARG extern int optind; extern char* optarg; #endif *mp++ = 'w'; *mp = '\0'; while ((c = getopt(argc, argv, "ac:d:e:f:hil:m:p:r:stvw:z:BCD:E:F:H:I:J:K:LMN:O:P:R:S:U:V:X:Y:Z:")) != -1) { good_args++; switch (c) { case 'a': mode[0] = 'a'; /* append to output */ break; case 'c': if (!processCompressOptions(optarg)) /* compression scheme */ { TIFFError ("Unknown compression option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'd': start = strtoul(optarg, NULL, 0); /* initial IFD offset */ if (start == 0) { TIFFError ("","Directory offset must be greater than zero"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *dirnum = start - 1; break; case 'e': switch (tolower((int) optarg[0])) /* image export modes*/ { case 'c': crop_data->exp_mode = ONE_FILE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Composite */ case 'd': crop_data->exp_mode = ONE_FILE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Divided */ case 'i': crop_data->exp_mode = FILE_PER_IMAGE_COMPOSITE; crop_data->img_mode = COMPOSITE_IMAGES; break; /* Image */ case 'm': crop_data->exp_mode = FILE_PER_IMAGE_SEPARATED; crop_data->img_mode = SEPARATED_IMAGES; break; /* Multiple */ case 's': crop_data->exp_mode = FILE_PER_SELECTION; crop_data->img_mode = SEPARATED_IMAGES; break; /* Sections */ default: TIFFError ("Unknown export mode","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'f': if (streq(optarg, "lsb2msb")) /* fill order */ *deffillorder = FILLORDER_LSB2MSB; else if (streq(optarg, "msb2lsb")) *deffillorder = FILLORDER_MSB2LSB; else { TIFFError ("Unknown fill order", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'h': usage(); break; case 'i': ignore = TRUE; /* ignore errors */ break; case 'l': outtiled = TRUE; /* tile length */ *deftilelength = atoi(optarg); break; case 'p': /* planar configuration */ if (streq(optarg, "separate")) *defconfig = PLANARCONFIG_SEPARATE; else if (streq(optarg, "contig")) *defconfig = PLANARCONFIG_CONTIG; else { TIFFError ("Unkown planar configuration", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'r': /* rows/strip */ *defrowsperstrip = atol(optarg); break; case 's': /* generate stripped output */ outtiled = FALSE; break; case 't': /* generate tiled output */ outtiled = TRUE; break; case 'v': TIFFError("Library Release", "%s", TIFFGetVersion()); TIFFError ("Tiffcrop version", "%s, last updated: %s", tiffcrop_version_id, tiffcrop_rev_date); TIFFError ("Tiffcp code", "Copyright (c) 1988-1997 Sam Leffler"); TIFFError (" ", "Copyright (c) 1991-1997 Silicon Graphics, Inc"); TIFFError ("Tiffcrop additions", "Copyright (c) 2007-2010 Richard Nolde"); exit (0); break; case 'w': /* tile width */ outtiled = TRUE; *deftilewidth = atoi(optarg); break; case 'z': /* regions of an image specified as x1,y1,x2,y2:x3,y3,x4,y4 etc */ crop_data->crop_mode |= CROP_REGIONS; for (i = 0, opt_ptr = strtok (optarg, ":"); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ":")), i++) { crop_data->regions++; if (sscanf(opt_ptr, "%lf,%lf,%lf,%lf", &crop_data->corners[i].X1, &crop_data->corners[i].Y1, &crop_data->corners[i].X2, &crop_data->corners[i].Y2) != 4) { TIFFError ("Unable to parse coordinates for region", "%d %s", i, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError ("Region list exceeds limit of", "%d regions %s", MAX_REGIONS, optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1);; } break; /* options for file open modes */ case 'B': *mp++ = 'b'; *mp = '\0'; break; case 'L': *mp++ = 'l'; *mp = '\0'; break; case 'M': *mp++ = 'm'; *mp = '\0'; break; case 'C': *mp++ = 'c'; *mp = '\0'; break; /* options for Debugging / data dump */ case 'D': for (i = 0, opt_ptr = strtok (optarg, ","); (opt_ptr != NULL); (opt_ptr = strtok (NULL, ",")), i++) { opt_offset = strpbrk(opt_ptr, ":="); if (opt_offset == NULL) { TIFFError("Invalid dump option", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } *opt_offset = '\0'; /* convert option to lowercase */ end = strlen (opt_ptr); for (i = 0; i < end; i++) *(opt_ptr + i) = tolower((int) *(opt_ptr + i)); /* Look for dump format specification */ if (strncmp(opt_ptr, "for", 3) == 0) { /* convert value to lowercase */ end = strlen (opt_offset + 1); for (i = 1; i <= end; i++) *(opt_offset + i) = tolower((int) *(opt_offset + i)); /* check dump format value */ if (strncmp (opt_offset + 1, "txt", 3) == 0) { dump->format = DUMP_TEXT; strcpy (dump->mode, "w"); } else { if (strncmp(opt_offset + 1, "raw", 3) == 0) { dump->format = DUMP_RAW; strcpy (dump->mode, "wb"); } else { TIFFError("parse_command_opts", "Unknown dump format %s", opt_offset + 1); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } } else { /* Look for dump level specification */ if (strncmp (opt_ptr, "lev", 3) == 0) dump->level = atoi(opt_offset + 1); /* Look for input data dump file name */ if (strncmp (opt_ptr, "in", 2) == 0) { strncpy (dump->infilename, opt_offset + 1, PATH_MAX - 20); dump->infilename[PATH_MAX - 20] = '\0'; } /* Look for output data dump file name */ if (strncmp (opt_ptr, "out", 3) == 0) { strncpy (dump->outfilename, opt_offset + 1, PATH_MAX - 20); dump->outfilename[PATH_MAX - 20] = '\0'; } if (strncmp (opt_ptr, "deb", 3) == 0) dump->debug = atoi(opt_offset + 1); } } if ((strlen(dump->infilename)) || (strlen(dump->outfilename))) { if (dump->level == 1) TIFFError("","Defaulting to dump level 1, no data."); if (dump->format == DUMP_NONE) { TIFFError("", "You must specify a dump format for dump files"); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } } break; /* image manipulation routine options */ case 'm': /* margins to exclude from selection, uppercase M was already used */ /* order of values must be TOP, LEFT, BOTTOM, RIGHT */ crop_data->crop_mode |= CROP_MARGINS; for (i = 0, opt_ptr = strtok (optarg, ",:"); ((opt_ptr != NULL) && (i < 4)); (opt_ptr = strtok (NULL, ",:")), i++) { crop_data->margins[i] = atof(opt_ptr); } break; case 'E': /* edge reference */ switch (tolower((int) optarg[0])) { case 't': crop_data->edge_ref = EDGE_TOP; break; case 'b': crop_data->edge_ref = EDGE_BOTTOM; break; case 'l': crop_data->edge_ref = EDGE_LEFT; break; case 'r': crop_data->edge_ref = EDGE_RIGHT; break; default: TIFFError ("Edge reference must be top, bottom, left, or right", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'F': /* flip eg mirror image or cropped segment, M was already used */ crop_data->crop_mode |= CROP_MIRROR; switch (tolower((int) optarg[0])) { case 'h': crop_data->mirror = MIRROR_HORIZ; break; case 'v': crop_data->mirror = MIRROR_VERT; break; case 'b': crop_data->mirror = MIRROR_BOTH; break; default: TIFFError ("Flip mode must be horiz, vert, or both", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'H': /* set horizontal resolution to new value */ page->hres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'I': /* invert the color space, eg black to white */ crop_data->crop_mode |= CROP_INVERT; /* The PHOTOMETIC_INTERPRETATION tag may be updated */ if (streq(optarg, "black")) { crop_data->photometric = PHOTOMETRIC_MINISBLACK; continue; } if (streq(optarg, "white")) { crop_data->photometric = PHOTOMETRIC_MINISWHITE; continue; } if (streq(optarg, "data")) { crop_data->photometric = INVERT_DATA_ONLY; continue; } if (streq(optarg, "both")) { crop_data->photometric = INVERT_DATA_AND_TAG; continue; } TIFFError("Missing or unknown option for inverting PHOTOMETRIC_INTERPRETATION", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); break; case 'J': /* horizontal margin for sectioned ouput pages */ page->hmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'K': /* vertical margin for sectioned ouput pages*/ page->vmargin = atof(optarg); page->mode |= PAGE_MODE_MARGINS; break; case 'N': /* list of images to process */ for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_IMAGES)); (opt_ptr = strtok (NULL, ","))) { /* We do not know how many images are in file yet * so we build a list to include the maximum allowed * and follow it until we hit the end of the file. * Image count is not accurate for odd, even, last * so page numbers won't be valid either. */ if (streq(opt_ptr, "odd")) { for (j = 1; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = (MAX_IMAGES - 1) / 2; break; } else { if (streq(opt_ptr, "even")) { for (j = 2; j <= MAX_IMAGES; j += 2) imagelist[i++] = j; *image_count = MAX_IMAGES / 2; break; } else { if (streq(opt_ptr, "last")) imagelist[i++] = MAX_IMAGES; else /* single value between commas */ { sep = strpbrk(opt_ptr, ":-"); if (!sep) imagelist[i++] = atoi(opt_ptr); else { *sep = '\0'; start = atoi (opt_ptr); if (!strcmp((sep + 1), "last")) end = MAX_IMAGES; else end = atoi (sep + 1); for (j = start; j <= end && j - start + i < MAX_IMAGES; j++) imagelist[i++] = j; } } } } } *image_count = i; break; case 'O': /* page orientation */ switch (tolower((int) optarg[0])) { case 'a': page->orient = ORIENTATION_AUTO; break; case 'p': page->orient = ORIENTATION_PORTRAIT; break; case 'l': page->orient = ORIENTATION_LANDSCAPE; break; default: TIFFError ("Orientation must be portrait, landscape, or auto.", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'P': /* page size selection */ if (sscanf(optarg, "%lfx%lf", &page->width, &page->length) == 2) { strcpy (page->name, "Custom"); page->mode |= PAGE_MODE_PAPERSIZE; break; } if (get_page_geometry (optarg, page)) { if (!strcmp(optarg, "list")) { TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } TIFFError ("Invalid paper size", "%s", optarg); TIFFError ("", "Select one of:"); TIFFError("", "Name Width Length (in inches)"); for (i = 0; i < MAX_PAPERNAMES - 1; i++) TIFFError ("", "%-15.15s %5.2f %5.2f", PaperTable[i].name, PaperTable[i].width, PaperTable[i].length); exit (-1); } else { page->mode |= PAGE_MODE_PAPERSIZE; } break; case 'R': /* rotate image or cropped segment */ crop_data->crop_mode |= CROP_ROTATE; switch (strtoul(optarg, NULL, 0)) { case 90: crop_data->rotation = (uint16)90; break; case 180: crop_data->rotation = (uint16)180; break; case 270: crop_data->rotation = (uint16)270; break; default: TIFFError ("Rotation must be 90, 180, or 270 degrees clockwise", "%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'S': /* subdivide into Cols:Rows sections, eg 3:2 would be 3 across and 2 down */ sep = strpbrk(optarg, ",:"); if (sep) { *sep = '\0'; page->cols = atoi(optarg); page->rows = atoi(sep +1); } else { page->cols = atoi(optarg); page->rows = atoi(optarg); } if ((page->cols * page->rows) > MAX_SECTIONS) { TIFFError ("Limit for subdivisions, ie rows x columns, exceeded", "%d", MAX_SECTIONS); exit (-1); } page->mode |= PAGE_MODE_ROWSCOLS; break; case 'U': /* units for measurements and offsets */ if (streq(optarg, "in")) { crop_data->res_unit = RESUNIT_INCH; page->res_unit = RESUNIT_INCH; } else if (streq(optarg, "cm")) { crop_data->res_unit = RESUNIT_CENTIMETER; page->res_unit = RESUNIT_CENTIMETER; } else if (streq(optarg, "px")) { crop_data->res_unit = RESUNIT_NONE; page->res_unit = RESUNIT_NONE; } else { TIFFError ("Illegal unit of measure","%s", optarg); TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); } break; case 'V': /* set vertical resolution to new value */ page->vres = atof (optarg); page->mode |= PAGE_MODE_RESOLUTION; break; case 'X': /* selection width */ crop_data->crop_mode |= CROP_WIDTH; crop_data->width = atof(optarg); break; case 'Y': /* selection length */ crop_data->crop_mode |= CROP_LENGTH; crop_data->length = atof(optarg); break; case 'Z': /* zones of an image X:Y read as zone X of Y */ crop_data->crop_mode |= CROP_ZONES; for (i = 0, opt_ptr = strtok (optarg, ","); ((opt_ptr != NULL) && (i < MAX_REGIONS)); (opt_ptr = strtok (NULL, ",")), i++) { crop_data->zones++; opt_offset = strchr(opt_ptr, ':'); if (!opt_offset) { TIFFError("Wrong parameter syntax for -Z", "tiffcrop -h"); exit(-1); } *opt_offset = '\0'; crop_data->zonelist[i].position = atoi(opt_ptr); crop_data->zonelist[i].total = atoi(opt_offset + 1); } /* check for remaining elements over MAX_REGIONS */ if ((opt_ptr != NULL) && (i >= MAX_REGIONS)) { TIFFError("Zone list exceeds region limit", "%d", MAX_REGIONS); exit (-1); } break; case '?': TIFFError ("For valid options type", "tiffcrop -h"); exit (-1); /*NOTREACHED*/ } } } /* end process_command_opts */ /* Start a new output file if one has not been previously opened or * autoindex is set to non-zero. Update page and file counters * so TIFFTAG PAGENUM will be correct in image. */ static int update_output_file (TIFF **tiffout, char *mode, int autoindex, char *outname, unsigned int *page) { static int findex = 0; /* file sequence indicator */ char *sep; char filenum[16]; char export_ext[16]; char exportname[PATH_MAX]; if (autoindex && (*tiffout != NULL)) { /* Close any export file that was previously opened */ TIFFClose (*tiffout); *tiffout = NULL; } strcpy (export_ext, ".tiff"); memset (exportname, '\0', PATH_MAX); /* Leave room for page number portion of the new filename */ strncpy (exportname, outname, PATH_MAX - 16); if (*tiffout == NULL) /* This is a new export file */ { if (autoindex) { /* create a new filename for each export */ findex++; if ((sep = strstr(exportname, ".tif")) || (sep = strstr(exportname, ".TIF"))) { strncpy (export_ext, sep, 5); *sep = '\0'; } else strncpy (export_ext, ".tiff", 5); export_ext[5] = '\0'; /* MAX_EXPORT_PAGES limited to 6 digits to prevent string overflow of pathname */ if (findex > MAX_EXPORT_PAGES) { TIFFError("update_output_file", "Maximum of %d pages per file exceeded", MAX_EXPORT_PAGES); return 1; } snprintf(filenum, sizeof(filenum), "-%03d%s", findex, export_ext); filenum[14] = '\0'; strncat (exportname, filenum, 15); } exportname[PATH_MAX - 1] = '\0'; *tiffout = TIFFOpen(exportname, mode); if (*tiffout == NULL) { TIFFError("update_output_file", "Unable to open output file %s", exportname); return 1; } *page = 0; return 0; } else (*page)++; return 0; } /* end update_output_file */ int main(int argc, char* argv[]) { #if !HAVE_DECL_OPTARG extern int optind; #endif uint16 defconfig = (uint16) -1; uint16 deffillorder = 0; uint32 deftilewidth = (uint32) 0; uint32 deftilelength = (uint32) 0; uint32 defrowsperstrip = (uint32) 0; uint32 dirnum = 0; TIFF *in = NULL; TIFF *out = NULL; char mode[10]; char *mp = mode; /** RJN additions **/ struct image_data image; /* Image parameters for one image */ struct crop_mask crop; /* Cropping parameters for all images */ struct pagedef page; /* Page definition for output pages */ struct pageseg sections[MAX_SECTIONS]; /* Sections of one output page */ struct buffinfo seg_buffs[MAX_SECTIONS]; /* Segment buffer sizes and pointers */ struct dump_opts dump; /* Data dump options */ unsigned char *read_buff = NULL; /* Input image data buffer */ unsigned char *crop_buff = NULL; /* Crop area buffer */ unsigned char *sect_buff = NULL; /* Image section buffer */ unsigned char *sect_src = NULL; /* Image section buffer pointer */ unsigned int imagelist[MAX_IMAGES + 1]; /* individually specified images */ unsigned int image_count = 0; unsigned int dump_images = 0; unsigned int next_image = 0; unsigned int next_page = 0; unsigned int total_pages = 0; unsigned int total_images = 0; unsigned int end_of_input = FALSE; int seg, length; char temp_filename[PATH_MAX + 1]; little_endian = *((unsigned char *)&little_endian) & '1'; initImageData(&image); initCropMasks(&crop); initPageSetup(&page, sections, seg_buffs); initDumpOptions(&dump); process_command_opts (argc, argv, mp, mode, &dirnum, &defconfig, &deffillorder, &deftilewidth, &deftilelength, &defrowsperstrip, &crop, &page, &dump, imagelist, &image_count); if (argc - optind < 2) usage(); if ((argc - optind) == 2) pageNum = -1; else total_images = 0; /* read multiple input files and write to output file(s) */ while (optind < argc - 1) { in = TIFFOpen (argv[optind], "r"); if (in == NULL) return (-3); /* If only one input file is specified, we can use directory count */ total_images = TIFFNumberOfDirectories(in); if (image_count == 0) { dirnum = 0; total_pages = total_images; /* Only valid with single input file */ } else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; /* Total pages only valid for enumerated list of pages not derived * using odd, even, or last keywords. */ if (image_count > total_images) image_count = total_images; total_pages = image_count; } /* MAX_IMAGES is used for special case "last" in selection list */ if (dirnum == (MAX_IMAGES - 1)) dirnum = total_images - 1; if (dirnum > (total_images)) { TIFFError (TIFFFileName(in), "Invalid image number %d, File contains only %d images", (int)dirnum + 1, total_images); if (out != NULL) (void) TIFFClose(out); return (1); } if (dirnum != 0 && !TIFFSetDirectory(in, (tdir_t)dirnum)) { TIFFError(TIFFFileName(in),"Error, setting subdirectory at %d", dirnum); if (out != NULL) (void) TIFFClose(out); return (1); } end_of_input = FALSE; while (end_of_input == FALSE) { config = defconfig; compression = defcompression; predictor = defpredictor; fillorder = deffillorder; rowsperstrip = defrowsperstrip; tilewidth = deftilewidth; tilelength = deftilelength; g3opts = defg3opts; if (dump.format != DUMP_NONE) { /* manage input and/or output dump files here */ dump_images++; length = strlen(dump.infilename); if (length > 0) { if (dump.infile != NULL) fclose (dump.infile); /* dump.infilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-read-%03d.%s", dump.infilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.infile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.infile, dump.format, "Reading image","%d from %s", dump_images, TIFFFileName(in)); } length = strlen(dump.outfilename); if (length > 0) { if (dump.outfile != NULL) fclose (dump.outfile); /* dump.outfilename is guaranteed to be NUL termimated and have 20 bytes fewer than PATH_MAX */ snprintf(temp_filename, sizeof(temp_filename), "%s-write-%03d.%s", dump.outfilename, dump_images, (dump.format == DUMP_TEXT) ? "txt" : "raw"); if ((dump.outfile = fopen(temp_filename, dump.mode)) == NULL) { TIFFError ("Unable to open dump file for writing", "%s", temp_filename); exit (-1); } dump_info(dump.outfile, dump.format, "Writing image","%d from %s", dump_images, TIFFFileName(in)); } } if (dump.debug) TIFFError("main", "Reading image %4d of %4d total pages.", dirnum + 1, total_pages); if (loadImage(in, &image, &dump, &read_buff)) { TIFFError("main", "Unable to load source image"); exit (-1); } /* Correct the image orientation if it was not ORIENTATION_TOPLEFT. */ if (image.adjustments != 0) { if (correct_orientation(&image, &read_buff)) TIFFError("main", "Unable to correct image orientation"); } if (getCropOffsets(&image, &crop, &dump)) { TIFFError("main", "Unable to define crop regions"); exit (-1); } if (crop.selections > 0) { if (processCropSelections(&image, &crop, &read_buff, seg_buffs)) { TIFFError("main", "Unable to process image selections"); exit (-1); } } else /* Single image segment without zones or regions */ { if (createCroppedImage(&image, &crop, &read_buff, &crop_buff)) { TIFFError("main", "Unable to create output image"); exit (-1); } } if (page.mode == PAGE_MODE_NONE) { /* Whole image or sections not based on output page size */ if (crop.selections > 0) { writeSelections(in, &out, &crop, &image, &dump, seg_buffs, mp, argv[argc - 1], &next_page, total_pages); } else /* One file all images and sections */ { if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeCroppedImage(in, out, &image, &dump,crop.combined_width, crop.combined_length, crop_buff, next_page, total_pages)) { TIFFError("main", "Unable to write new image"); exit (-1); } } } else { /* If we used a crop buffer, our data is there, otherwise it is * in the read_buffer */ if (crop_buff != NULL) sect_src = crop_buff; else sect_src = read_buff; /* Break input image into pages or rows and columns */ if (computeOutputPixelOffsets(&crop, &image, &page, sections, &dump)) { TIFFError("main", "Unable to compute output section data"); exit (-1); } /* If there are multiple files on the command line, the final one is assumed * to be the output filename into which the images are written. */ if (update_output_file (&out, mp, crop.exp_mode, argv[argc - 1], &next_page)) exit (1); if (writeImageSections(in, out, &image, &page, sections, &dump, sect_src, &sect_buff)) { TIFFError("main", "Unable to write image sections"); exit (-1); } } /* No image list specified, just read the next image */ if (image_count == 0) dirnum++; else { dirnum = (tdir_t)(imagelist[next_image] - 1); next_image++; } if (dirnum == MAX_IMAGES - 1) dirnum = TIFFNumberOfDirectories(in) - 1; if (!TIFFSetDirectory(in, (tdir_t)dirnum)) end_of_input = TRUE; } TIFFClose(in); optind++; } /* If we did not use the read buffer as the crop buffer */ if (read_buff) _TIFFfree(read_buff); if (crop_buff) _TIFFfree(crop_buff); if (sect_buff) _TIFFfree(sect_buff); /* Clean up any segment buffers used for zones or regions */ for (seg = 0; seg < crop.selections; seg++) _TIFFfree (seg_buffs[seg].buffer); if (dump.format != DUMP_NONE) { if (dump.infile != NULL) fclose (dump.infile); if (dump.outfile != NULL) { dump_info (dump.outfile, dump.format, "", "Completed run for %s", TIFFFileName(out)); fclose (dump.outfile); } } TIFFClose(out); return (0); } /* end main */ /* Debugging functions */ static int dump_data (FILE *dumpfile, int format, char *dump_tag, unsigned char *data, uint32 count) { int j, k; uint32 i; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (i = 0; i < count; i++) { for (j = 0, k = 7; j < 8; j++, k--) { bitset = (*(data + i)) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s", dump_array); } fprintf (dumpfile,"\n"); } else { if ((fwrite (data, 1, count, dumpfile)) != count) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_byte (FILE *dumpfile, int format, char *dump_tag, unsigned char data) { int j, k; char dump_array[10]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 7; j < 8; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); } dump_array[8] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 1, 1, dumpfile)) != 1) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_short (FILE *dumpfile, int format, char *dump_tag, uint16 data) { int j, k; char dump_array[20]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 15; k >= 0; j++, k--) { bitset = data & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[17] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 2, 1, dumpfile)) != 2) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_long (FILE *dumpfile, int format, char *dump_tag, uint32 data) { int j, k; char dump_array[40]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 31; k >= 0; j++, k--) { bitset = data & (((uint32)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[35] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 4, 1, dumpfile)) != 4) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static int dump_wide (FILE *dumpfile, int format, char *dump_tag, uint64 data) { int j, k; char dump_array[80]; unsigned char bitset; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } if (format == DUMP_TEXT) { fprintf (dumpfile," %s ", dump_tag); for (j = 0, k = 63; k >= 0; j++, k--) { bitset = data & (((uint64)1 << k)) ? 1 : 0; sprintf(&dump_array[j], (bitset) ? "1" : "0"); if ((k % 8) == 0) sprintf(&dump_array[++j], " "); } dump_array[71] = '\0'; fprintf (dumpfile," %s\n", dump_array); } else { if ((fwrite (&data, 8, 1, dumpfile)) != 8) { TIFFError ("", "Unable to write binary data to dump file"); return (1); } } return (0); } static void dump_info(FILE *dumpfile, int format, char *prefix, char *msg, ...) { if (format == DUMP_TEXT) { va_list ap; va_start(ap, msg); fprintf(dumpfile, "%s ", prefix); vfprintf(dumpfile, msg, ap); fprintf(dumpfile, "\n"); va_end(ap); } } static int dump_buffer (FILE* dumpfile, int format, uint32 rows, uint32 width, uint32 row, unsigned char *buff) { int j, k; uint32 i; unsigned char * dump_ptr; if (dumpfile == NULL) { TIFFError ("", "Invalid FILE pointer for dump file"); return (1); } for (i = 0; i < rows; i++) { dump_ptr = buff + (i * width); if (format == DUMP_TEXT) dump_info (dumpfile, format, "", "Row %4d, %d bytes at offset %d", row + i + 1, width, row * width); for (j = 0, k = width; k >= 10; j += 10, k -= 10, dump_ptr += 10) dump_data (dumpfile, format, "", dump_ptr, 10); if (k > 0) dump_data (dumpfile, format, "", dump_ptr, k); } return (0); } /* Extract one or more samples from an interleaved buffer. If count == 1, * only the sample plane indicated by sample will be extracted. If count > 1, * count samples beginning at sample will be extracted. Portions of a * scanline can be extracted by specifying a start and end value. */ static int extractContigSamplesBytes (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int i, bytes_per_sample, sindex; uint32 col, dst_rowsize, bit_offset; uint32 src_byte /*, src_bit */; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesBytes","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesBytes", "Invalid end column value %d ignored", end); end = cols; } dst_rowsize = (bps * (end - start) * count) / 8; bytes_per_sample = (bps + 7) / 8; /* Optimize case for copying all samples */ if (count == spp) { src = in + (start * spp * bytes_per_sample); _TIFFmemcpy (dst, src, dst_rowsize); } else { for (col = start; col < end; col++) { for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { bit_offset = col * bps * spp; if (sindex == 0) { src_byte = bit_offset / 8; /* src_bit = bit_offset % 8; */ } else { src_byte = (bit_offset + (sindex * bps)) / 8; /* src_bit = (bit_offset + (sindex * bps)) % 8; */ } src = in + src_byte; for (i = 0; i < bytes_per_sample; i++) *dst++ = *src++; } } } return (0); } /* end extractContigSamplesBytes */ static int extractContigSamples8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = (buff2 | (buff1 >> ready_bits)); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamples8bits */ static int extractContigSamples16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamples16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ { bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamples16bits */ static int extractContigSamples24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = 0; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamples24bits */ static int extractContigSamples32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamples32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamples32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamples32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = 0; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamples32bits */ static int extractContigSamplesShifted8bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted8bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted8bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*src) & matchbits) << (src_bit); if ((col == start) && (sindex == sample)) buff2 = *src & ((uint8)-1) << (shift); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ |= buff2; buff2 = buff1; ready_bits -= 8; } else buff2 = buff2 | (buff1 >> ready_bits); ready_bits += bps; } } while (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted8bits */ static int extractContigSamplesShifted16bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *src = in; uint8 *dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("extractContigSamplesShifted16bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted16bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint16)-1 >> (16 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint16)-1) << (8 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 8) /* add another bps bits to the buffer */ buff2 = buff2 | (buff1 >> ready_bits); else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted16bits */ static int extractContigSamplesShifted24bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0; uint32 col, src_byte, src_bit, bit_offset; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted24bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted24bits", "Invalid end column value %d ignored", end); end = cols; } ready_bits = shift; maskbits = (uint32)-1 >> ( 32 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; if ((col == start) && (sindex == sample)) buff2 = buff1 & ((uint32)-1) << (16 - shift); buff1 = (buff1 & matchbits) << (src_bit); if (ready_bits < 16) /* add another bps bits to the buffer */ { bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted24bits */ static int extractContigSamplesShifted32bits (uint8 *in, uint8 *out, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, tsample_t count, uint32 start, uint32 end, int shift) { int ready_bits = 0, sindex = 0 /*, shift_width = 0 */; uint32 col, src_byte, src_bit, bit_offset; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *src = in; uint8 *dst = out; if ((in == NULL) || (out == NULL)) { TIFFError("extractContigSamplesShifted32bits","Invalid input or output buffer"); return (1); } if ((start > end) || (start > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid start column value %d ignored", start); start = 0; } if ((end == 0) || (end > cols)) { TIFFError ("extractContigSamplesShifted32bits", "Invalid end column value %d ignored", end); end = cols; } /* shift_width = ((bps + 7) / 8) + 1; */ ready_bits = shift; maskbits = (uint64)-1 >> ( 64 - bps); for (col = start; col < end; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps * spp; for (sindex = sample; (sindex < spp) && (sindex < (sample + count)); sindex++) { if (sindex == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sindex * bps)) / 8; src_bit = (bit_offset + (sindex * bps)) % 8; } src = in + src_byte; matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; if ((col == start) && (sindex == sample)) buff2 = buff3 & ((uint64)-1) << (32 - shift); buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end extractContigSamplesShifted32bits */ static int extractContigSamplesToBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, tsample_t sample, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row, first_col = 0; uint32 dst_rowsize, dst_offset; tsample_t count = 1; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src_rowsize = ((bps * spp * cols) + 7) / 8; dst_rowsize = ((bps * cols) + 7) / 8; if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, first_col, cols)) return (1); break; default: TIFFError ("extractContigSamplesToBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToBuffer */ static int extractContigSamplesToTileBuffer(uint8 *out, uint8 *in, uint32 rows, uint32 cols, uint32 imagewidth, uint32 tilewidth, tsample_t sample, uint16 count, uint16 spp, uint16 bps, struct dump_opts *dump) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, src_offset, row; uint32 dst_rowsize, dst_offset; uint8 *src, *dst; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } if ((dump->outfile != NULL) && (dump->level == 4)) { dump_info (dump->outfile, dump->format, "extractContigSamplesToTileBuffer", "Sample %d, %d rows", sample + 1, rows + 1); } src_rowsize = ((bps * spp * imagewidth) + 7) / 8; dst_rowsize = ((bps * tilewidth * count) + 7) / 8; for (row = 0; row < rows; row++) { src_offset = row * src_rowsize; dst_offset = row * dst_rowsize; src = in + src_offset; dst = out + dst_offset; /* pack the data into the scanline */ switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 1: if (bps == 1) { if (extractContigSamples8bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; } else if (extractContigSamples16bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 2: if (extractContigSamples24bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; case 3: case 4: case 5: if (extractContigSamples32bits (src, dst, cols, sample, spp, bps, count, 0, cols)) return (1); break; default: TIFFError ("extractContigSamplesToTileBuffer", "Unsupported bit depth: %d", bps); return (1); } if ((dump->outfile != NULL) && (dump->level == 4)) dump_buffer(dump->outfile, dump->format, 1, dst_rowsize, row, dst); } return (0); } /* end extractContigSamplesToTileBuffer */ static int readContigStripsIntoBuffer (TIFF* in, uint8* buf) { uint8* bufp = buf; int32 bytes_read = 0; uint32 strip, nstrips = TIFFNumberOfStrips(in); uint32 stripsize = TIFFStripSize(in); uint32 rows = 0; uint32 rps = TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); tsize_t scanline_size = TIFFScanlineSize(in); if (scanline_size == 0) { TIFFError("", "TIFF scanline size is zero!"); return 0; } for (strip = 0; strip < nstrips; strip++) { bytes_read = TIFFReadEncodedStrip (in, strip, bufp, -1); rows = bytes_read / scanline_size; if ((strip < (nstrips - 1)) && (bytes_read != (int32)stripsize)) TIFFError("", "Strip %d: read %lu bytes, strip size %lu", (int)strip + 1, (unsigned long) bytes_read, (unsigned long)stripsize); if (bytes_read < 0 && !ignore) { TIFFError("", "Error reading strip %lu after %lu rows", (unsigned long) strip, (unsigned long)rows); return 0; } bufp += bytes_read; } return 1; } /* end readContigStripsIntoBuffer */ static int combineSeparateSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, row_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * spp * cols) + 7) / 8; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); row_offset = row * src_rowsize; for (col = 0; col < cols; col++) { col_offset = row_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); src += bytes_per_sample; dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamplesBytes */ static int combineSeparateSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; /* int bytes_per_sample = 0; */ uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples8bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples8bits */ static int combineSeparateSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples16bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples16bits */ static int combineSeparateSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0 */; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples24bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateSamples24bits */ static int combineSeparateSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, bytes_per_sample = 0, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateSamples32bits","Invalid input or output buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ src_rowsize = ((bps * cols) + 7) / 8; dst_rowsize = ((bps * cols * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateSamples32bits */ static int combineSeparateTileSamplesBytes (unsigned char *srcbuffs[], unsigned char *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int i, bytes_per_sample; uint32 row, col, col_offset, src_rowsize, dst_rowsize, src_offset; unsigned char *src; unsigned char *dst; tsample_t s; src = srcbuffs[0]; dst = out; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamplesBytes","Invalid buffer address"); return (1); } bytes_per_sample = (bps + 7) / 8; src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = imagewidth * bytes_per_sample * spp; for (row = 0; row < rows; row++) { if ((dumpfile != NULL) && (level == 2)) { for (s = 0; s < spp; s++) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Input data, Sample %d", s); dump_buffer(dumpfile, format, 1, cols, row, srcbuffs[s] + (row * src_rowsize)); } } dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; #ifdef DEVELMODE TIFFError("","Tile row %4d, Src offset %6d Dst offset %6d", row, src_offset, dst - out); #endif for (col = 0; col < cols; col++) { col_offset = src_offset + (col * (bps / 8)); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = srcbuffs[s] + col_offset; for (i = 0; i < bytes_per_sample; i++) *(dst + i) = *(src + i); dst += bytes_per_sample; } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamplesBytes","Output data, combined samples"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamplesBytes */ static int combineSeparateTileSamples8bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize, src_offset; uint32 bit_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint8 maskbits = 0, matchbits = 0; uint8 buff1 = 0, buff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples8bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint8)-1 >> ( 8 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (8 - src_bit - bps); /* load up next sample from each plane */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; buff1 = ((*src) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; strcpy (action, "Flush"); } else { buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Match bits", matchbits); dump_byte (dumpfile, format, "Src bits", *src); dump_byte (dumpfile, format, "Buff1 bits", buff1); dump_byte (dumpfile, format, "Buff2 bits", buff2); dump_info (dumpfile, format, "","%s", action); } } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", buff1); } } if ((dumpfile != NULL) && (level >= 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples8bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples8bits */ static int combineSeparateTileSamples16bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint16 maskbits = 0, matchbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples16bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint16)-1 >> (16 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (16 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_short (dumpfile, format, "Match bits", matchbits); dump_data (dumpfile, format, "Src bits", src, 2); dump_short (dumpfile, format, "Buff1 bits", buff1); dump_short (dumpfile, format, "Buff2 bits", buff2); dump_byte (dumpfile, format, "Write byte", bytebuff); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_byte (dumpfile, format, "Final bits", bytebuff); } } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples16bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples16bits */ static int combineSeparateTileSamples24bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0; uint32 src_rowsize, dst_rowsize; uint32 bit_offset, src_offset; uint32 row, col, src_byte = 0, src_bit = 0; uint32 maskbits = 0, matchbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples24bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint32)-1 >> ( 32 - bps); for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (32 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Samples %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "","Ready bits: %d, %s", ready_bits, action); } } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples24bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out + (row * dst_rowsize)); } } return (0); } /* end combineSeparateTileSamples24bits */ static int combineSeparateTileSamples32bits (uint8 *in[], uint8 *out, uint32 cols, uint32 rows, uint32 imagewidth, uint32 tw, uint16 spp, uint16 bps, FILE *dumpfile, int format, int level) { int ready_bits = 0 /*, shift_width = 0 */; uint32 src_rowsize, dst_rowsize, bit_offset, src_offset; uint32 src_byte = 0, src_bit = 0; uint32 row, col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; tsample_t s; unsigned char *src = in[0]; unsigned char *dst = out; char action[8]; if ((src == NULL) || (dst == NULL)) { TIFFError("combineSeparateTileSamples32bits","Invalid input or output buffer"); return (1); } src_rowsize = ((bps * tw) + 7) / 8; dst_rowsize = ((imagewidth * bps * spp) + 7) / 8; maskbits = (uint64)-1 >> ( 64 - bps); /* shift_width = ((bps + 7) / 8) + 1; */ for (row = 0; row < rows; row++) { ready_bits = 0; buff1 = buff2 = 0; dst = out + (row * dst_rowsize); src_offset = row * src_rowsize; for (col = 0; col < cols; col++) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = col * bps; src_byte = bit_offset / 8; src_bit = bit_offset % 8; matchbits = maskbits << (64 - src_bit - bps); for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { src = in[s] + src_offset + src_byte; if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 32) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); strcpy (action, "Flush"); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); strcpy (action, "Update"); } ready_bits += bps; if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Sample %d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, s, src_byte, src_bit, dst - out); dump_wide (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 8); dump_wide (dumpfile, format, "Buff1 bits ", buff1); dump_wide (dumpfile, format, "Buff2 bits ", buff2); dump_info (dumpfile, format, "", "Ready bits: %d, %s", ready_bits, action); } } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } if ((dumpfile != NULL) && (level == 3)) { dump_info (dumpfile, format, "", "Row %3d, Col %3d, Src byte offset %3d bit offset %2d Dst offset %3d", row + 1, col + 1, src_byte, src_bit, dst - out); dump_long (dumpfile, format, "Match bits ", matchbits); dump_data (dumpfile, format, "Src bits ", src, 4); dump_long (dumpfile, format, "Buff1 bits ", buff1); dump_long (dumpfile, format, "Buff2 bits ", buff2); dump_byte (dumpfile, format, "Write bits1", bytebuff1); dump_byte (dumpfile, format, "Write bits2", bytebuff2); dump_info (dumpfile, format, "", "Ready bits: %2d", ready_bits); } if ((dumpfile != NULL) && (level == 2)) { dump_info (dumpfile, format, "combineSeparateTileSamples32bits","Output data"); dump_buffer(dumpfile, format, 1, dst_rowsize, row, out); } } return (0); } /* end combineSeparateTileSamples32bits */ static int readSeparateStripsIntoBuffer (TIFF *in, uint8 *obuf, uint32 length, uint32 width, uint16 spp, struct dump_opts *dump) { int i, bytes_per_sample, bytes_per_pixel, shift_width, result = 1; uint32 j; int32 bytes_read = 0; uint16 bps, planar; uint32 nstrips; uint32 strips_per_sample; uint32 src_rowsize, dst_rowsize, rows_processed, rps; uint32 rows_this_strip = 0; tsample_t s; tstrip_t strip; tsize_t scanlinesize = TIFFScanlineSize(in); tsize_t stripsize = TIFFStripSize(in); unsigned char *srcbuffs[MAX_SAMPLES]; unsigned char *buff = NULL; unsigned char *dst = NULL; if (obuf == NULL) { TIFFError("readSeparateStripsIntoBuffer","Invalid buffer argument"); return (0); } memset (srcbuffs, '\0', sizeof(srcbuffs)); TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rps); if (rps > length) rps = length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; src_rowsize = ((bps * width) + 7) / 8; dst_rowsize = ((bps * width * spp) + 7) / 8; dst = obuf; if ((dump->infile != NULL) && (dump->level == 3)) { dump_info (dump->infile, dump->format, "", "Image width %d, length %d, Scanline size, %4d bytes", width, length, scanlinesize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d, Shift width %d", bps, spp, shift_width); } /* Libtiff seems to assume/require that data for separate planes are * written one complete plane after another and not interleaved in any way. * Multiple scanlines and possibly strips of the same plane must be * written before data for any other plane. */ nstrips = TIFFNumberOfStrips(in); strips_per_sample = nstrips /spp; for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { srcbuffs[s] = NULL; buff = _TIFFmalloc(stripsize); if (!buff) { TIFFError ("readSeparateStripsIntoBuffer", "Unable to allocate strip read buffer for sample %d", s); for (i = 0; i < s; i++) _TIFFfree (srcbuffs[i]); return 0; } srcbuffs[s] = buff; } rows_processed = 0; for (j = 0; (j < strips_per_sample) && (result == 1); j++) { for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; strip = (s * strips_per_sample) + j; bytes_read = TIFFReadEncodedStrip (in, strip, buff, stripsize); rows_this_strip = bytes_read / src_rowsize; if (bytes_read < 0 && !ignore) { TIFFError(TIFFFileName(in), "Error, can't read strip %lu for sample %d", (unsigned long) strip, s + 1); result = 0; break; } #ifdef DEVELMODE TIFFError("", "Strip %2d, read %5d bytes for %4d scanlines, shift width %d", strip, bytes_read, rows_this_strip, shift_width); #endif } if (rps > rows_this_strip) rps = rows_this_strip; dst = obuf + (dst_rowsize * rows_processed); if ((bps % 8) == 0) { if (combineSeparateSamplesBytes (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } } else { switch (shift_width) { case 1: if (combineSeparateSamples8bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 2: if (combineSeparateSamples16bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 3: if (combineSeparateSamples24bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; case 4: case 5: case 6: case 7: case 8: if (combineSeparateSamples32bits (srcbuffs, dst, width, rps, spp, bps, dump->infile, dump->format, dump->level)) { result = 0; break; } break; default: TIFFError ("readSeparateStripsIntoBuffer", "Unsupported bit depth: %d", bps); result = 0; break; } } if ((rows_processed + rps) > length) { rows_processed = length; rps = length - rows_processed; } else rows_processed += rps; } /* free any buffers allocated for each plane or scanline and * any temporary buffers */ for (s = 0; (s < spp) && (s < MAX_SAMPLES); s++) { buff = srcbuffs[s]; if (buff != NULL) _TIFFfree(buff); } return (result); } /* end readSeparateStripsIntoBuffer */ static int get_page_geometry (char *name, struct pagedef *page) { char *ptr; int n; for (ptr = name; *ptr; ptr++) *ptr = (char)tolower((int)*ptr); for (n = 0; n < MAX_PAPERNAMES; n++) { if (strcmp(name, PaperTable[n].name) == 0) { page->width = PaperTable[n].width; page->length = PaperTable[n].length; strncpy (page->name, PaperTable[n].name, 15); page->name[15] = '\0'; return (0); } } return (1); } static void initPageSetup (struct pagedef *page, struct pageseg *pagelist, struct buffinfo seg_buffs[]) { int i; strcpy (page->name, ""); page->mode = PAGE_MODE_NONE; page->res_unit = RESUNIT_NONE; page->hres = 0.0; page->vres = 0.0; page->width = 0.0; page->length = 0.0; page->hmargin = 0.0; page->vmargin = 0.0; page->rows = 0; page->cols = 0; page->orient = ORIENTATION_NONE; for (i = 0; i < MAX_SECTIONS; i++) { pagelist[i].x1 = (uint32)0; pagelist[i].x2 = (uint32)0; pagelist[i].y1 = (uint32)0; pagelist[i].y2 = (uint32)0; pagelist[i].buffsize = (uint32)0; pagelist[i].position = 0; pagelist[i].total = 0; } for (i = 0; i < MAX_OUTBUFFS; i++) { seg_buffs[i].size = 0; seg_buffs[i].buffer = NULL; } } static void initImageData (struct image_data *image) { image->xres = 0.0; image->yres = 0.0; image->width = 0; image->length = 0; image->res_unit = RESUNIT_NONE; image->bps = 0; image->spp = 0; image->planar = 0; image->photometric = 0; image->orientation = 0; image->compression = COMPRESSION_NONE; image->adjustments = 0; } static void initCropMasks (struct crop_mask *cps) { int i; cps->crop_mode = CROP_NONE; cps->res_unit = RESUNIT_NONE; cps->edge_ref = EDGE_TOP; cps->width = 0; cps->length = 0; for (i = 0; i < 4; i++) cps->margins[i] = 0.0; cps->bufftotal = (uint32)0; cps->combined_width = (uint32)0; cps->combined_length = (uint32)0; cps->rotation = (uint16)0; cps->photometric = INVERT_DATA_AND_TAG; cps->mirror = (uint16)0; cps->invert = (uint16)0; cps->zones = (uint32)0; cps->regions = (uint32)0; for (i = 0; i < MAX_REGIONS; i++) { cps->corners[i].X1 = 0.0; cps->corners[i].X2 = 0.0; cps->corners[i].Y1 = 0.0; cps->corners[i].Y2 = 0.0; cps->regionlist[i].x1 = 0; cps->regionlist[i].x2 = 0; cps->regionlist[i].y1 = 0; cps->regionlist[i].y2 = 0; cps->regionlist[i].width = 0; cps->regionlist[i].length = 0; cps->regionlist[i].buffsize = 0; cps->regionlist[i].buffptr = NULL; cps->zonelist[i].position = 0; cps->zonelist[i].total = 0; } cps->exp_mode = ONE_FILE_COMPOSITE; cps->img_mode = COMPOSITE_IMAGES; } static void initDumpOptions(struct dump_opts *dump) { dump->debug = 0; dump->format = DUMP_NONE; dump->level = 1; sprintf (dump->mode, "w"); memset (dump->infilename, '\0', PATH_MAX + 1); memset (dump->outfilename, '\0',PATH_MAX + 1); dump->infile = NULL; dump->outfile = NULL; } /* Compute pixel offsets into the image for margins and fixed regions */ static int computeInputPixelOffsets(struct crop_mask *crop, struct image_data *image, struct offset *off) { double scale; float xres, yres; /* Values for these offsets are in pixels from start of image, not bytes, * and are indexed from zero to width - 1 or length - 1 */ uint32 tmargin, bmargin, lmargin, rmargin; uint32 startx, endx; /* offsets of first and last columns to extract */ uint32 starty, endy; /* offsets of first and last row to extract */ uint32 width, length, crop_width, crop_length; uint32 i, max_width, max_length, zwidth, zlength, buffsize; uint32 x1, x2, y1, y2; if (image->res_unit != RESUNIT_INCH && image->res_unit != RESUNIT_CENTIMETER) { xres = 1.0; yres = 1.0; } else { if (((image->xres == 0) || (image->yres == 0)) && (crop->res_unit != RESUNIT_NONE) && ((crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH))) { TIFFError("computeInputPixelOffsets", "Cannot compute margins or fixed size sections without image resolution"); TIFFError("computeInputPixelOffsets", "Specify units in pixels and try again"); return (-1); } xres = image->xres; yres = image->yres; } /* Translate user units to image units */ scale = 1.0; switch (crop->res_unit) { case RESUNIT_CENTIMETER: if (image->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (image->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } if (crop->crop_mode & CROP_REGIONS) { max_width = max_length = 0; for (i = 0; i < crop->regions; i++) { if ((crop->res_unit == RESUNIT_INCH) || (crop->res_unit == RESUNIT_CENTIMETER)) { x1 = (uint32) (crop->corners[i].X1 * scale * xres); x2 = (uint32) (crop->corners[i].X2 * scale * xres); y1 = (uint32) (crop->corners[i].Y1 * scale * yres); y2 = (uint32) (crop->corners[i].Y2 * scale * yres); } else { x1 = (uint32) (crop->corners[i].X1); x2 = (uint32) (crop->corners[i].X2); y1 = (uint32) (crop->corners[i].Y1); y2 = (uint32) (crop->corners[i].Y2); } if (x1 < 1) crop->regionlist[i].x1 = 0; else crop->regionlist[i].x1 = (uint32) (x1 - 1); if (x2 > image->width - 1) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = (uint32) (x2 - 1); zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; if (y1 < 1) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = (uint32) (y1 - 1); if (y2 > image->length - 1) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = (uint32) (y2 - 1); zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; if (zwidth > max_width) max_width = zwidth; if (zlength > max_length) max_length = zlength; buffsize = (uint32) (((zwidth * image->bps * image->spp + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (crop->img_mode == COMPOSITE_IMAGES) { switch (crop->edge_ref) { case EDGE_LEFT: case EDGE_RIGHT: crop->combined_length = zlength; crop->combined_width += zwidth; break; case EDGE_BOTTOM: case EDGE_TOP: /* width from left, length from top */ default: crop->combined_width = zwidth; crop->combined_length += zlength; break; } } } return (0); } /* Convert crop margins into offsets into image * Margins are expressed as pixel rows and columns, not bytes */ if (crop->crop_mode & CROP_MARGINS) { if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { /* User has specified pixels as reference unit */ tmargin = (uint32)(crop->margins[0]); lmargin = (uint32)(crop->margins[1]); bmargin = (uint32)(crop->margins[2]); rmargin = (uint32)(crop->margins[3]); } else { /* inches or centimeters specified */ tmargin = (uint32)(crop->margins[0] * scale * yres); lmargin = (uint32)(crop->margins[1] * scale * xres); bmargin = (uint32)(crop->margins[2] * scale * yres); rmargin = (uint32)(crop->margins[3] * scale * xres); } if ((lmargin + rmargin) > image->width) { TIFFError("computeInputPixelOffsets", "Combined left and right margins exceed image width"); lmargin = (uint32) 0; rmargin = (uint32) 0; return (-1); } if ((tmargin + bmargin) > image->length) { TIFFError("computeInputPixelOffsets", "Combined top and bottom margins exceed image length"); tmargin = (uint32) 0; bmargin = (uint32) 0; return (-1); } } else { /* no margins requested */ tmargin = (uint32) 0; lmargin = (uint32) 0; bmargin = (uint32) 0; rmargin = (uint32) 0; } /* Width, height, and margins are expressed as pixel offsets into image */ if (crop->res_unit != RESUNIT_INCH && crop->res_unit != RESUNIT_CENTIMETER) { if (crop->crop_mode & CROP_WIDTH) width = (uint32)crop->width; else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)crop->length; else length = image->length - tmargin - bmargin; } else { if (crop->crop_mode & CROP_WIDTH) width = (uint32)(crop->width * scale * image->xres); else width = image->width - lmargin - rmargin; if (crop->crop_mode & CROP_LENGTH) length = (uint32)(crop->length * scale * image->yres); else length = image->length - tmargin - bmargin; } off->tmargin = tmargin; off->bmargin = bmargin; off->lmargin = lmargin; off->rmargin = rmargin; /* Calculate regions defined by margins, width, and length. * Coordinates expressed as 0 to imagewidth - 1, imagelength - 1, * since they are used to compute offsets into buffers */ switch (crop->edge_ref) { case EDGE_BOTTOM: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; endy = image->length - bmargin - 1; if ((endy - length) <= tmargin) starty = tmargin; else starty = endy - length + 1; break; case EDGE_RIGHT: endx = image->width - rmargin - 1; if ((endx - width) <= lmargin) startx = lmargin; else startx = endx - width + 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; case EDGE_TOP: /* width from left, length from top */ case EDGE_LEFT: default: startx = lmargin; if ((startx + width) >= (image->width - rmargin)) endx = image->width - rmargin - 1; else endx = startx + width - 1; starty = tmargin; if ((starty + length) >= (image->length - bmargin)) endy = image->length - bmargin - 1; else endy = starty + length - 1; break; } off->startx = startx; off->starty = starty; off->endx = endx; off->endy = endy; crop_width = endx - startx + 1; crop_length = endy - starty + 1; if (crop_width <= 0) { TIFFError("computeInputPixelOffsets", "Invalid left/right margins and /or image crop width requested"); return (-1); } if (crop_width > image->width) crop_width = image->width; if (crop_length <= 0) { TIFFError("computeInputPixelOffsets", "Invalid top/bottom margins and /or image crop length requested"); return (-1); } if (crop_length > image->length) crop_length = image->length; off->crop_width = crop_width; off->crop_length = crop_length; return (0); } /* end computeInputPixelOffsets */ /* * Translate crop options into pixel offsets for one or more regions of the image. * Options are applied in this order: margins, specific width and length, zones, * but all are optional. Margins are relative to each edge. Width, length and * zones are relative to the specified reference edge. Zones are expressed as * X:Y where X is the ordinal value in a set of Y equal sized portions. eg. * 2:3 would indicate the middle third of the region qualified by margins and * any explicit width and length specified. Regions are specified by coordinates * of the top left and lower right corners with range 1 to width or height. */ static int getCropOffsets(struct image_data *image, struct crop_mask *crop, struct dump_opts *dump) { struct offset offsets; int i; int32 test; uint32 seg, total, need_buff = 0; uint32 buffsize; uint32 zwidth, zlength; memset(&offsets, '\0', sizeof(struct offset)); crop->bufftotal = 0; crop->combined_width = (uint32)0; crop->combined_length = (uint32)0; crop->selections = 0; /* Compute pixel offsets if margins or fixed width or length specified */ if ((crop->crop_mode & CROP_MARGINS) || (crop->crop_mode & CROP_REGIONS) || (crop->crop_mode & CROP_LENGTH) || (crop->crop_mode & CROP_WIDTH)) { if (computeInputPixelOffsets(crop, image, &offsets)) { TIFFError ("getCropOffsets", "Unable to compute crop margins"); return (-1); } need_buff = TRUE; crop->selections = crop->regions; /* Regions are only calculated from top and left edges with no margins */ if (crop->crop_mode & CROP_REGIONS) return (0); } else { /* cropped area is the full image */ offsets.tmargin = 0; offsets.lmargin = 0; offsets.bmargin = 0; offsets.rmargin = 0; offsets.crop_width = image->width; offsets.crop_length = image->length; offsets.startx = 0; offsets.endx = image->width - 1; offsets.starty = 0; offsets.endy = image->length - 1; need_buff = FALSE; } if (dump->outfile != NULL) { dump_info (dump->outfile, dump->format, "", "Margins: Top: %d Left: %d Bottom: %d Right: %d", offsets.tmargin, offsets.lmargin, offsets.bmargin, offsets.rmargin); dump_info (dump->outfile, dump->format, "", "Crop region within margins: Adjusted Width: %6d Length: %6d", offsets.crop_width, offsets.crop_length); } if (!(crop->crop_mode & CROP_ZONES)) /* no crop zones requested */ { if (need_buff == FALSE) /* No margins or fixed width or length areas */ { crop->selections = 0; crop->combined_width = image->width; crop->combined_length = image->length; return (0); } else { /* Use one region for margins and fixed width or length areas * even though it was not formally declared as a region. */ crop->selections = 1; crop->zones = 1; crop->zonelist[0].total = 1; crop->zonelist[0].position = 1; } } else crop->selections = crop->zones; for (i = 0; i < crop->zones; i++) { seg = crop->zonelist[i].position; total = crop->zonelist[i].total; switch (crop->edge_ref) { case EDGE_LEFT: /* zones from left to right, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * 1.0 * (seg - 1) / total); test = (int32)offsets.startx + (int32)(offsets.crop_width * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_BOTTOM: /* width from left, zones from bottom to top */ zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; test = offsets.endy - (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y1 = 0; else crop->regionlist[i].y1 = test + 1; test = offsets.endy - (offsets.crop_length * 1.0 * (seg - 1) / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; case EDGE_RIGHT: /* zones from right to left, length from top */ zlength = offsets.crop_length; crop->regionlist[i].y1 = offsets.starty; crop->regionlist[i].y2 = offsets.endy; crop->regionlist[i].x1 = offsets.startx + (uint32)(offsets.crop_width * (total - seg) * 1.0 / total); test = offsets.startx + (offsets.crop_width * (total - seg + 1) * 1.0 / total); if (test < 1 ) crop->regionlist[i].x2 = 0; else { if (test > (int32)(image->width - 1)) crop->regionlist[i].x2 = image->width - 1; else crop->regionlist[i].x2 = test - 1; } zwidth = crop->regionlist[i].x2 - crop->regionlist[i].x1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ crop->combined_length = (uint32)zlength; if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_width += (uint32)zwidth; else crop->combined_width = (uint32)zwidth; break; case EDGE_TOP: /* width from left, zones from top to bottom */ default: zwidth = offsets.crop_width; crop->regionlist[i].x1 = offsets.startx; crop->regionlist[i].x2 = offsets.endx; crop->regionlist[i].y1 = offsets.starty + (uint32)(offsets.crop_length * 1.0 * (seg - 1) / total); test = offsets.starty + (uint32)(offsets.crop_length * 1.0 * seg / total); if (test < 1 ) crop->regionlist[i].y2 = 0; else { if (test > (int32)(image->length - 1)) crop->regionlist[i].y2 = image->length - 1; else crop->regionlist[i].y2 = test - 1; } zlength = crop->regionlist[i].y2 - crop->regionlist[i].y1 + 1; /* This is passed to extractCropZone or extractCompositeZones */ if (crop->exp_mode == COMPOSITE_IMAGES) crop->combined_length += (uint32)zlength; else crop->combined_length = (uint32)zlength; crop->combined_width = (uint32)zwidth; break; } /* end switch statement */ buffsize = (uint32) ((((zwidth * image->bps * image->spp) + 7 ) / 8) * (zlength + 1)); crop->regionlist[i].width = (uint32) zwidth; crop->regionlist[i].length = (uint32) zlength; crop->regionlist[i].buffsize = buffsize; crop->bufftotal += buffsize; if (dump->outfile != NULL) dump_info (dump->outfile, dump->format, "", "Zone %d, width: %4d, length: %4d, x1: %4d x2: %4d y1: %4d y2: %4d", i + 1, (uint32)zwidth, (uint32)zlength, crop->regionlist[i].x1, crop->regionlist[i].x2, crop->regionlist[i].y1, crop->regionlist[i].y2); } return (0); } /* end getCropOffsets */ static int computeOutputPixelOffsets (struct crop_mask *crop, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts* dump) { double scale; double pwidth, plength; /* Output page width and length in user units*/ uint32 iwidth, ilength; /* Input image width and length in pixels*/ uint32 owidth, olength; /* Output image width and length in pixels*/ uint32 orows, ocols; /* rows and cols for output */ uint32 hmargin, vmargin; /* Horizontal and vertical margins */ uint32 x1, x2, y1, y2, line_bytes; /* unsigned int orientation; */ uint32 i, j, k; scale = 1.0; if (page->res_unit == RESUNIT_NONE) page->res_unit = image->res_unit; switch (image->res_unit) { case RESUNIT_CENTIMETER: if (page->res_unit == RESUNIT_INCH) scale = 1.0/2.54; break; case RESUNIT_INCH: if (page->res_unit == RESUNIT_CENTIMETER) scale = 2.54; break; case RESUNIT_NONE: /* Dimensions in pixels */ default: break; } /* get width, height, resolutions of input image selection */ if (crop->combined_width > 0) iwidth = crop->combined_width; else iwidth = image->width; if (crop->combined_length > 0) ilength = crop->combined_length; else ilength = image->length; if (page->hres <= 1.0) page->hres = image->xres; if (page->vres <= 1.0) page->vres = image->yres; if ((page->hres < 1.0) || (page->vres < 1.0)) { TIFFError("computeOutputPixelOffsets", "Invalid horizontal or vertical resolution specified or read from input image"); return (1); } /* If no page sizes are being specified, we just use the input image size to * calculate maximum margins that can be taken from image. */ if (page->width <= 0) pwidth = iwidth; else pwidth = page->width; if (page->length <= 0) plength = ilength; else plength = page->length; if (dump->debug) { TIFFError("", "Page size: %s, Vres: %3.2f, Hres: %3.2f, " "Hmargin: %3.2f, Vmargin: %3.2f", page->name, page->vres, page->hres, page->hmargin, page->vmargin); TIFFError("", "Res_unit: %d, Scale: %3.2f, Page width: %3.2f, length: %3.2f", page->res_unit, scale, pwidth, plength); } /* compute margins at specified unit and resolution */ if (page->mode & PAGE_MODE_MARGINS) { if (page->res_unit == RESUNIT_INCH || page->res_unit == RESUNIT_CENTIMETER) { /* inches or centimeters specified */ hmargin = (uint32)(page->hmargin * scale * page->hres * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * page->vres * ((image->bps + 7)/ 8)); } else { /* Otherwise user has specified pixels as reference unit */ hmargin = (uint32)(page->hmargin * scale * ((image->bps + 7)/ 8)); vmargin = (uint32)(page->vmargin * scale * ((image->bps + 7)/ 8)); } if ((hmargin * 2.0) > (pwidth * page->hres)) { TIFFError("computeOutputPixelOffsets", "Combined left and right margins exceed page width"); hmargin = (uint32) 0; return (-1); } if ((vmargin * 2.0) > (plength * page->vres)) { TIFFError("computeOutputPixelOffsets", "Combined top and bottom margins exceed page length"); vmargin = (uint32) 0; return (-1); } } else { hmargin = 0; vmargin = 0; } if (page->mode & PAGE_MODE_ROWSCOLS ) { /* Maybe someday but not for now */ if (page->mode & PAGE_MODE_MARGINS) TIFFError("computeOutputPixelOffsets", "Output margins cannot be specified with rows and columns"); owidth = TIFFhowmany(iwidth, page->cols); olength = TIFFhowmany(ilength, page->rows); } else { if (page->mode & PAGE_MODE_PAPERSIZE ) { owidth = (uint32)((pwidth * page->hres) - (hmargin * 2)); olength = (uint32)((plength * page->vres) - (vmargin * 2)); } else { owidth = (uint32)(iwidth - (hmargin * 2 * page->hres)); olength = (uint32)(ilength - (vmargin * 2 * page->vres)); } } if (owidth > iwidth) owidth = iwidth; if (olength > ilength) olength = ilength; /* Compute the number of pages required for Portrait or Landscape */ switch (page->orient) { case ORIENTATION_NONE: case ORIENTATION_PORTRAIT: ocols = TIFFhowmany(iwidth, owidth); orows = TIFFhowmany(ilength, olength); /* orientation = ORIENTATION_PORTRAIT; */ break; case ORIENTATION_LANDSCAPE: ocols = TIFFhowmany(iwidth, olength); orows = TIFFhowmany(ilength, owidth); x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ break; case ORIENTATION_AUTO: default: x1 = TIFFhowmany(iwidth, owidth); x2 = TIFFhowmany(ilength, olength); y1 = TIFFhowmany(iwidth, olength); y2 = TIFFhowmany(ilength, owidth); if ( (x1 * x2) < (y1 * y2)) { /* Portrait */ ocols = x1; orows = x2; /* orientation = ORIENTATION_PORTRAIT; */ } else { /* Landscape */ ocols = y1; orows = y2; x1 = olength; olength = owidth; owidth = x1; /* orientation = ORIENTATION_LANDSCAPE; */ } } if (ocols < 1) ocols = 1; if (orows < 1) orows = 1; /* If user did not specify rows and cols, set them from calcuation */ if (page->rows < 1) page->rows = orows; if (page->cols < 1) page->cols = ocols; line_bytes = TIFFhowmany8(owidth * image->bps) * image->spp; if ((page->rows * page->cols) > MAX_SECTIONS) { TIFFError("computeOutputPixelOffsets", "Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections"); return (-1); } /* build the list of offsets for each output section */ for (k = 0, i = 0 && k <= MAX_SECTIONS; i < orows; i++) { y1 = (uint32)(olength * i); y2 = (uint32)(olength * (i + 1) - 1); if (y2 >= ilength) y2 = ilength - 1; for (j = 0; j < ocols; j++, k++) { x1 = (uint32)(owidth * j); x2 = (uint32)(owidth * (j + 1) - 1); if (x2 >= iwidth) x2 = iwidth - 1; sections[k].x1 = x1; sections[k].x2 = x2; sections[k].y1 = y1; sections[k].y2 = y2; sections[k].buffsize = line_bytes * olength; sections[k].position = k + 1; sections[k].total = orows * ocols; } } return (0); } /* end computeOutputPixelOffsets */ static int loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr) { uint32 i; float xres = 0.0, yres = 0.0; uint32 nstrips = 0, ntiles = 0; uint16 planar = 0; uint16 bps = 0, spp = 0, res_unit = 0; uint16 orientation = 0; uint16 input_compression = 0, input_photometric = 0; uint16 subsampling_horiz, subsampling_vert; uint32 width = 0, length = 0; uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0; uint32 tw = 0, tl = 0; /* Tile width and length */ uint32 tile_rowsize = 0; unsigned char *read_buff = NULL; unsigned char *new_buff = NULL; int readunit = 0; static uint32 prev_readsize = 0; TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps); TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp); TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar); TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation); if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric)) TIFFError("loadImage","Image lacks Photometric interpreation tag"); if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width)) TIFFError("loadimage","Image lacks image width tag"); if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length)) TIFFError("loadimage","Image lacks image length tag"); TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres); TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres); if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit)) res_unit = RESUNIT_INCH; if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression)) input_compression = COMPRESSION_NONE; #ifdef DEBUG2 char compressionid[16]; switch (input_compression) { case COMPRESSION_NONE: /* 1 dump mode */ strcpy (compressionid, "None/dump"); break; case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */ strcpy (compressionid, "Huffman RLE"); break; case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */ strcpy (compressionid, "Group3 Fax"); break; case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */ strcpy (compressionid, "Group4 Fax"); break; case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */ strcpy (compressionid, "LZW"); break; case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */ strcpy (compressionid, "Old Jpeg"); break; case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */ strcpy (compressionid, "New Jpeg"); break; case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */ strcpy (compressionid, "Next RLE"); break; case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */ strcpy (compressionid, "CITTRLEW"); break; case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */ strcpy (compressionid, "Mac Packbits"); break; case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */ strcpy (compressionid, "Thunderscan"); break; case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */ strcpy (compressionid, "IT8 padded"); break; case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */ strcpy (compressionid, "IT8 RLE"); break; case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */ strcpy (compressionid, "IT8 mono"); break; case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */ strcpy (compressionid, "IT8 lineart"); break; case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */ strcpy (compressionid, "Pixar 10 bit"); break; case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */ strcpy (compressionid, "Pixar 11bit"); break; case COMPRESSION_DEFLATE: /* 32946 Deflate compression */ strcpy (compressionid, "Deflate"); break; case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */ strcpy (compressionid, "Adobe deflate"); break; default: strcpy (compressionid, "None/unknown"); break; } TIFFError("loadImage", "Input compression %s", compressionid); #endif scanlinesize = TIFFScanlineSize(in); image->bps = bps; image->spp = spp; image->planar = planar; image->width = width; image->length = length; image->xres = xres; image->yres = yres; image->res_unit = res_unit; image->compression = input_compression; image->photometric = input_photometric; #ifdef DEBUG2 char photometricid[12]; switch (input_photometric) { case PHOTOMETRIC_MINISWHITE: strcpy (photometricid, "MinIsWhite"); break; case PHOTOMETRIC_MINISBLACK: strcpy (photometricid, "MinIsBlack"); break; case PHOTOMETRIC_RGB: strcpy (photometricid, "RGB"); break; case PHOTOMETRIC_PALETTE: strcpy (photometricid, "Palette"); break; case PHOTOMETRIC_MASK: strcpy (photometricid, "Mask"); break; case PHOTOMETRIC_SEPARATED: strcpy (photometricid, "Separated"); break; case PHOTOMETRIC_YCBCR: strcpy (photometricid, "YCBCR"); break; case PHOTOMETRIC_CIELAB: strcpy (photometricid, "CIELab"); break; case PHOTOMETRIC_ICCLAB: strcpy (photometricid, "ICCLab"); break; case PHOTOMETRIC_ITULAB: strcpy (photometricid, "ITULab"); break; case PHOTOMETRIC_LOGL: strcpy (photometricid, "LogL"); break; case PHOTOMETRIC_LOGLUV: strcpy (photometricid, "LOGLuv"); break; default: strcpy (photometricid, "Unknown"); break; } TIFFError("loadImage", "Input photometric interpretation %s", photometricid); #endif image->orientation = orientation; switch (orientation) { case 0: case ORIENTATION_TOPLEFT: image->adjustments = 0; break; case ORIENTATION_TOPRIGHT: image->adjustments = MIRROR_HORIZ; break; case ORIENTATION_BOTRIGHT: image->adjustments = ROTATECW_180; break; case ORIENTATION_BOTLEFT: image->adjustments = MIRROR_VERT; break; case ORIENTATION_LEFTTOP: image->adjustments = MIRROR_VERT | ROTATECW_90; break; case ORIENTATION_RIGHTTOP: image->adjustments = ROTATECW_90; break; case ORIENTATION_RIGHTBOT: image->adjustments = MIRROR_VERT | ROTATECW_270; break; case ORIENTATION_LEFTBOT: image->adjustments = ROTATECW_270; break; default: image->adjustments = 0; image->orientation = ORIENTATION_TOPLEFT; } if ((bps == 0) || (spp == 0)) { TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)", spp, bps); return (-1); } if (TIFFIsTiled(in)) { readunit = TILE; tlsize = TIFFTileSize(in); ntiles = TIFFNumberOfTiles(in); TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(in, TIFFTAG_TILELENGTH, &tl); tile_rowsize = TIFFTileRowSize(in); if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0) { TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero."); exit(-1); } buffsize = tlsize * ntiles; if (tlsize != (buffsize / ntiles)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } if (buffsize < (uint32)(ntiles * tl * tile_rowsize)) { buffsize = ntiles * tl * tile_rowsize; if (ntiles != (buffsize / tl / tile_rowsize)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } #ifdef DEBUG2 TIFFError("loadImage", "Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu", tlsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Tilesize: %u, Number of Tiles: %u, Tile row size: %u", tlsize, ntiles, tile_rowsize); } else { uint32 buffsize_check; readunit = STRIP; TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); stsize = TIFFStripSize(in); nstrips = TIFFNumberOfStrips(in); if (nstrips == 0 || stsize == 0) { TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero."); exit(-1); } buffsize = stsize * nstrips; if (stsize != (buffsize / nstrips)) { TIFFError("loadImage", "Integer overflow when calculating buffer size"); exit(-1); } buffsize_check = ((length * width * spp * bps) + 7); if (length != ((buffsize_check - 7) / width / spp / bps)) { TIFFError("loadImage", "Integer overflow detected."); exit(-1); } if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8)) { buffsize = ((length * width * spp * bps) + 7) / 8; #ifdef DEBUG2 TIFFError("loadImage", "Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu", stsize, (unsigned long)buffsize); #endif } if (dump->infile != NULL) dump_info (dump->infile, dump->format, "", "Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u", stsize, nstrips, rowsperstrip, scanlinesize); } if (input_compression == COMPRESSION_JPEG) { /* Force conversion to RGB */ jpegcolormode = JPEGCOLORMODE_RGB; TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } /* The clause up to the read statement is taken from Tom Lane's tiffcp patch */ else { /* Otherwise, can't handle subsampled input */ if (input_photometric == PHOTOMETRIC_YCBCR) { TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING, &subsampling_horiz, &subsampling_vert); if (subsampling_horiz != 1 || subsampling_vert != 1) { TIFFError("loadImage", "Can't copy/convert subsampled image with subsampling %d horiz %d vert", subsampling_horiz, subsampling_vert); return (-1); } } } read_buff = *read_ptr; /* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */ /* outside buffer */ if (!read_buff) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else { if (prev_readsize < buffsize) { if( buffsize > 0xFFFFFFFFU - 3 ) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } new_buff = _TIFFrealloc(read_buff, buffsize+3); if (!new_buff) { free (read_buff); read_buff = (unsigned char *)_TIFFmalloc(buffsize+3); } else read_buff = new_buff; } } if (!read_buff) { TIFFError("loadImage", "Unable to allocate/reallocate read buffer"); return (-1); } read_buff[buffsize] = 0; read_buff[buffsize+1] = 0; read_buff[buffsize+2] = 0; prev_readsize = buffsize; *read_ptr = read_buff; /* N.B. The read functions used copy separate plane data into a buffer as interleaved * samples rather than separate planes so the same logic works to extract regions * regardless of the way the data are organized in the input file. */ switch (readunit) { case STRIP: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigStripsIntoBuffer(in, read_buff))) { TIFFError("loadImage", "Unable to read contiguous strips into buffer"); return (-1); } } else { if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump))) { TIFFError("loadImage", "Unable to read separate strips into buffer"); return (-1); } } break; case TILE: if (planar == PLANARCONFIG_CONTIG) { if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read contiguous tiles into buffer"); return (-1); } } else { if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps))) { TIFFError("loadImage", "Unable to read separate tiles into buffer"); return (-1); } } break; default: TIFFError("loadImage", "Unsupported image file format"); return (-1); break; } if ((dump->infile != NULL) && (dump->level == 2)) { dump_info (dump->infile, dump->format, "loadImage", "Image width %d, length %d, Raw image data, %4d bytes", width, length, buffsize); dump_info (dump->infile, dump->format, "", "Bits per sample %d, Samples per pixel %d", bps, spp); for (i = 0; i < length; i++) dump_buffer(dump->infile, dump->format, 1, scanlinesize, i, read_buff + (i * scanlinesize)); } return (0); } /* end loadImage */ static int correct_orientation(struct image_data *image, unsigned char **work_buff_ptr) { uint16 mirror, rotation; unsigned char *work_buff; work_buff = *work_buff_ptr; if ((image == NULL) || (work_buff == NULL)) { TIFFError ("correct_orientatin", "Invalid image or buffer pointer"); return (-1); } if ((image->adjustments & MIRROR_HORIZ) || (image->adjustments & MIRROR_VERT)) { mirror = (uint16)(image->adjustments & MIRROR_BOTH); if (mirrorImage(image->spp, image->bps, mirror, image->width, image->length, work_buff)) { TIFFError ("correct_orientation", "Unable to mirror image"); return (-1); } } if (image->adjustments & ROTATE_ANY) { if (image->adjustments & ROTATECW_90) rotation = (uint16) 90; else if (image->adjustments & ROTATECW_180) rotation = (uint16) 180; else if (image->adjustments & ROTATECW_270) rotation = (uint16) 270; else { TIFFError ("correct_orientation", "Invalid rotation value: %d", image->adjustments & ROTATE_ANY); return (-1); } if (rotateImage(rotation, image, &image->width, &image->length, work_buff_ptr)) { TIFFError ("correct_orientation", "Unable to rotate image"); return (-1); } image->orientation = ORIENTATION_TOPLEFT; } return (0); } /* end correct_orientation */ /* Extract multiple zones from an image and combine into a single composite image */ static int extractCompositeRegions(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff) { int shift_width, bytes_per_sample, bytes_per_pixel; uint32 i, trailing_bits, prev_trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_rowsize, dst_rowsize, src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint32 prev_length, prev_width, composite_width; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract one or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } src = read_buff; dst = crop_buff; /* These are setup for adding additional sections */ prev_width = prev_length = 0; prev_trailing_bits = trailing_bits = 0; composite_width = crop->combined_width; crop->combined_width = 0; crop->combined_length = 0; for (i = 0; i < crop->selections; i++) { /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[i].y1; last_row = crop->regionlist[i].y2; first_col = crop->regionlist[i].x1; last_col = crop->regionlist[i].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; /* These should not be needed for composite images */ crop->regionlist[i].width = crop_width; crop->regionlist[i].length = crop_length; crop->regionlist[i].buffptr = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * count) + 7) / 8); switch (crop->edge_ref) { default: case EDGE_TOP: case EDGE_BOTTOM: if ((i > 0) && (crop_width != crop->regionlist[i - 1].width)) { TIFFError ("extractCompositeRegions", "Only equal width regions can be combined for -E top or bottom"); return (1); } crop->combined_width = crop_width; crop->combined_length += crop_length; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + (prev_length * dst_rowsize); switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_length += crop_length; break; case EDGE_LEFT: /* splice the pieces of each row together, side by side */ case EDGE_RIGHT: if ((i > 0) && (crop_length != crop->regionlist[i - 1].length)) { TIFFError ("extractCompositeRegions", "Only equal length regions can be combined for -E left or right"); return (1); } crop->combined_width += crop_width; crop->combined_length = crop_length; dst_rowsize = (((composite_width * bps * count) + 7) / 8); trailing_bits = (crop_width * bps * count) % 8; for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset + prev_width; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractCompositeRegions", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractCompositeRegions", "Unsupported bit depth %d", bps); return (1); } } prev_width += (crop_width * bps * count) / 8; prev_trailing_bits += trailing_bits; if (prev_trailing_bits > 7) prev_trailing_bits-= 8; break; } } if (crop->combined_width != composite_width) TIFFError("combineSeparateRegions","Combined width does not match composite width"); return (0); } /* end extractCompositeRegions */ /* Copy a single region of input buffer to an output buffer. * The read functions used copy separate plane data into a buffer * as interleaved samples rather than separate planes so the same * logic works to extract regions regardless of the way the data * are organized in the input file. This function can be used to * extract one or more samples from the input image by updating the * parameters for starting sample and number of samples to copy in the * fifth and eighth arguments of the call to extractContigSamples. * They would be passed as new elements of the crop_mask struct. */ static int extractSeparateRegion(struct image_data *image, struct crop_mask *crop, unsigned char *read_buff, unsigned char *crop_buff, int region) { int shift_width, prev_trailing_bits = 0; uint32 bytes_per_sample, bytes_per_pixel; uint32 src_rowsize, dst_rowsize; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset; uint32 crop_width, crop_length, img_width /*, img_length */; uint16 bps, spp; uint8 *src, *dst; tsample_t count, sample = 0; /* Update to extract more or more samples */ img_width = image->width; /* img_length = image->length; */ bps = image->bps; spp = image->spp; count = spp; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if ((bps % 8) == 0) shift_width = 0; /* Byte aligned data only */ else { if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; } /* rows, columns, width, length are expressed in pixels */ first_row = crop->regionlist[region].y1; last_row = crop->regionlist[region].y2; first_col = crop->regionlist[region].x1; last_col = crop->regionlist[region].x2; crop_width = last_col - first_col + 1; crop_length = last_row - first_row + 1; crop->regionlist[region].width = crop_width; crop->regionlist[region].length = crop_length; crop->regionlist[region].buffptr = crop_buff; src = read_buff; dst = crop_buff; src_rowsize = ((img_width * bps * spp) + 7) / 8; dst_rowsize = (((crop_width * bps * spp) + 7) / 8); for (row = first_row; row <= last_row; row++) { src_offset = row * src_rowsize; dst_offset = (row - first_row) * dst_rowsize; src = read_buff + src_offset; dst = crop_buff + dst_offset; switch (shift_width) { case 0: if (extractContigSamplesBytes (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 1: if (bps == 1) { if (extractContigSamplesShifted8bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; } else if (extractContigSamplesShifted16bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 2: if (extractContigSamplesShifted24bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; case 3: case 4: case 5: if (extractContigSamplesShifted32bits (src, dst, img_width, sample, spp, bps, count, first_col, last_col + 1, prev_trailing_bits)) { TIFFError("extractSeparateRegion", "Unable to extract row %d", row); return (1); } break; default: TIFFError("extractSeparateRegion", "Unsupported bit depth %d", bps); return (1); } } return (0); } /* end extractSeparateRegion */ static int extractImageSection(struct image_data *image, struct pageseg *section, unsigned char *src_buff, unsigned char *sect_buff) { unsigned char bytebuff1, bytebuff2; #ifdef DEVELMODE /* unsigned char *src, *dst; */ #endif uint32 img_width, img_rowsize; #ifdef DEVELMODE uint32 img_length; #endif uint32 j, shift1, shift2, trailing_bits; uint32 row, first_row, last_row, first_col, last_col; uint32 src_offset, dst_offset, row_offset, col_offset; uint32 offset1, offset2, full_bytes; uint32 sect_width; #ifdef DEVELMODE uint32 sect_length; #endif uint16 bps, spp; #ifdef DEVELMODE int k; unsigned char bitset; static char *bitarray = NULL; #endif img_width = image->width; #ifdef DEVELMODE img_length = image->length; #endif bps = image->bps; spp = image->spp; #ifdef DEVELMODE /* src = src_buff; */ /* dst = sect_buff; */ #endif src_offset = 0; dst_offset = 0; #ifdef DEVELMODE if (bitarray == NULL) { if ((bitarray = (char *)malloc(img_width)) == NULL) { TIFFError ("", "DEBUG: Unable to allocate debugging bitarray"); return (-1); } } #endif /* rows, columns, width, length are expressed in pixels */ first_row = section->y1; last_row = section->y2; first_col = section->x1; last_col = section->x2; sect_width = last_col - first_col + 1; #ifdef DEVELMODE sect_length = last_row - first_row + 1; #endif img_rowsize = ((img_width * bps + 7) / 8) * spp; full_bytes = (sect_width * spp * bps) / 8; /* number of COMPLETE bytes per row in section */ trailing_bits = (sect_width * bps) % 8; #ifdef DEVELMODE TIFFError ("", "First row: %d, last row: %d, First col: %d, last col: %d\n", first_row, last_row, first_col, last_col); TIFFError ("", "Image width: %d, Image length: %d, bps: %d, spp: %d\n", img_width, img_length, bps, spp); TIFFError ("", "Sect width: %d, Sect length: %d, full bytes: %d trailing bits %d\n", sect_width, sect_length, full_bytes, trailing_bits); #endif if ((bps % 8) == 0) { col_offset = first_col * spp * bps / 8; for (row = first_row; row <= last_row; row++) { /* row_offset = row * img_width * spp * bps / 8; */ row_offset = row * img_rowsize; src_offset = row_offset + col_offset; #ifdef DEVELMODE TIFFError ("", "Src offset: %8d, Dst offset: %8d", src_offset, dst_offset); #endif _TIFFmemcpy (sect_buff + dst_offset, src_buff + src_offset, full_bytes); dst_offset += full_bytes; } } else { /* bps != 8 */ shift1 = spp * ((first_col * bps) % 8); shift2 = spp * ((last_col * bps) % 8); for (row = first_row; row <= last_row; row++) { /* pull out the first byte */ row_offset = row * img_rowsize; offset1 = row_offset + (first_col * bps / 8); offset2 = row_offset + (last_col * bps / 8); #ifdef DEVELMODE for (j = 0, k = 7; j < 8; j++, k--) { bitset = *(src_buff + offset1) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } sprintf(&bitarray[8], " "); sprintf(&bitarray[9], " "); for (j = 10, k = 7; j < 18; j++, k--) { bitset = *(src_buff + offset2) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[18] = '\0'; TIFFError ("", "Row: %3d Offset1: %d, Shift1: %d, Offset2: %d, Shift2: %d\n", row, offset1, shift1, offset2, shift2); #endif bytebuff1 = bytebuff2 = 0; if (shift1 == 0) /* the region is byte and sample alligned */ { _TIFFmemcpy (sect_buff + dst_offset, src_buff + offset1, full_bytes); #ifdef DEVELMODE TIFFError ("", " Alligned data src offset1: %8d, Dst offset: %8d\n", offset1, dst_offset); sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { bytebuff2 = src_buff[offset2] & ((unsigned char)255 << (7 - shift2)); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset2, dst_offset); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } else /* each destination byte will have to be built from two source bytes*/ { #ifdef DEVELMODE TIFFError ("", " Unalligned data src offset: %8d, Dst offset: %8d\n", offset1 , dst_offset); #endif for (j = 0; j <= full_bytes; j++) { bytebuff1 = src_buff[offset1 + j] & ((unsigned char)255 >> shift1); bytebuff2 = src_buff[offset1 + j + 1] & ((unsigned char)255 << (7 - shift1)); sect_buff[dst_offset + j] = (bytebuff1 << shift1) | (bytebuff2 >> (8 - shift1)); } #ifdef DEVELMODE sprintf(&bitarray[18], "\n"); sprintf(&bitarray[19], "\t"); for (j = 20, k = 7; j < 28; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[28] = ' '; bitarray[29] = ' '; #endif dst_offset += full_bytes; if (trailing_bits != 0) { #ifdef DEVELMODE TIFFError ("", " Trailing bits src offset: %8d, Dst offset: %8d\n", offset1 + full_bytes, dst_offset); #endif if (shift2 > shift1) { bytebuff1 = src_buff[offset1 + full_bytes] & ((unsigned char)255 << (7 - shift2)); bytebuff2 = bytebuff1 & ((unsigned char)255 << shift1); sect_buff[dst_offset] = bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 > Shift1\n"); #endif } else { if (shift2 < shift1) { bytebuff2 = ((unsigned char)255 << (shift1 - shift2 - 1)); sect_buff[dst_offset] &= bytebuff2; #ifdef DEVELMODE TIFFError ("", " Shift2 < Shift1\n"); #endif } #ifdef DEVELMODE else TIFFError ("", " Shift2 == Shift1\n"); #endif } } #ifdef DEVELMODE sprintf(&bitarray[28], " "); sprintf(&bitarray[29], " "); for (j = 30, k = 7; j < 38; j++, k--) { bitset = *(sect_buff + dst_offset) & (((unsigned char)1 << k)) ? 1 : 0; sprintf(&bitarray[j], (bitset) ? "1" : "0"); } bitarray[38] = '\0'; TIFFError ("", "\tFirst and last bytes before and after masking:\n\t%s\n\n", bitarray); #endif dst_offset++; } } } return (0); } /* end extractImageSection */ static int writeSelections(TIFF *in, TIFF **out, struct crop_mask *crop, struct image_data *image, struct dump_opts *dump, struct buffinfo seg_buffs[], char *mp, char *filename, unsigned int *page, unsigned int total_pages) { int i, page_count; int autoindex = 0; unsigned char *crop_buff = NULL; /* Where we open a new file depends on the export mode */ switch (crop->exp_mode) { case ONE_FILE_COMPOSITE: /* Regions combined into single image */ autoindex = 0; crop_buff = seg_buffs[0].buffer; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = total_pages; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case ONE_FILE_SEPARATED: /* Regions as separated images */ autoindex = 0; if (update_output_file (out, mp, autoindex, filename, page)) return (1); page_count = crop->selections * total_pages; for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_IMAGE_COMPOSITE: /* Regions as composite image */ autoindex = 1; if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[0].buffer; if (writeCroppedImage(in, *out, image, dump, crop->combined_width, crop->combined_length, crop_buff, *page, total_pages)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } break; case FILE_PER_IMAGE_SEPARATED: /* Regions as separated images */ autoindex = 1; page_count = crop->selections; if (update_output_file (out, mp, autoindex, filename, page)) return (1); for (i = 0; i < crop->selections; i++) { crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; case FILE_PER_SELECTION: autoindex = 1; page_count = 1; for (i = 0; i < crop->selections; i++) { if (update_output_file (out, mp, autoindex, filename, page)) return (1); crop_buff = seg_buffs[i].buffer; /* Write the current region to the current file */ if (writeCroppedImage(in, *out, image, dump, crop->regionlist[i].width, crop->regionlist[i].length, crop_buff, *page, page_count)) { TIFFError("writeRegions", "Unable to write new image"); return (-1); } } break; default: return (1); } return (0); } /* end writeRegions */ static int writeImageSections(TIFF *in, TIFF *out, struct image_data *image, struct pagedef *page, struct pageseg *sections, struct dump_opts * dump, unsigned char *src_buff, unsigned char **sect_buff_ptr) { double hres, vres; uint32 i, k, width, length, sectsize; unsigned char *sect_buff = *sect_buff_ptr; hres = page->hres; vres = page->vres; k = page->cols * page->rows; if ((k < 1) || (k > MAX_SECTIONS)) { TIFFError("writeImageSections", "%d Rows and Columns exceed maximum sections\nIncrease resolution or reduce sections", k); return (-1); } for (i = 0; i < k; i++) { width = sections[i].x2 - sections[i].x1 + 1; length = sections[i].y2 - sections[i].y1 + 1; sectsize = (uint32) ceil((width * image->bps + 7) / (double)8) * image->spp * length; /* allocate a buffer if we don't have one already */ if (createImageSection(sectsize, sect_buff_ptr)) { TIFFError("writeImageSections", "Unable to allocate section buffer"); exit (-1); } sect_buff = *sect_buff_ptr; if (extractImageSection (image, &sections[i], src_buff, sect_buff)) { TIFFError("writeImageSections", "Unable to extract image sections"); exit (-1); } /* call the write routine here instead of outside the loop */ if (writeSingleSection(in, out, image, dump, width, length, hres, vres, sect_buff)) { TIFFError("writeImageSections", "Unable to write image section"); exit (-1); } } return (0); } /* end writeImageSections */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. */ static int writeSingleSection(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, double hres, double vres, unsigned char *sect_buff) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; /* Calling this seems to reset the compression mode on the TIFF *in file. TIFFGetField(in, TIFFTAG_JPEGCOLORMODE, &input_jpeg_colormode); */ input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeSingleSection", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif /* This is the global variable compression which is set * if the user has specified a command line option for * a compression option. Should be passed around in one * of the parameters instead of as a global. If no user * option specified it will still be (uint16) -1. */ if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { /* OJPEG is no longer supported for writing so upgrade to JPEG */ if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else /* Use the compression from the input file */ CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* holdout mask */ { TIFFError ("writeSingleSection", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } #ifdef DEBUG2 TIFFError("writeSingleSection", "Input photometric: %s", (input_photometric == PHOTOMETRIC_RGB) ? "RGB" : ((input_photometric == PHOTOMETRIC_YCBCR) ? "YCbCr" : "Not RGB or YCbCr")); #endif if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeSingleSection", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { /* These are references to GLOBAL variables set by defaults * and /or the compression flag */ case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeSingleSection", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { if (pageNum < 0) /* only one input file */ TIFFSetField(out, TIFFTAG_PAGENUMBER, pg0, pg1); else TIFFSetField(out, TIFFTAG_PAGENUMBER, pageNum++, 0); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Update these since they are overwritten from input res by loop above */ TIFFSetField(out, TIFFTAG_XRESOLUTION, (float)hres); TIFFSetField(out, TIFFTAG_YRESOLUTION, (float)vres); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) writeBufferToContigTiles (out, sect_buff, length, width, spp, dump); else writeBufferToSeparateTiles (out, sect_buff, length, width, spp, dump); } else { if (config == PLANARCONFIG_CONTIG) writeBufferToContigStrips (out, sect_buff, length); else writeBufferToSeparateStrips(out, sect_buff, length, width, spp, dump); } if (!TIFFWriteDirectory(out)) { TIFFClose(out); return (-1); } return (0); } /* end writeSingleSection */ /* Create a buffer to write one section at a time */ static int createImageSection(uint32 sectsize, unsigned char **sect_buff_ptr) { unsigned char *sect_buff = NULL; unsigned char *new_buff = NULL; static uint32 prev_sectsize = 0; sect_buff = *sect_buff_ptr; if (!sect_buff) { sect_buff = (unsigned char *)_TIFFmalloc(sectsize); *sect_buff_ptr = sect_buff; _TIFFmemset(sect_buff, 0, sectsize); } else { if (prev_sectsize < sectsize) { new_buff = _TIFFrealloc(sect_buff, sectsize); if (!new_buff) { free (sect_buff); sect_buff = (unsigned char *)_TIFFmalloc(sectsize); } else sect_buff = new_buff; _TIFFmemset(sect_buff, 0, sectsize); } } if (!sect_buff) { TIFFError("createImageSection", "Unable to allocate/reallocate section buffer"); return (-1); } prev_sectsize = sectsize; *sect_buff_ptr = sect_buff; return (0); } /* end createImageSection */ /* Process selections defined by regions, zones, margins, or fixed sized areas */ static int processCropSelections(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, struct buffinfo seg_buffs[]) { int i; uint32 width, length, total_width, total_length; tsize_t cropsize; unsigned char *crop_buff = NULL; unsigned char *read_buff = NULL; unsigned char *next_buff = NULL; tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; if (crop->img_mode == COMPOSITE_IMAGES) { cropsize = crop->bufftotal; crop_buff = seg_buffs[0].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = cropsize; /* Checks for matching width or length as required */ if (extractCompositeRegions(image, crop, read_buff, crop_buff) != 0) return (1); if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for composite regions"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } /* Mirror and Rotate will not work with multiple regions unless they are the same width */ if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror composite regions %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate composite regions by %d degrees", crop->rotation); return (-1); } seg_buffs[0].buffer = crop_buff; seg_buffs[0].size = (((crop->combined_width * image->bps + 7 ) / 8) * image->spp) * crop->combined_length; } } else /* Separated Images */ { total_width = total_length = 0; for (i = 0; i < crop->selections; i++) { cropsize = crop->bufftotal; crop_buff = seg_buffs[i].buffer; if (!crop_buff) crop_buff = (unsigned char *)_TIFFmalloc(cropsize); else { prev_cropsize = seg_buffs[0].size; if (prev_cropsize < cropsize) { next_buff = _TIFFrealloc(crop_buff, cropsize); if (! next_buff) { _TIFFfree (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = next_buff; } } if (!crop_buff) { TIFFError("processCropSelections", "Unable to allocate/reallocate crop buffer"); return (-1); } _TIFFmemset(crop_buff, 0, cropsize); seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = cropsize; if (extractSeparateRegion(image, crop, read_buff, crop_buff, i)) { TIFFError("processCropSelections", "Unable to extract cropped region %d from image", i); return (-1); } width = crop->regionlist[i].width; length = crop->regionlist[i].length; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to invert colorspace for region"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, width, length, crop_buff)) { TIFFError("processCropSelections", "Failed to mirror crop region %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->regionlist[i].width, &crop->regionlist[i].length, &crop_buff)) { TIFFError("processCropSelections", "Failed to rotate crop region by %d degrees", crop->rotation); return (-1); } total_width += crop->regionlist[i].width; total_length += crop->regionlist[i].length; crop->combined_width = total_width; crop->combined_length = total_length; seg_buffs[i].buffer = crop_buff; seg_buffs[i].size = (((crop->regionlist[i].width * image->bps + 7 ) / 8) * image->spp) * crop->regionlist[i].length; } } } return (0); } /* end processCropSelections */ /* Copy the crop section of the data from the current image into a buffer * and adjust the IFD values to reflect the new size. If no cropping is * required, use the origial read buffer as the crop buffer. * * There is quite a bit of redundancy between this routine and the more * specialized processCropSelections, but this provides * the most optimized path when no Zones or Regions are required. */ static int createCroppedImage(struct image_data *image, struct crop_mask *crop, unsigned char **read_buff_ptr, unsigned char **crop_buff_ptr) { tsize_t cropsize; unsigned char *read_buff = NULL; unsigned char *crop_buff = NULL; unsigned char *new_buff = NULL; static tsize_t prev_cropsize = 0; read_buff = *read_buff_ptr; /* process full image, no crop buffer needed */ crop_buff = read_buff; *crop_buff_ptr = read_buff; crop->combined_width = image->width; crop->combined_length = image->length; cropsize = crop->bufftotal; crop_buff = *crop_buff_ptr; if (!crop_buff) { crop_buff = (unsigned char *)_TIFFmalloc(cropsize); *crop_buff_ptr = crop_buff; _TIFFmemset(crop_buff, 0, cropsize); prev_cropsize = cropsize; } else { if (prev_cropsize < cropsize) { new_buff = _TIFFrealloc(crop_buff, cropsize); if (!new_buff) { free (crop_buff); crop_buff = (unsigned char *)_TIFFmalloc(cropsize); } else crop_buff = new_buff; _TIFFmemset(crop_buff, 0, cropsize); } } if (!crop_buff) { TIFFError("createCroppedImage", "Unable to allocate/reallocate crop buffer"); return (-1); } *crop_buff_ptr = crop_buff; if (crop->crop_mode & CROP_INVERT) { switch (crop->photometric) { /* Just change the interpretation */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: image->photometric = crop->photometric; break; case INVERT_DATA_ONLY: case INVERT_DATA_AND_TAG: if (invertImage(image->photometric, image->spp, image->bps, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to invert colorspace for image or cropped selection"); return (-1); } if (crop->photometric == INVERT_DATA_AND_TAG) { switch (image->photometric) { case PHOTOMETRIC_MINISWHITE: image->photometric = PHOTOMETRIC_MINISBLACK; break; case PHOTOMETRIC_MINISBLACK: image->photometric = PHOTOMETRIC_MINISWHITE; break; default: break; } } break; default: break; } } if (crop->crop_mode & CROP_MIRROR) { if (mirrorImage(image->spp, image->bps, crop->mirror, crop->combined_width, crop->combined_length, crop_buff)) { TIFFError("createCroppedImage", "Failed to mirror image or cropped selection %s", (crop->rotation == MIRROR_HORIZ) ? "horizontally" : "vertically"); return (-1); } } if (crop->crop_mode & CROP_ROTATE) /* rotate should be last as it can reallocate the buffer */ { if (rotateImage(crop->rotation, image, &crop->combined_width, &crop->combined_length, crop_buff_ptr)) { TIFFError("createCroppedImage", "Failed to rotate image or cropped selection by %d degrees", crop->rotation); return (-1); } } if (crop_buff == read_buff) /* we used the read buffer for the crop buffer */ *read_buff_ptr = NULL; /* so we don't try to free it later */ return (0); } /* end createCroppedImage */ /* Code in this function is heavily indebted to code in tiffcp * with modifications by Richard Nolde to handle orientation correctly. * It will have to be updated significantly if support is added to * extract one or more samples from original image since the * original code assumes we are always copying all samples. * Use of global variables for config, compression and others * should be replaced by addition to the crop_mask struct (which * will be renamed to proc_opts indicating that is controlls * user supplied processing options, not just cropping) and * then passed in as an argument. */ static int writeCroppedImage(TIFF *in, TIFF *out, struct image_data *image, struct dump_opts *dump, uint32 width, uint32 length, unsigned char *crop_buff, int pagenum, int total_pages) { uint16 bps, spp; uint16 input_compression, input_photometric; uint16 input_planar; struct cpTag* p; input_compression = image->compression; input_photometric = image->photometric; spp = image->spp; bps = image->bps; TIFFSetField(out, TIFFTAG_IMAGEWIDTH, width); TIFFSetField(out, TIFFTAG_IMAGELENGTH, length); TIFFSetField(out, TIFFTAG_BITSPERSAMPLE, bps); TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, spp); #ifdef DEBUG2 TIFFError("writeCroppedImage", "Input compression: %s", (input_compression == COMPRESSION_OJPEG) ? "Old Jpeg" : ((input_compression == COMPRESSION_JPEG) ? "New Jpeg" : "Non Jpeg")); #endif if (compression != (uint16)-1) TIFFSetField(out, TIFFTAG_COMPRESSION, compression); else { if (input_compression == COMPRESSION_OJPEG) { compression = COMPRESSION_JPEG; jpegcolormode = JPEGCOLORMODE_RAW; TIFFSetField(out, TIFFTAG_COMPRESSION, COMPRESSION_JPEG); } else CopyField(TIFFTAG_COMPRESSION, compression); } if (compression == COMPRESSION_JPEG) { if ((input_photometric == PHOTOMETRIC_PALETTE) || /* color map indexed */ (input_photometric == PHOTOMETRIC_MASK)) /* $holdout mask */ { TIFFError ("writeCroppedImage", "JPEG compression cannot be used with %s image data", (input_photometric == PHOTOMETRIC_PALETTE) ? "palette" : "mask"); return (-1); } if ((input_photometric == PHOTOMETRIC_RGB) && (jpegcolormode == JPEGCOLORMODE_RGB)) TIFFSetField(out, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_YCBCR); else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, input_photometric); } else { if (compression == COMPRESSION_SGILOG || compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else { if (input_compression == COMPRESSION_SGILOG || input_compression == COMPRESSION_SGILOG24) { TIFFSetField(out, TIFFTAG_PHOTOMETRIC, spp == 1 ? PHOTOMETRIC_LOGL : PHOTOMETRIC_LOGLUV); } else TIFFSetField(out, TIFFTAG_PHOTOMETRIC, image->photometric); } } if (((input_photometric == PHOTOMETRIC_LOGL) || (input_photometric == PHOTOMETRIC_LOGLUV)) && ((compression != COMPRESSION_SGILOG) && (compression != COMPRESSION_SGILOG24))) { TIFFError("writeCroppedImage", "LogL and LogLuv source data require SGI_LOG or SGI_LOG24 compression"); return (-1); } if (fillorder != 0) TIFFSetField(out, TIFFTAG_FILLORDER, fillorder); else CopyTag(TIFFTAG_FILLORDER, 1, TIFF_SHORT); /* The loadimage function reads input orientation and sets * image->orientation. The correct_image_orientation function * applies the required rotation and mirror operations to * present the data in TOPLEFT orientation and updates * image->orientation if any transforms are performed, * as per EXIF standard. */ TIFFSetField(out, TIFFTAG_ORIENTATION, image->orientation); /* * Choose tiles/strip for the output image according to * the command line arguments (-tiles, -strips) and the * structure of the input image. */ if (outtiled == -1) outtiled = TIFFIsTiled(in); if (outtiled) { /* * Setup output file's tile width&height. If either * is not specified, use either the value from the * input image or, if nothing is defined, use the * library default. */ if (tilewidth == (uint32) 0) TIFFGetField(in, TIFFTAG_TILEWIDTH, &tilewidth); if (tilelength == (uint32) 0) TIFFGetField(in, TIFFTAG_TILELENGTH, &tilelength); if (tilewidth == 0 || tilelength == 0) TIFFDefaultTileSize(out, &tilewidth, &tilelength); TIFFSetField(out, TIFFTAG_TILEWIDTH, tilewidth); TIFFSetField(out, TIFFTAG_TILELENGTH, tilelength); } else { /* * RowsPerStrip is left unspecified: use either the * value from the input image or, if nothing is defined, * use the library default. */ if (rowsperstrip == (uint32) 0) { if (!TIFFGetField(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip)) rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip); if (compression != COMPRESSION_JPEG) { if (rowsperstrip > length) rowsperstrip = length; } } else if (rowsperstrip == (uint32) -1) rowsperstrip = length; TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, rowsperstrip); } TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &input_planar); if (config != (uint16) -1) TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); else CopyField(TIFFTAG_PLANARCONFIG, config); if (spp <= 4) CopyTag(TIFFTAG_TRANSFERFUNCTION, 4, TIFF_SHORT); CopyTag(TIFFTAG_COLORMAP, 4, TIFF_SHORT); /* SMinSampleValue & SMaxSampleValue */ switch (compression) { case COMPRESSION_JPEG: if (((bps % 8) == 0) || ((bps % 12) == 0)) { TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); } else { TIFFError("writeCroppedImage", "JPEG compression requires 8 or 12 bits per sample"); return (-1); } break; case COMPRESSION_LZW: case COMPRESSION_ADOBE_DEFLATE: case COMPRESSION_DEFLATE: if (predictor != (uint16)-1) TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); else CopyField(TIFFTAG_PREDICTOR, predictor); break; case COMPRESSION_CCITTFAX3: case COMPRESSION_CCITTFAX4: if (bps != 1) { TIFFError("writeCroppedImage", "Group 3/4 compression is not usable with bps > 1"); return (-1); } if (compression == COMPRESSION_CCITTFAX3) { if (g3opts != (uint32) -1) TIFFSetField(out, TIFFTAG_GROUP3OPTIONS, g3opts); else CopyField(TIFFTAG_GROUP3OPTIONS, g3opts); } else { CopyTag(TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG); } CopyTag(TIFFTAG_BADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_CLEANFAXDATA, 1, TIFF_LONG); CopyTag(TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVPARAMS, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXRECVTIME, 1, TIFF_LONG); CopyTag(TIFFTAG_FAXSUBADDRESS, 1, TIFF_ASCII); break; case COMPRESSION_NONE: break; default: break; } { uint32 len32; void** data; if (TIFFGetField(in, TIFFTAG_ICCPROFILE, &len32, &data)) TIFFSetField(out, TIFFTAG_ICCPROFILE, len32, data); } { uint16 ninks; const char* inknames; if (TIFFGetField(in, TIFFTAG_NUMBEROFINKS, &ninks)) { TIFFSetField(out, TIFFTAG_NUMBEROFINKS, ninks); if (TIFFGetField(in, TIFFTAG_INKNAMES, &inknames)) { int inknameslen = strlen(inknames) + 1; const char* cp = inknames; while (ninks > 1) { cp = strchr(cp, '\0'); if (cp) { cp++; inknameslen += (strlen(cp) + 1); } ninks--; } TIFFSetField(out, TIFFTAG_INKNAMES, inknameslen, inknames); } } } { unsigned short pg0, pg1; if (TIFFGetField(in, TIFFTAG_PAGENUMBER, &pg0, &pg1)) { TIFFSetField(out, TIFFTAG_PAGENUMBER, pagenum, total_pages); } } for (p = tags; p < &tags[NTAGS]; p++) CopyTag(p->tag, p->count, p->type); /* Compute the tile or strip dimensions and write to disk */ if (outtiled) { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write contiguous tile data for page %d", pagenum); } else { if (writeBufferToSeparateTiles (out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate tile data for page %d", pagenum); } } else { if (config == PLANARCONFIG_CONTIG) { if (writeBufferToContigStrips (out, crop_buff, length)) TIFFError("","Unable to write contiguous strip data for page %d", pagenum); } else { if (writeBufferToSeparateStrips(out, crop_buff, length, width, spp, dump)) TIFFError("","Unable to write separate strip data for page %d", pagenum); } } if (!TIFFWriteDirectory(out)) { TIFFError("","Failed to write IFD for page number %d", pagenum); TIFFClose(out); return (-1); } return (0); } /* end writeCroppedImage */ static int rotateContigSamples8bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 src_byte = 0, src_bit = 0; uint32 row, rowsize = 0, bit_offset = 0; uint8 matchbits = 0, maskbits = 0; uint8 buff1 = 0, buff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples8bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint8)-1 >> ( 8 - bps); buff1 = buff2 = 0; for (row = 0; row < length ; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (8 - src_bit - bps); buff1 = ((*next) & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } else { buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end rotateContigSamples8bits */ static int rotateContigSamples16bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint16 matchbits = 0, maskbits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples16bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint16)-1 >> (16 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (16 - src_bit - bps); if (little_endian) buff1 = (next[0] << 8) | next[1]; else buff1 = (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 8) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end rotateContigSamples16bits */ static int rotateContigSamples24bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0; uint32 row, rowsize, bit_offset; uint32 src_byte = 0, src_bit = 0; uint32 matchbits = 0, maskbits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint32)-1 >> (32 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (32 - src_bit - bps); if (little_endian) buff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; else buff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; buff1 = (buff1 & matchbits) << (src_bit); /* If we have a full buffer's worth, write it out */ if (ready_bits >= 16) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } else { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end rotateContigSamples24bits */ static int rotateContigSamples32bits(uint16 rotation, uint16 spp, uint16 bps, uint32 width, uint32 length, uint32 col, uint8 *src, uint8 *dst) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 row, rowsize, bit_offset; uint32 src_byte, src_bit; uint32 longbuff1 = 0, longbuff2 = 0; uint64 maskbits = 0, matchbits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; uint8 *next; tsample_t sample; if ((src == NULL) || (dst == NULL)) { TIFFError("rotateContigSamples24bits","Invalid src or destination buffer"); return (1); } /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ rowsize = ((bps * spp * width) + 7) / 8; ready_bits = 0; maskbits = (uint64)-1 >> (64 - bps); buff1 = buff2 = 0; for (row = 0; row < length; row++) { bit_offset = col * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } switch (rotation) { case 90: next = src + src_byte - (row * rowsize); break; case 270: next = src + src_byte + (row * rowsize); break; default: TIFFError("rotateContigSamples8bits", "Invalid rotation %d", rotation); return (1); } matchbits = maskbits << (64 - src_bit - bps); if (little_endian) { longbuff1 = (next[0] << 24) | (next[1] << 16) | (next[2] << 8) | next[3]; longbuff2 = longbuff1; } else { longbuff1 = (next[3] << 24) | (next[2] << 16) | (next[1] << 8) | next[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & matchbits) << (src_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end rotateContigSamples32bits */ /* Rotate an image by a multiple of 90 degrees clockwise */ static int rotateImage(uint16 rotation, struct image_data *image, uint32 *img_width, uint32 *img_length, unsigned char **ibuff_ptr) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, src_offset, dst_offset; uint32 i, col, width, length; uint32 colsize, buffsize, col_offset, pix_offset; unsigned char *ibuff; unsigned char *src; unsigned char *dst; uint16 spp, bps; float res_temp; unsigned char *rbuff = NULL; width = *img_width; length = *img_length; spp = image->spp; bps = image->bps; rowsize = ((bps * spp * width) + 7) / 8; colsize = ((bps * spp * length) + 7) / 8; if ((colsize * width) > (rowsize * length)) buffsize = (colsize + 1) * width; else buffsize = (rowsize + 1) * length; bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; switch (rotation) { case 0: case 360: return (0); case 90: case 180: case 270: break; default: TIFFError("rotateImage", "Invalid rotation angle %d", rotation); return (-1); } if (!(rbuff = (unsigned char *)_TIFFmalloc(buffsize))) { TIFFError("rotateImage", "Unable to allocate rotation buffer of %1u bytes", buffsize); return (-1); } _TIFFmemset(rbuff, '\0', buffsize); ibuff = *ibuff_ptr; switch (rotation) { case 180: if ((bps % 8) == 0) /* byte alligned data */ { src = ibuff; pix_offset = (spp * bps) / 8; for (row = 0; row < length; row++) { dst_offset = (length - row - 1) * rowsize; for (col = 0; col < width; col++) { col_offset = (width - col - 1) * pix_offset; dst = rbuff + dst_offset + col_offset; for (i = 0; i < bytes_per_pixel; i++) *dst++ = *src++; } } } else { /* non 8 bit per sample data */ for (row = 0; row < length; row++) { src_offset = row * rowsize; dst_offset = (length - row - 1) * rowsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (reverseSamples8bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (reverseSamples16bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (reverseSamples24bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; break; case 90: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = ((length - 1) * rowsize) + (col * bytes_per_pixel); dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src -= rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = (length - 1) * rowsize; dst_offset = col * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; case 270: if ((bps % 8) == 0) /* byte aligned data */ { for (col = 0; col < width; col++) { src_offset = col * bytes_per_pixel; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; for (row = length; row > 0; row--) { for (i = 0; i < bytes_per_pixel; i++) *dst++ = *(src + i); src += rowsize; } } } else { /* non 8 bit per sample data */ for (col = 0; col < width; col++) { src_offset = 0; dst_offset = (width - col - 1) * colsize; src = ibuff + src_offset; dst = rbuff + dst_offset; switch (shift_width) { case 1: if (bps == 1) { if (rotateContigSamples8bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; } if (rotateContigSamples16bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 2: if (rotateContigSamples24bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; case 3: case 4: case 5: if (rotateContigSamples32bits(rotation, spp, bps, width, length, col, src, dst)) { _TIFFfree(rbuff); return (-1); } break; default: TIFFError("rotateImage","Unsupported bit depth %d", bps); _TIFFfree(rbuff); return (-1); } } } _TIFFfree(ibuff); *(ibuff_ptr) = rbuff; *img_width = length; *img_length = width; image->width = length; image->length = width; res_temp = image->xres; image->xres = image->yres; image->yres = res_temp; break; default: break; } return (0); } /* end rotateImage */ static int reverseSamples8bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte, src_bit; uint32 bit_offset = 0; uint8 match_bits = 0, mask_bits = 0; uint8 buff1 = 0, buff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples8bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint8)-1 >> ( 8 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; src_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; src_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (8 - src_bit - bps); buff1 = ((*src) & match_bits) << (src_bit); if (ready_bits < 8) buff2 = (buff2 | (buff1 >> ready_bits)); else /* If we have a full buffer's worth, write it out */ { *dst++ = buff2; buff2 = buff1; ready_bits -= 8; } ready_bits += bps; } } if (ready_bits > 0) { buff1 = (buff2 & ((unsigned int)255 << (8 - ready_bits))); *dst++ = buff1; } return (0); } /* end reverseSamples8bits */ static int reverseSamples16bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint16 match_bits = 0, mask_bits = 0; uint16 buff1 = 0, buff2 = 0; uint8 bytebuff = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSample16bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint16)-1 >> (16 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (16 - high_bit - bps); if (little_endian) buff1 = (src[0] << 8) | src[1]; else buff1 = (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 8) { /* add another bps bits to the buffer */ bytebuff = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff = (buff2 >> 8); *dst++ = bytebuff; ready_bits -= 8; /* shift in new bits */ buff2 = ((buff2 << 8) | (buff1 >> ready_bits)); } ready_bits += bps; } } if (ready_bits > 0) { bytebuff = (buff2 >> 8); *dst++ = bytebuff; } return (0); } /* end reverseSamples16bits */ static int reverseSamples24bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0; uint32 col; uint32 src_byte = 0, high_bit = 0; uint32 bit_offset = 0; uint32 match_bits = 0, mask_bits = 0; uint32 buff1 = 0, buff2 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples24bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint32)-1 >> (32 - bps); dst = obuff; for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (32 - high_bit - bps); if (little_endian) buff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; else buff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; buff1 = (buff1 & match_bits) << (high_bit); if (ready_bits < 16) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 16); *dst++ = bytebuff2; ready_bits -= 16; /* shift in new bits */ buff2 = ((buff2 << 16) | (buff1 >> ready_bits)); } ready_bits += bps; } } /* catch any trailing bits at the end of the line */ while (ready_bits > 0) { bytebuff1 = (buff2 >> 24); *dst++ = bytebuff1; buff2 = (buff2 << 8); bytebuff2 = bytebuff1; ready_bits -= 8; } return (0); } /* end reverseSamples24bits */ static int reverseSamples32bits (uint16 spp, uint16 bps, uint32 width, uint8 *ibuff, uint8 *obuff) { int ready_bits = 0 /*, shift_width = 0 */; /* int bytes_per_sample, bytes_per_pixel; */ uint32 bit_offset; uint32 src_byte = 0, high_bit = 0; uint32 col; uint32 longbuff1 = 0, longbuff2 = 0; uint64 mask_bits = 0, match_bits = 0; uint64 buff1 = 0, buff2 = 0, buff3 = 0; uint8 bytebuff1 = 0, bytebuff2 = 0, bytebuff3 = 0, bytebuff4 = 0; unsigned char *src; unsigned char *dst; tsample_t sample; if ((ibuff == NULL) || (obuff == NULL)) { TIFFError("reverseSamples32bits","Invalid image or work buffer"); return (1); } ready_bits = 0; mask_bits = (uint64)-1 >> (64 - bps); dst = obuff; /* bytes_per_sample = (bps + 7) / 8; */ /* bytes_per_pixel = ((bps * spp) + 7) / 8; */ /* if (bytes_per_pixel < (bytes_per_sample + 1)) */ /* shift_width = bytes_per_pixel; */ /* else */ /* shift_width = bytes_per_sample + 1; */ for (col = width; col > 0; col--) { /* Compute src byte(s) and bits within byte(s) */ bit_offset = (col - 1) * bps * spp; for (sample = 0; sample < spp; sample++) { if (sample == 0) { src_byte = bit_offset / 8; high_bit = bit_offset % 8; } else { src_byte = (bit_offset + (sample * bps)) / 8; high_bit = (bit_offset + (sample * bps)) % 8; } src = ibuff + src_byte; match_bits = mask_bits << (64 - high_bit - bps); if (little_endian) { longbuff1 = (src[0] << 24) | (src[1] << 16) | (src[2] << 8) | src[3]; longbuff2 = longbuff1; } else { longbuff1 = (src[3] << 24) | (src[2] << 16) | (src[1] << 8) | src[0]; longbuff2 = longbuff1; } buff3 = ((uint64)longbuff1 << 32) | longbuff2; buff1 = (buff3 & match_bits) << (high_bit); if (ready_bits < 32) { /* add another bps bits to the buffer */ bytebuff1 = bytebuff2 = bytebuff3 = bytebuff4 = 0; buff2 = (buff2 | (buff1 >> ready_bits)); } else /* If we have a full buffer's worth, write it out */ { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; bytebuff2 = (buff2 >> 48); *dst++ = bytebuff2; bytebuff3 = (buff2 >> 40); *dst++ = bytebuff3; bytebuff4 = (buff2 >> 32); *dst++ = bytebuff4; ready_bits -= 32; /* shift in new bits */ buff2 = ((buff2 << 32) | (buff1 >> ready_bits)); } ready_bits += bps; } } while (ready_bits > 0) { bytebuff1 = (buff2 >> 56); *dst++ = bytebuff1; buff2 = (buff2 << 8); ready_bits -= 8; } return (0); } /* end reverseSamples32bits */ static int reverseSamplesBytes (uint16 spp, uint16 bps, uint32 width, uint8 *src, uint8 *dst) { int i; uint32 col, bytes_per_pixel, col_offset; uint8 bytebuff1; unsigned char swapbuff[32]; if ((src == NULL) || (dst == NULL)) { TIFFError("reverseSamplesBytes","Invalid input or output buffer"); return (1); } bytes_per_pixel = ((bps * spp) + 7) / 8; if( bytes_per_pixel > sizeof(swapbuff) ) { TIFFError("reverseSamplesBytes","bytes_per_pixel too large"); return (1); } switch (bps / 8) { case 8: /* Use memcpy for multiple bytes per sample data */ case 4: case 3: case 2: for (col = 0; col < (width / 2); col++) { col_offset = col * bytes_per_pixel; _TIFFmemcpy (swapbuff, src + col_offset, bytes_per_pixel); _TIFFmemcpy (src + col_offset, dst - col_offset - bytes_per_pixel, bytes_per_pixel); _TIFFmemcpy (dst - col_offset - bytes_per_pixel, swapbuff, bytes_per_pixel); } break; case 1: /* Use byte copy only for single byte per sample data */ for (col = 0; col < (width / 2); col++) { for (i = 0; i < spp; i++) { bytebuff1 = *src; *src++ = *(dst - spp + i); *(dst - spp + i) = bytebuff1; } dst -= spp; } break; default: TIFFError("reverseSamplesBytes","Unsupported bit depth %d", bps); return (1); } return (0); } /* end reverseSamplesBytes */ /* Mirror an image horizontally or vertically */ static int mirrorImage(uint16 spp, uint16 bps, uint16 mirror, uint32 width, uint32 length, unsigned char *ibuff) { int shift_width; uint32 bytes_per_pixel, bytes_per_sample; uint32 row, rowsize, row_offset; unsigned char *line_buff = NULL; unsigned char *src; unsigned char *dst; src = ibuff; rowsize = ((width * bps * spp) + 7) / 8; switch (mirror) { case MIRROR_BOTH: case MIRROR_VERT: line_buff = (unsigned char *)_TIFFmalloc(rowsize); if (line_buff == NULL) { TIFFError ("mirrorImage", "Unable to allocate mirror line buffer of %1u bytes", rowsize); return (-1); } dst = ibuff + (rowsize * (length - 1)); for (row = 0; row < length / 2; row++) { _TIFFmemcpy(line_buff, src, rowsize); _TIFFmemcpy(src, dst, rowsize); _TIFFmemcpy(dst, line_buff, rowsize); src += (rowsize); dst -= (rowsize); } if (line_buff) _TIFFfree(line_buff); if (mirror == MIRROR_VERT) break; case MIRROR_HORIZ : if ((bps % 8) == 0) /* byte alligned data */ { for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; dst = ibuff + row_offset + rowsize; if (reverseSamplesBytes(spp, bps, width, src, dst)) { return (-1); } } } else { /* non 8 bit per sample data */ if (!(line_buff = (unsigned char *)_TIFFmalloc(rowsize + 1))) { TIFFError("mirrorImage", "Unable to allocate mirror line buffer"); return (-1); } bytes_per_sample = (bps + 7) / 8; bytes_per_pixel = ((bps * spp) + 7) / 8; if (bytes_per_pixel < (bytes_per_sample + 1)) shift_width = bytes_per_pixel; else shift_width = bytes_per_sample + 1; for (row = 0; row < length; row++) { row_offset = row * rowsize; src = ibuff + row_offset; _TIFFmemset (line_buff, '\0', rowsize); switch (shift_width) { case 1: if (reverseSamples16bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 2: if (reverseSamples24bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; case 3: case 4: case 5: if (reverseSamples32bits(spp, bps, width, src, line_buff)) { _TIFFfree(line_buff); return (-1); } _TIFFmemcpy (src, line_buff, rowsize); break; default: TIFFError("mirrorImage","Unsupported bit depth %d", bps); _TIFFfree(line_buff); return (-1); } } if (line_buff) _TIFFfree(line_buff); } break; default: TIFFError ("mirrorImage", "Invalid mirror axis %d", mirror); return (-1); break; } return (0); } /* Invert the light and dark values for a bilevel or grayscale image */ static int invertImage(uint16 photometric, uint16 spp, uint16 bps, uint32 width, uint32 length, unsigned char *work_buff) { uint32 row, col; unsigned char bytebuff1, bytebuff2, bytebuff3, bytebuff4; unsigned char *src; uint16 *src_uint16; uint32 *src_uint32; if (spp != 1) { TIFFError("invertImage", "Image inversion not supported for more than one sample per pixel"); return (-1); } if (photometric != PHOTOMETRIC_MINISWHITE && photometric != PHOTOMETRIC_MINISBLACK) { TIFFError("invertImage", "Only black and white and grayscale images can be inverted"); return (-1); } src = work_buff; if (src == NULL) { TIFFError ("invertImage", "Invalid crop buffer passed to invertImage"); return (-1); } switch (bps) { case 32: src_uint32 = (uint32 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint32 = (uint32)0xFFFFFFFF - *src_uint32; src_uint32++; } break; case 16: src_uint16 = (uint16 *)src; for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src_uint16 = (uint16)0xFFFF - *src_uint16; src_uint16++; } break; case 8: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { *src = (uint8)255 - *src; src++; } break; case 4: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 16 - (uint8)(*src & 240 >> 4); bytebuff2 = 16 - (*src & 15); *src = bytebuff1 << 4 & bytebuff2; src++; } break; case 2: for (row = 0; row < length; row++) for (col = 0; col < width; col++) { bytebuff1 = 4 - (uint8)(*src & 192 >> 6); bytebuff2 = 4 - (uint8)(*src & 48 >> 4); bytebuff3 = 4 - (uint8)(*src & 12 >> 2); bytebuff4 = 4 - (uint8)(*src & 3); *src = (bytebuff1 << 6) || (bytebuff2 << 4) || (bytebuff3 << 2) || bytebuff4; src++; } break; case 1: for (row = 0; row < length; row++) for (col = 0; col < width; col += 8 /(spp * bps)) { *src = ~(*src); src++; } break; default: TIFFError("invertImage", "Unsupported bit depth %d", bps); return (-1); } return (0); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5480_2
crossvul-cpp_data_bad_4988_0
/* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt. | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Piere-Alain Joye <pierre@php.net> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "ext/pcre/php_pcre.h" #include "ext/standard/php_filestat.h" #include "php_zip.h" /* zip_open is a macro for renaming libzip zipopen, so we need to use PHP_NAMED_FUNCTION */ static PHP_NAMED_FUNCTION(zif_zip_open); static PHP_NAMED_FUNCTION(zif_zip_read); static PHP_NAMED_FUNCTION(zif_zip_close); static PHP_NAMED_FUNCTION(zif_zip_entry_read); static PHP_NAMED_FUNCTION(zif_zip_entry_filesize); static PHP_NAMED_FUNCTION(zif_zip_entry_name); static PHP_NAMED_FUNCTION(zif_zip_entry_compressedsize); static PHP_NAMED_FUNCTION(zif_zip_entry_compressionmethod); static PHP_NAMED_FUNCTION(zif_zip_entry_open); static PHP_NAMED_FUNCTION(zif_zip_entry_close); #ifdef HAVE_GLOB #ifndef PHP_WIN32 #include <glob.h> #else #include "win32/glob.h" #endif #endif /* {{{ Resource le */ static int le_zip_dir; #define le_zip_dir_name "Zip Directory" static int le_zip_entry; #define le_zip_entry_name "Zip Entry" /* }}} */ /* {{{ PHP_ZIP_STAT_INDEX(za, index, flags, sb) */ #define PHP_ZIP_STAT_INDEX(za, index, flags, sb) \ if (zip_stat_index(za, index, flags, &sb) != 0) { \ RETURN_FALSE; \ } /* }}} */ /* {{{ PHP_ZIP_STAT_PATH(za, path, path_len, flags, sb) */ #define PHP_ZIP_STAT_PATH(za, path, path_len, flags, sb) \ if (path_len < 1) { \ php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); \ RETURN_FALSE; \ } \ if (zip_stat(za, path, flags, &sb) != 0) { \ RETURN_FALSE; \ } /* }}} */ /* {{{ PHP_ZIP_SET_FILE_COMMENT(za, index, comment, comment_len) */ #define PHP_ZIP_SET_FILE_COMMENT(za, index, comment, comment_len) \ if (comment_len == 0) { \ /* Passing NULL remove the existing comment */ \ if (zip_set_file_comment(za, index, NULL, 0) < 0) { \ RETURN_FALSE; \ } \ } else if (zip_set_file_comment(za, index, comment, comment_len) < 0) { \ RETURN_FALSE; \ } \ RETURN_TRUE; /* }}} */ # define add_ascii_assoc_string add_assoc_string # define add_ascii_assoc_long add_assoc_long /* Flatten a path by making a relative path (to .)*/ static char * php_zip_make_relative_path(char *path, size_t path_len) /* {{{ */ { char *path_begin = path; size_t i; if (path_len < 1 || path == NULL) { return NULL; } if (IS_SLASH(path[0])) { return path + 1; } i = path_len; while (1) { while (i > 0 && !IS_SLASH(path[i])) { i--; } if (!i) { return path; } if (i >= 2 && (path[i -1] == '.' || path[i -1] == ':')) { /* i is the position of . or :, add 1 for / */ path_begin = path + i + 1; break; } i--; } return path_begin; } /* }}} */ # define CWD_STATE_ALLOC(l) emalloc(l) # define CWD_STATE_FREE(s) efree(s) /* {{{ php_zip_extract_file */ static int php_zip_extract_file(struct zip * za, char *dest, char *file, int file_len) { php_stream_statbuf ssb; struct zip_file *zf; struct zip_stat sb; char b[8192]; int n, len, ret; php_stream *stream; char *fullpath; char *file_dirname_fullpath; char file_dirname[MAXPATHLEN]; size_t dir_len; int is_dir_only = 0; char *path_cleaned; size_t path_cleaned_len; cwd_state new_state; zend_string *file_basename; new_state.cwd = CWD_STATE_ALLOC(1); new_state.cwd[0] = '\0'; new_state.cwd_length = 0; /* Clean/normlize the path and then transform any path (absolute or relative) to a path relative to cwd (../../mydir/foo.txt > mydir/foo.txt) */ virtual_file_ex(&new_state, file, NULL, CWD_EXPAND); path_cleaned = php_zip_make_relative_path(new_state.cwd, new_state.cwd_length); if(!path_cleaned) { return 0; } path_cleaned_len = strlen(path_cleaned); if (path_cleaned_len >= MAXPATHLEN || zip_stat(za, file, 0, &sb) != 0) { return 0; } /* it is a directory only, see #40228 */ if (path_cleaned_len > 1 && IS_SLASH(path_cleaned[path_cleaned_len - 1])) { len = spprintf(&file_dirname_fullpath, 0, "%s/%s", dest, path_cleaned); is_dir_only = 1; } else { memcpy(file_dirname, path_cleaned, path_cleaned_len); dir_len = php_dirname(file_dirname, path_cleaned_len); if (dir_len <= 0 || (dir_len == 1 && file_dirname[0] == '.')) { len = spprintf(&file_dirname_fullpath, 0, "%s", dest); } else { len = spprintf(&file_dirname_fullpath, 0, "%s/%s", dest, file_dirname); } file_basename = php_basename(path_cleaned, path_cleaned_len, NULL, 0); if (ZIP_OPENBASEDIR_CHECKPATH(file_dirname_fullpath)) { efree(file_dirname_fullpath); zend_string_release(file_basename); CWD_STATE_FREE(new_state.cwd); return 0; } } /* let see if the path already exists */ if (php_stream_stat_path_ex(file_dirname_fullpath, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL) < 0) { ret = php_stream_mkdir(file_dirname_fullpath, 0777, PHP_STREAM_MKDIR_RECURSIVE|REPORT_ERRORS, NULL); if (!ret) { efree(file_dirname_fullpath); if (!is_dir_only) { zend_string_release(file_basename); CWD_STATE_FREE(new_state.cwd); } return 0; } } /* it is a standalone directory, job done */ if (is_dir_only) { efree(file_dirname_fullpath); CWD_STATE_FREE(new_state.cwd); return 1; } len = spprintf(&fullpath, 0, "%s/%s", file_dirname_fullpath, ZSTR_VAL(file_basename)); if (!len) { efree(file_dirname_fullpath); zend_string_release(file_basename); CWD_STATE_FREE(new_state.cwd); return 0; } else if (len > MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "Full extraction path exceed MAXPATHLEN (%i)", MAXPATHLEN); efree(file_dirname_fullpath); zend_string_release(file_basename); CWD_STATE_FREE(new_state.cwd); return 0; } /* check again the full path, not sure if it * is required, does a file can have a different * safemode status as its parent folder? */ if (ZIP_OPENBASEDIR_CHECKPATH(fullpath)) { efree(fullpath); efree(file_dirname_fullpath); zend_string_release(file_basename); CWD_STATE_FREE(new_state.cwd); return 0; } stream = php_stream_open_wrapper(fullpath, "w+b", REPORT_ERRORS, NULL); if (stream == NULL) { n = -1; goto done; } zf = zip_fopen(za, file, 0); if (zf == NULL) { n = -1; php_stream_close(stream); goto done; } n = 0; while ((n=zip_fread(zf, b, sizeof(b))) > 0) { php_stream_write(stream, b, n); } php_stream_close(stream); n = zip_fclose(zf); done: efree(fullpath); zend_string_release(file_basename); efree(file_dirname_fullpath); CWD_STATE_FREE(new_state.cwd); if (n<0) { return 0; } else { return 1; } } /* }}} */ static int php_zip_add_file(struct zip *za, const char *filename, size_t filename_len, char *entry_name, size_t entry_name_len, long offset_start, long offset_len) /* {{{ */ { struct zip_source *zs; char resolved_path[MAXPATHLEN]; zval exists_flag; if (ZIP_OPENBASEDIR_CHECKPATH(filename)) { return -1; } if (!expand_filepath(filename, resolved_path)) { return -1; } php_stat(resolved_path, strlen(resolved_path), FS_EXISTS, &exists_flag); if (Z_TYPE(exists_flag) == IS_FALSE) { return -1; } zs = zip_source_file(za, resolved_path, offset_start, offset_len); if (!zs) { return -1; } if (zip_file_add(za, entry_name, zs, ZIP_FL_OVERWRITE) < 0) { zip_source_free(zs); return -1; } else { zip_error_clear(za); return 1; } } /* }}} */ static int php_zip_parse_options(zval *options, zend_long *remove_all_path, char **remove_path, size_t *remove_path_len, char **add_path, size_t *add_path_len) /* {{{ */ { zval *option; if ((option = zend_hash_str_find(Z_ARRVAL_P(options), "remove_all_path", sizeof("remove_all_path") - 1)) != NULL) { *remove_all_path = zval_get_long(option); } /* If I add more options, it would make sense to create a nice static struct and loop over it. */ if ((option = zend_hash_str_find(Z_ARRVAL_P(options), "remove_path", sizeof("remove_path") - 1)) != NULL) { if (Z_TYPE_P(option) != IS_STRING) { php_error_docref(NULL, E_WARNING, "remove_path option expected to be a string"); return -1; } if (Z_STRLEN_P(option) < 1) { php_error_docref(NULL, E_NOTICE, "Empty string given as remove_path option"); return -1; } if (Z_STRLEN_P(option) >= MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "remove_path string is too long (max: %d, %zd given)", MAXPATHLEN - 1, Z_STRLEN_P(option)); return -1; } *remove_path_len = Z_STRLEN_P(option); *remove_path = Z_STRVAL_P(option); } if ((option = zend_hash_str_find(Z_ARRVAL_P(options), "add_path", sizeof("add_path") - 1)) != NULL) { if (Z_TYPE_P(option) != IS_STRING) { php_error_docref(NULL, E_WARNING, "add_path option expected to be a string"); return -1; } if (Z_STRLEN_P(option) < 1) { php_error_docref(NULL, E_NOTICE, "Empty string given as the add_path option"); return -1; } if (Z_STRLEN_P(option) >= MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "add_path string too long (max: %d, %zd given)", MAXPATHLEN - 1, Z_STRLEN_P(option)); return -1; } *add_path_len = Z_STRLEN_P(option); *add_path = Z_STRVAL_P(option); } return 1; } /* }}} */ /* {{{ REGISTER_ZIP_CLASS_CONST_LONG */ #define REGISTER_ZIP_CLASS_CONST_LONG(const_name, value) \ zend_declare_class_constant_long(zip_class_entry, const_name, sizeof(const_name)-1, (zend_long)value); /* }}} */ /* {{{ ZIP_FROM_OBJECT */ #define ZIP_FROM_OBJECT(intern, object) \ { \ ze_zip_object *obj = Z_ZIP_P(object); \ intern = obj->za; \ if (!intern) { \ php_error_docref(NULL, E_WARNING, "Invalid or uninitialized Zip object"); \ RETURN_FALSE; \ } \ } /* }}} */ /* {{{ RETURN_SB(sb) */ #define RETURN_SB(sb) \ { \ array_init(return_value); \ add_ascii_assoc_string(return_value, "name", (char *)(sb)->name); \ add_ascii_assoc_long(return_value, "index", (zend_long) (sb)->index); \ add_ascii_assoc_long(return_value, "crc", (zend_long) (sb)->crc); \ add_ascii_assoc_long(return_value, "size", (zend_long) (sb)->size); \ add_ascii_assoc_long(return_value, "mtime", (zend_long) (sb)->mtime); \ add_ascii_assoc_long(return_value, "comp_size", (zend_long) (sb)->comp_size); \ add_ascii_assoc_long(return_value, "comp_method", (zend_long) (sb)->comp_method); \ } /* }}} */ static int php_zip_status(struct zip *za) /* {{{ */ { #if LIBZIP_VERSION_MAJOR < 1 int zep, syp; zip_error_get(za, &zep, &syp); #else int zep; zip_error_t *err; err = zip_get_error(za); zep = zip_error_code_zip(err); zip_error_fini(err); #endif return zep; } /* }}} */ static int php_zip_status_sys(struct zip *za) /* {{{ */ { #if LIBZIP_VERSION_MAJOR < 1 int zep, syp; zip_error_get(za, &zep, &syp); #else int syp; zip_error_t *err; err = zip_get_error(za); syp = zip_error_code_system(err); zip_error_fini(err); #endif return syp; } /* }}} */ static int php_zip_get_num_files(struct zip *za) /* {{{ */ { return zip_get_num_files(za); } /* }}} */ static char * php_zipobj_get_filename(ze_zip_object *obj) /* {{{ */ { if (!obj) { return NULL; } if (obj->filename) { return obj->filename; } return NULL; } /* }}} */ static char * php_zipobj_get_zip_comment(struct zip *za, int *len) /* {{{ */ { if (za) { return (char *)zip_get_archive_comment(za, len, 0); } return NULL; } /* }}} */ #ifdef HAVE_GLOB /* {{{ */ #ifndef GLOB_ONLYDIR #define GLOB_ONLYDIR (1<<30) #define GLOB_EMULATE_ONLYDIR #define GLOB_FLAGMASK (~GLOB_ONLYDIR) #else #define GLOB_FLAGMASK (~0) #endif #ifndef GLOB_BRACE # define GLOB_BRACE 0 #endif #ifndef GLOB_MARK # define GLOB_MARK 0 #endif #ifndef GLOB_NOSORT # define GLOB_NOSORT 0 #endif #ifndef GLOB_NOCHECK # define GLOB_NOCHECK 0 #endif #ifndef GLOB_NOESCAPE # define GLOB_NOESCAPE 0 #endif #ifndef GLOB_ERR # define GLOB_ERR 0 #endif /* This is used for checking validity of passed flags (passing invalid flags causes segfault in glob()!! */ #define GLOB_AVAILABLE_FLAGS (0 | GLOB_BRACE | GLOB_MARK | GLOB_NOSORT | GLOB_NOCHECK | GLOB_NOESCAPE | GLOB_ERR | GLOB_ONLYDIR) #endif /* }}} */ int php_zip_glob(char *pattern, int pattern_len, zend_long flags, zval *return_value) /* {{{ */ { #ifdef HAVE_GLOB char cwd[MAXPATHLEN]; int cwd_skip = 0; #ifdef ZTS char work_pattern[MAXPATHLEN]; char *result; #endif glob_t globbuf; int n; int ret; if (pattern_len >= MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "Pattern exceeds the maximum allowed length of %d characters", MAXPATHLEN); return -1; } if ((GLOB_AVAILABLE_FLAGS & flags) != flags) { php_error_docref(NULL, E_WARNING, "At least one of the passed flags is invalid or not supported on this platform"); return -1; } #ifdef ZTS if (!IS_ABSOLUTE_PATH(pattern, pattern_len)) { result = VCWD_GETCWD(cwd, MAXPATHLEN); if (!result) { cwd[0] = '\0'; } #ifdef PHP_WIN32 if (IS_SLASH(*pattern)) { cwd[2] = '\0'; } #endif cwd_skip = strlen(cwd)+1; snprintf(work_pattern, MAXPATHLEN, "%s%c%s", cwd, DEFAULT_SLASH, pattern); pattern = work_pattern; } #endif globbuf.gl_offs = 0; if (0 != (ret = glob(pattern, flags & GLOB_FLAGMASK, NULL, &globbuf))) { #ifdef GLOB_NOMATCH if (GLOB_NOMATCH == ret) { /* Some glob implementation simply return no data if no matches were found, others return the GLOB_NOMATCH error code. We don't want to treat GLOB_NOMATCH as an error condition so that PHP glob() behaves the same on both types of implementations and so that 'foreach (glob() as ...' can be used for simple glob() calls without further error checking. */ array_init(return_value); return 0; } #endif return 0; } /* now catch the FreeBSD style of "no matches" */ if (!globbuf.gl_pathc || !globbuf.gl_pathv) { array_init(return_value); return 0; } /* we assume that any glob pattern will match files from one directory only so checking the dirname of the first match should be sufficient */ strncpy(cwd, globbuf.gl_pathv[0], MAXPATHLEN); if (ZIP_OPENBASEDIR_CHECKPATH(cwd)) { return -1; } array_init(return_value); for (n = 0; n < globbuf.gl_pathc; n++) { /* we need to do this every time since GLOB_ONLYDIR does not guarantee that * all directories will be filtered. GNU libc documentation states the * following: * If the information about the type of the file is easily available * non-directories will be rejected but no extra work will be done to * determine the information for each file. I.e., the caller must still be * able to filter directories out. */ if (flags & GLOB_ONLYDIR) { zend_stat_t s; if (0 != VCWD_STAT(globbuf.gl_pathv[n], &s)) { continue; } if (S_IFDIR != (s.st_mode & S_IFMT)) { continue; } } add_next_index_string(return_value, globbuf.gl_pathv[n]+cwd_skip); } globfree(&globbuf); return globbuf.gl_pathc; #else php_error_docref(NULL, E_ERROR, "Glob support is not available"); return 0; #endif /* HAVE_GLOB */ } /* }}} */ int php_zip_pcre(zend_string *regexp, char *path, int path_len, zval *return_value) /* {{{ */ { #ifdef ZTS char cwd[MAXPATHLEN]; int cwd_skip = 0; char work_path[MAXPATHLEN]; char *result; #endif int files_cnt; zend_string **namelist; #ifdef ZTS if (!IS_ABSOLUTE_PATH(path, path_len)) { result = VCWD_GETCWD(cwd, MAXPATHLEN); if (!result) { cwd[0] = '\0'; } #ifdef PHP_WIN32 if (IS_SLASH(*path)) { cwd[2] = '\0'; } #endif cwd_skip = strlen(cwd)+1; snprintf(work_path, MAXPATHLEN, "%s%c%s", cwd, DEFAULT_SLASH, path); path = work_path; } #endif if (ZIP_OPENBASEDIR_CHECKPATH(path)) { return -1; } files_cnt = php_stream_scandir(path, &namelist, NULL, (void *) php_stream_dirent_alphasort); if (files_cnt > 0) { pcre *re = NULL; pcre_extra *pcre_extra = NULL; int preg_options = 0, i; re = pcre_get_compiled_regex(regexp, &pcre_extra, &preg_options); if (!re) { php_error_docref(NULL, E_WARNING, "Invalid expression"); return -1; } array_init(return_value); /* only the files, directories are ignored */ for (i = 0; i < files_cnt; i++) { zend_stat_t s; char fullpath[MAXPATHLEN]; int ovector[3]; int matches; int namelist_len = ZSTR_LEN(namelist[i]); if ((namelist_len == 1 && ZSTR_VAL(namelist[i])[0] == '.') || (namelist_len == 2 && ZSTR_VAL(namelist[i])[0] == '.' && ZSTR_VAL(namelist[i])[1] == '.')) { zend_string_release(namelist[i]); continue; } if ((path_len + namelist_len + 1) >= MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "add_path string too long (max: %i, %i given)", MAXPATHLEN - 1, (path_len + namelist_len + 1)); zend_string_release(namelist[i]); break; } snprintf(fullpath, MAXPATHLEN, "%s%c%s", path, DEFAULT_SLASH, ZSTR_VAL(namelist[i])); if (0 != VCWD_STAT(fullpath, &s)) { php_error_docref(NULL, E_WARNING, "Cannot read <%s>", fullpath); zend_string_release(namelist[i]); continue; } if (S_IFDIR == (s.st_mode & S_IFMT)) { zend_string_release(namelist[i]); continue; } matches = pcre_exec(re, NULL, ZSTR_VAL(namelist[i]), ZSTR_LEN(namelist[i]), 0, 0, ovector, 3); /* 0 means that the vector is too small to hold all the captured substring offsets */ if (matches < 0) { zend_string_release(namelist[i]); continue; } add_next_index_string(return_value, fullpath); zend_string_release(namelist[i]); } efree(namelist); } return files_cnt; } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_open, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_close, 0, 0, 1) ZEND_ARG_INFO(0, zip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_read, 0, 0, 1) ZEND_ARG_INFO(0, zip) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_open, 0, 0, 2) ZEND_ARG_INFO(0, zip_dp) ZEND_ARG_INFO(0, zip_entry) ZEND_ARG_INFO(0, mode) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_close, 0, 0, 1) ZEND_ARG_INFO(0, zip_ent) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_read, 0, 0, 1) ZEND_ARG_INFO(0, zip_entry) ZEND_ARG_INFO(0, len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_name, 0, 0, 1) ZEND_ARG_INFO(0, zip_entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_compressedsize, 0, 0, 1) ZEND_ARG_INFO(0, zip_entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_filesize, 0, 0, 1) ZEND_ARG_INFO(0, zip_entry) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_zip_entry_compressionmethod, 0, 0, 1) ZEND_ARG_INFO(0, zip_entry) ZEND_END_ARG_INFO() /* }}} */ /* {{{ zend_function_entry */ static const zend_function_entry zip_functions[] = { ZEND_RAW_FENTRY("zip_open", zif_zip_open, arginfo_zip_open, 0) ZEND_RAW_FENTRY("zip_close", zif_zip_close, arginfo_zip_close, 0) ZEND_RAW_FENTRY("zip_read", zif_zip_read, arginfo_zip_read, 0) PHP_FE(zip_entry_open, arginfo_zip_entry_open) PHP_FE(zip_entry_close, arginfo_zip_entry_close) PHP_FE(zip_entry_read, arginfo_zip_entry_read) PHP_FE(zip_entry_filesize, arginfo_zip_entry_filesize) PHP_FE(zip_entry_name, arginfo_zip_entry_name) PHP_FE(zip_entry_compressedsize, arginfo_zip_entry_compressedsize) PHP_FE(zip_entry_compressionmethod, arginfo_zip_entry_compressionmethod) #ifdef PHP_FE_END PHP_FE_END #else {NULL,NULL,NULL} #endif }; /* }}} */ /* {{{ ZE2 OO definitions */ static zend_class_entry *zip_class_entry; static zend_object_handlers zip_object_handlers; static HashTable zip_prop_handlers; typedef int (*zip_read_int_t)(struct zip *za); typedef char *(*zip_read_const_char_t)(struct zip *za, int *len); typedef char *(*zip_read_const_char_from_ze_t)(ze_zip_object *obj); typedef struct _zip_prop_handler { zip_read_int_t read_int_func; zip_read_const_char_t read_const_char_func; zip_read_const_char_from_ze_t read_const_char_from_obj_func; int type; } zip_prop_handler; /* }}} */ static void php_zip_register_prop_handler(HashTable *prop_handler, char *name, zip_read_int_t read_int_func, zip_read_const_char_t read_char_func, zip_read_const_char_from_ze_t read_char_from_obj_func, int rettype) /* {{{ */ { zip_prop_handler hnd; hnd.read_const_char_func = read_char_func; hnd.read_int_func = read_int_func; hnd.read_const_char_from_obj_func = read_char_from_obj_func; hnd.type = rettype; zend_hash_str_add_mem(prop_handler, name, strlen(name), &hnd, sizeof(zip_prop_handler)); } /* }}} */ static zval *php_zip_property_reader(ze_zip_object *obj, zip_prop_handler *hnd, zval *rv) /* {{{ */ { const char *retchar = NULL; int retint = 0; int len = 0; if (obj && obj->za != NULL) { if (hnd->read_const_char_func) { retchar = hnd->read_const_char_func(obj->za, &len); } else { if (hnd->read_int_func) { retint = hnd->read_int_func(obj->za); if (retint == -1) { php_error_docref(NULL, E_WARNING, "Internal zip error returned"); return NULL; } } else { if (hnd->read_const_char_from_obj_func) { retchar = hnd->read_const_char_from_obj_func(obj); len = strlen(retchar); } } } } switch (hnd->type) { case IS_STRING: if (retchar) { ZVAL_STRINGL(rv, (char *) retchar, len); } else { ZVAL_EMPTY_STRING(rv); } break; /* case IS_TRUE */ case IS_FALSE: ZVAL_BOOL(rv, (long)retint); break; case IS_LONG: ZVAL_LONG(rv, (long)retint); break; default: ZVAL_NULL(rv); } return rv; } /* }}} */ static zval *php_zip_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */ { ze_zip_object *obj; zval tmp_member; zval *retval = NULL; zip_prop_handler *hnd = NULL; zend_object_handlers *std_hnd; if (Z_TYPE_P(member) != IS_STRING) { ZVAL_COPY(&tmp_member, member); convert_to_string(&tmp_member); member = &tmp_member; cache_slot = NULL; } obj = Z_ZIP_P(object); if (obj->prop_handler != NULL) { hnd = zend_hash_find_ptr(obj->prop_handler, Z_STR_P(member)); } if (hnd == NULL) { std_hnd = zend_get_std_object_handlers(); retval = std_hnd->get_property_ptr_ptr(object, member, type, cache_slot); } if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ static zval *php_zip_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */ { ze_zip_object *obj; zval tmp_member; zval *retval = NULL; zip_prop_handler *hnd = NULL; zend_object_handlers *std_hnd; if (Z_TYPE_P(member) != IS_STRING) { ZVAL_COPY(&tmp_member, member); convert_to_string(&tmp_member); member = &tmp_member; cache_slot = NULL; } obj = Z_ZIP_P(object); if (obj->prop_handler != NULL) { hnd = zend_hash_find_ptr(obj->prop_handler, Z_STR_P(member)); } if (hnd != NULL) { retval = php_zip_property_reader(obj, hnd, rv); if (retval == NULL) { retval = &EG(uninitialized_zval); } } else { std_hnd = zend_get_std_object_handlers(); retval = std_hnd->read_property(object, member, type, cache_slot, rv); } if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ static int php_zip_has_property(zval *object, zval *member, int type, void **cache_slot) /* {{{ */ { ze_zip_object *obj; zval tmp_member; zip_prop_handler *hnd = NULL; zend_object_handlers *std_hnd; int retval = 0; if (Z_TYPE_P(member) != IS_STRING) { ZVAL_COPY(&tmp_member, member); convert_to_string(&tmp_member); member = &tmp_member; cache_slot = NULL; } obj = Z_ZIP_P(object); if (obj->prop_handler != NULL) { hnd = zend_hash_find_ptr(obj->prop_handler, Z_STR_P(member)); } if (hnd != NULL) { zval tmp, *prop; if (type == 2) { retval = 1; } else if ((prop = php_zip_property_reader(obj, hnd, &tmp)) != NULL) { if (type == 1) { retval = zend_is_true(&tmp); } else if (type == 0) { retval = (Z_TYPE(tmp) != IS_NULL); } } zval_ptr_dtor(&tmp); } else { std_hnd = zend_get_std_object_handlers(); retval = std_hnd->has_property(object, member, type, cache_slot); } if (member == &tmp_member) { zval_dtor(member); } return retval; } /* }}} */ static HashTable *php_zip_get_properties(zval *object)/* {{{ */ { ze_zip_object *obj; HashTable *props; zip_prop_handler *hnd; zend_string *key; obj = Z_ZIP_P(object); props = zend_std_get_properties(object); if (obj->prop_handler == NULL) { return NULL; } ZEND_HASH_FOREACH_STR_KEY_PTR(obj->prop_handler, key, hnd) { zval *ret, val; ret = php_zip_property_reader(obj, hnd, &val); if (ret == NULL) { ret = &EG(uninitialized_zval); } zend_hash_update(props, key, ret); } ZEND_HASH_FOREACH_END(); return props; } /* }}} */ static void php_zip_object_free_storage(zend_object *object) /* {{{ */ { ze_zip_object * intern = php_zip_fetch_object(object); int i; if (!intern) { return; } if (intern->za) { if (zip_close(intern->za) != 0) { php_error_docref(NULL, E_WARNING, "Cannot destroy the zip context: %s", zip_strerror(intern->za)); return; } intern->za = NULL; } if (intern->buffers_cnt>0) { for (i=0; i<intern->buffers_cnt; i++) { efree(intern->buffers[i]); } efree(intern->buffers); } intern->za = NULL; zend_object_std_dtor(&intern->zo); if (intern->filename) { efree(intern->filename); } } /* }}} */ static zend_object *php_zip_object_new(zend_class_entry *class_type) /* {{{ */ { ze_zip_object *intern; intern = ecalloc(1, sizeof(ze_zip_object) + zend_object_properties_size(class_type)); intern->prop_handler = &zip_prop_handlers; zend_object_std_init(&intern->zo, class_type); object_properties_init(&intern->zo, class_type); intern->zo.handlers = &zip_object_handlers; return &intern->zo; } /* }}} */ /* {{{ Resource dtors */ /* {{{ php_zip_free_dir */ static void php_zip_free_dir(zend_resource *rsrc) { zip_rsrc * zip_int = (zip_rsrc *) rsrc->ptr; if (zip_int) { if (zip_int->za) { if (zip_close(zip_int->za) != 0) { php_error_docref(NULL, E_WARNING, "Cannot destroy the zip context"); } zip_int->za = NULL; } efree(rsrc->ptr); rsrc->ptr = NULL; } } /* }}} */ /* {{{ php_zip_free_entry */ static void php_zip_free_entry(zend_resource *rsrc) { zip_read_rsrc *zr_rsrc = (zip_read_rsrc *) rsrc->ptr; if (zr_rsrc) { if (zr_rsrc->zf) { zip_fclose(zr_rsrc->zf); zr_rsrc->zf = NULL; } efree(zr_rsrc); rsrc->ptr = NULL; } } /* }}} */ /* }}}*/ /* reset macro */ /* {{{ function prototypes */ static PHP_MINIT_FUNCTION(zip); static PHP_MSHUTDOWN_FUNCTION(zip); static PHP_MINFO_FUNCTION(zip); /* }}} */ /* {{{ zip_module_entry */ zend_module_entry zip_module_entry = { STANDARD_MODULE_HEADER, "zip", zip_functions, PHP_MINIT(zip), PHP_MSHUTDOWN(zip), NULL, NULL, PHP_MINFO(zip), PHP_ZIP_VERSION, STANDARD_MODULE_PROPERTIES }; /* }}} */ #ifdef COMPILE_DL_ZIP ZEND_GET_MODULE(zip) #endif /* set macro */ /* {{{ proto resource zip_open(string filename) Create new zip using source uri for output */ static PHP_NAMED_FUNCTION(zif_zip_open) { char resolved_path[MAXPATHLEN + 1]; zip_rsrc *rsrc_int; int err = 0; zend_string *filename; if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &filename) == FAILURE) { return; } if (ZSTR_LEN(filename) == 0) { php_error_docref(NULL, E_WARNING, "Empty string as source"); RETURN_FALSE; } if (ZIP_OPENBASEDIR_CHECKPATH(ZSTR_VAL(filename))) { RETURN_FALSE; } if(!expand_filepath(ZSTR_VAL(filename), resolved_path)) { RETURN_FALSE; } rsrc_int = (zip_rsrc *)emalloc(sizeof(zip_rsrc)); rsrc_int->za = zip_open(resolved_path, 0, &err); if (rsrc_int->za == NULL) { efree(rsrc_int); RETURN_LONG((zend_long)err); } rsrc_int->index_current = 0; rsrc_int->num_files = zip_get_num_files(rsrc_int->za); RETURN_RES(zend_register_resource(rsrc_int, le_zip_dir)); } /* }}} */ /* {{{ proto void zip_close(resource zip) Close a Zip archive */ static PHP_NAMED_FUNCTION(zif_zip_close) { zval * zip; zip_rsrc *z_rsrc = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zip) == FAILURE) { return; } if ((z_rsrc = (zip_rsrc *)zend_fetch_resource(Z_RES_P(zip), le_zip_dir_name, le_zip_dir)) == NULL) { RETURN_FALSE; } /* really close the zip will break BC :-D */ zend_list_close(Z_RES_P(zip)); } /* }}} */ /* {{{ proto resource zip_read(resource zip) Returns the next file in the archive */ static PHP_NAMED_FUNCTION(zif_zip_read) { zval *zip_dp; zip_read_rsrc *zr_rsrc; int ret; zip_rsrc *rsrc_int; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zip_dp) == FAILURE) { return; } if ((rsrc_int = (zip_rsrc *)zend_fetch_resource(Z_RES_P(zip_dp), le_zip_dir_name, le_zip_dir)) == NULL) { RETURN_FALSE; } if (rsrc_int && rsrc_int->za) { if (rsrc_int->index_current >= rsrc_int->num_files) { RETURN_FALSE; } zr_rsrc = emalloc(sizeof(zip_read_rsrc)); ret = zip_stat_index(rsrc_int->za, rsrc_int->index_current, 0, &zr_rsrc->sb); if (ret != 0) { efree(zr_rsrc); RETURN_FALSE; } zr_rsrc->zf = zip_fopen_index(rsrc_int->za, rsrc_int->index_current, 0); if (zr_rsrc->zf) { rsrc_int->index_current++; RETURN_RES(zend_register_resource(zr_rsrc, le_zip_entry)); } else { efree(zr_rsrc); RETURN_FALSE; } } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool zip_entry_open(resource zip_dp, resource zip_entry [, string mode]) Open a Zip File, pointed by the resource entry */ /* Dummy function to follow the old API */ static PHP_NAMED_FUNCTION(zif_zip_entry_open) { zval * zip; zval * zip_entry; char *mode = NULL; size_t mode_len = 0; zip_read_rsrc * zr_rsrc; zip_rsrc *z_rsrc; if (zend_parse_parameters(ZEND_NUM_ARGS(), "rr|s", &zip, &zip_entry, &mode, &mode_len) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } if ((z_rsrc = (zip_rsrc *)zend_fetch_resource(Z_RES_P(zip), le_zip_dir_name, le_zip_dir)) == NULL) { RETURN_FALSE; } if (zr_rsrc->zf != NULL) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool zip_entry_close(resource zip_ent) Close a zip entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_close) { zval * zip_entry; zip_read_rsrc * zr_rsrc; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zip_entry) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } RETURN_BOOL(SUCCESS == zend_list_close(Z_RES_P(zip_entry))); } /* }}} */ /* {{{ proto mixed zip_entry_read(resource zip_entry [, int len]) Read from an open directory entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_read) { zval * zip_entry; zend_long len = 0; zip_read_rsrc * zr_rsrc; zend_string *buffer; int n = 0; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &zip_entry, &len) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } if (len <= 0) { len = 1024; } if (zr_rsrc->zf) { buffer = zend_string_alloc(len, 0); n = zip_fread(zr_rsrc->zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n > 0) { ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } else { zend_string_free(buffer); RETURN_EMPTY_STRING() } } else { RETURN_FALSE; } } /* }}} */ static void php_zip_entry_get_info(INTERNAL_FUNCTION_PARAMETERS, int opt) /* {{{ */ { zval * zip_entry; zip_read_rsrc * zr_rsrc; if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &zip_entry) == FAILURE) { return; } if ((zr_rsrc = (zip_read_rsrc *)zend_fetch_resource(Z_RES_P(zip_entry), le_zip_entry_name, le_zip_entry)) == NULL) { RETURN_FALSE; } if (!zr_rsrc->zf) { RETURN_FALSE; } switch (opt) { case 0: RETURN_STRING((char *)zr_rsrc->sb.name); break; case 1: RETURN_LONG((zend_long) (zr_rsrc->sb.comp_size)); break; case 2: RETURN_LONG((zend_long) (zr_rsrc->sb.size)); break; case 3: switch (zr_rsrc->sb.comp_method) { case 0: RETURN_STRING("stored"); break; case 1: RETURN_STRING("shrunk"); break; case 2: case 3: case 4: case 5: RETURN_STRING("reduced"); break; case 6: RETURN_STRING("imploded"); break; case 7: RETURN_STRING("tokenized"); break; case 8: RETURN_STRING("deflated"); break; case 9: RETURN_STRING("deflatedX"); break; case 10: RETURN_STRING("implodedX"); break; default: RETURN_FALSE; } RETURN_LONG((zend_long) (zr_rsrc->sb.comp_method)); break; } } /* }}} */ /* {{{ proto string zip_entry_name(resource zip_entry) Return the name given a ZZip entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_name) { php_zip_entry_get_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto int zip_entry_compressedsize(resource zip_entry) Return the compressed size of a ZZip entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_compressedsize) { php_zip_entry_get_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto int zip_entry_filesize(resource zip_entry) Return the actual filesize of a ZZip entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_filesize) { php_zip_entry_get_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto string zip_entry_compressionmethod(resource zip_entry) Return a string containing the compression method used on a particular entry */ static PHP_NAMED_FUNCTION(zif_zip_entry_compressionmethod) { php_zip_entry_get_info(INTERNAL_FUNCTION_PARAM_PASSTHRU, 3); } /* }}} */ /* {{{ proto mixed ZipArchive::open(string source [, int flags]) Create new zip using source uri for output, return TRUE on success or the error code */ static ZIPARCHIVE_METHOD(open) { struct zip *intern; int err = 0; zend_long flags = 0; char *resolved_path; zend_string *filename; zval *self = getThis(); ze_zip_object *ze_obj = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|l", &filename, &flags) == FAILURE) { return; } if (self) { /* We do not use ZIP_FROM_OBJECT, zip init function here */ ze_obj = Z_ZIP_P(self); } if (ZSTR_LEN(filename) == 0) { php_error_docref(NULL, E_WARNING, "Empty string as source"); RETURN_FALSE; } if (ZIP_OPENBASEDIR_CHECKPATH(ZSTR_VAL(filename))) { RETURN_FALSE; } if (!(resolved_path = expand_filepath(ZSTR_VAL(filename), NULL))) { RETURN_FALSE; } if (ze_obj->za) { /* we already have an opened zip, free it */ if (zip_close(ze_obj->za) != 0) { php_error_docref(NULL, E_WARNING, "Empty string as source"); efree(resolved_path); RETURN_FALSE; } ze_obj->za = NULL; } if (ze_obj->filename) { efree(ze_obj->filename); ze_obj->filename = NULL; } intern = zip_open(resolved_path, flags, &err); if (!intern || err) { efree(resolved_path); RETURN_LONG((zend_long)err); } ze_obj->filename = resolved_path; ze_obj->filename_len = strlen(resolved_path); ze_obj->za = intern; RETURN_TRUE; } /* }}} */ /* {{{ proto resource ZipArchive::setPassword(string password) Set the password for the active archive */ static ZIPARCHIVE_METHOD(setPassword) { struct zip *intern; zval *self = getThis(); char *password; size_t password_len; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &password, &password_len) == FAILURE) { return; } if (password_len < 1) { RETURN_FALSE; } else { int res = zip_set_default_password(intern, (const char *)password); if (res == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } } /* }}} */ /* {{{ proto bool ZipArchive::close() close the zip archive */ static ZIPARCHIVE_METHOD(close) { struct zip *intern; zval *self = getThis(); ze_zip_object *ze_obj; int err; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); ze_obj = Z_ZIP_P(self); if ((err = zip_close(intern))) { php_error_docref(NULL, E_WARNING, "%s", zip_strerror(intern)); zip_discard(intern); } efree(ze_obj->filename); ze_obj->filename = NULL; ze_obj->filename_len = 0; ze_obj->za = NULL; if (!err) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string ZipArchive::getStatusString() * Returns the status error message, system and/or zip messages */ static ZIPARCHIVE_METHOD(getStatusString) { struct zip *intern; zval *self = getThis(); #if LIBZIP_VERSION_MAJOR < 1 int zep, syp, len; char error_string[128]; #else zip_error_t *err; #endif if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); #if LIBZIP_VERSION_MAJOR < 1 zip_error_get(intern, &zep, &syp); len = zip_error_to_str(error_string, 128, zep, syp); RETVAL_STRINGL(error_string, len); #else err = zip_get_error(intern); RETVAL_STRING(zip_error_strerror(err)); zip_error_fini(err); #endif } /* }}} */ /* {{{ proto bool ZipArchive::createEmptyDir(string dirname) Returns the index of the entry named filename in the archive */ static ZIPARCHIVE_METHOD(addEmptyDir) { struct zip *intern; zval *self = getThis(); char *dirname; size_t dirname_len; int idx; struct zip_stat sb; char *s; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &dirname, &dirname_len) == FAILURE) { return; } if (dirname_len<1) { RETURN_FALSE; } if (dirname[dirname_len-1] != '/') { s=(char *)emalloc(dirname_len+2); strcpy(s, dirname); s[dirname_len] = '/'; s[dirname_len+1] = '\0'; } else { s = dirname; } idx = zip_stat(intern, s, 0, &sb); if (idx >= 0) { RETVAL_FALSE; } else { if (zip_add_dir(intern, (const char *)s) == -1) { RETVAL_FALSE; } zip_error_clear(intern); RETVAL_TRUE; } if (s != dirname) { efree(s); } } /* }}} */ static void php_zip_add_from_pattern(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); char *path = NULL; char *remove_path = NULL; char *add_path = NULL; size_t add_path_len, remove_path_len = 0, path_len = 0; zend_long remove_all_path = 0; zend_long flags = 0; zval *options = NULL; int found; zend_string *pattern; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); /* 1 == glob, 2 == pcre */ if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|la", &pattern, &flags, &options) == FAILURE) { return; } } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|sa", &pattern, &path, &path_len, &options) == FAILURE) { return; } } if (ZSTR_LEN(pattern) == 0) { php_error_docref(NULL, E_NOTICE, "Empty string as pattern"); RETURN_FALSE; } if (options && (php_zip_parse_options(options, &remove_all_path, &remove_path, &remove_path_len, &add_path, &add_path_len) < 0)) { RETURN_FALSE; } if (remove_path && remove_path_len > 1) { size_t real_len = strlen(remove_path); if ((real_len > 1) && ((remove_path[real_len - 1] == '/') || (remove_path[real_len - 1] == '\\'))) { remove_path[real_len - 1] = '\0'; } } if (type == 1) { found = php_zip_glob(ZSTR_VAL(pattern), ZSTR_LEN(pattern), flags, return_value); } else { found = php_zip_pcre(pattern, path, path_len, return_value); } if (found > 0) { int i; zval *zval_file; for (i = 0; i < found; i++) { char *file_stripped, *entry_name; size_t entry_name_len, file_stripped_len; char entry_name_buf[MAXPATHLEN]; zend_string *basename = NULL; if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(return_value), i)) != NULL) { if (remove_all_path) { basename = php_basename(Z_STRVAL_P(zval_file), Z_STRLEN_P(zval_file), NULL, 0); file_stripped = ZSTR_VAL(basename); file_stripped_len = ZSTR_LEN(basename); } else if (remove_path && strstr(Z_STRVAL_P(zval_file), remove_path) != NULL) { file_stripped = Z_STRVAL_P(zval_file) + remove_path_len + 1; file_stripped_len = Z_STRLEN_P(zval_file) - remove_path_len - 1; } else { file_stripped = Z_STRVAL_P(zval_file); file_stripped_len = Z_STRLEN_P(zval_file); } if (add_path) { if ((add_path_len + file_stripped_len) > MAXPATHLEN) { php_error_docref(NULL, E_WARNING, "Entry name too long (max: %d, %pd given)", MAXPATHLEN - 1, (add_path_len + file_stripped_len)); zval_ptr_dtor(return_value); RETURN_FALSE; } snprintf(entry_name_buf, MAXPATHLEN, "%s%s", add_path, file_stripped); entry_name = entry_name_buf; entry_name_len = strlen(entry_name); } else { entry_name = Z_STRVAL_P(zval_file); entry_name_len = Z_STRLEN_P(zval_file); } if (basename) { zend_string_release(basename); basename = NULL; } if (php_zip_add_file(intern, Z_STRVAL_P(zval_file), Z_STRLEN_P(zval_file), entry_name, entry_name_len, 0, 0) < 0) { zval_dtor(return_value); RETURN_FALSE; } } } } } /* }}} */ /* {{{ proto bool ZipArchive::addGlob(string pattern[,int flags [, array options]]) Add files matching the glob pattern. See php's glob for the pattern syntax. */ static ZIPARCHIVE_METHOD(addGlob) { php_zip_add_from_pattern(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto bool ZipArchive::addPattern(string pattern[, string path [, array options]]) Add files matching the pcre pattern. See php's pcre for the pattern syntax. */ static ZIPARCHIVE_METHOD(addPattern) { php_zip_add_from_pattern(INTERNAL_FUNCTION_PARAM_PASSTHRU, 2); } /* }}} */ /* {{{ proto bool ZipArchive::addFile(string filepath[, string entryname[, int start [, int length]]]) Add a file in a Zip archive using its path and the name to use. */ static ZIPARCHIVE_METHOD(addFile) { struct zip *intern; zval *self = getThis(); char *entry_name = NULL; size_t entry_name_len = 0; zend_long offset_start = 0, offset_len = 0; zend_string *filename; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|sll", &filename, &entry_name, &entry_name_len, &offset_start, &offset_len) == FAILURE) { return; } if (ZSTR_LEN(filename) == 0) { php_error_docref(NULL, E_NOTICE, "Empty string as filename"); RETURN_FALSE; } if (entry_name_len == 0) { entry_name = ZSTR_VAL(filename); entry_name_len = ZSTR_LEN(filename); } if (php_zip_add_file(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), entry_name, entry_name_len, 0, 0) < 0) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool ZipArchive::addFromString(string name, string content) Add a file using content and the entry name */ static ZIPARCHIVE_METHOD(addFromString) { struct zip *intern; zval *self = getThis(); zend_string *buffer; char *name; size_t name_len; ze_zip_object *ze_obj; struct zip_source *zs; int pos = 0; int cur_idx; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "sS", &name, &name_len, &buffer) == FAILURE) { return; } ze_obj = Z_ZIP_P(self); if (ze_obj->buffers_cnt) { ze_obj->buffers = (char **)erealloc(ze_obj->buffers, sizeof(char *) * (ze_obj->buffers_cnt+1)); pos = ze_obj->buffers_cnt++; } else { ze_obj->buffers = (char **)emalloc(sizeof(char *)); ze_obj->buffers_cnt++; pos = 0; } ze_obj->buffers[pos] = (char *)emalloc(ZSTR_LEN(buffer) + 1); memcpy(ze_obj->buffers[pos], ZSTR_VAL(buffer), ZSTR_LEN(buffer) + 1); zs = zip_source_buffer(intern, ze_obj->buffers[pos], ZSTR_LEN(buffer), 0); if (zs == NULL) { RETURN_FALSE; } cur_idx = zip_name_locate(intern, (const char *)name, 0); /* TODO: fix _zip_replace */ if (cur_idx >= 0) { if (zip_delete(intern, cur_idx) == -1) { zip_source_free(zs); RETURN_FALSE; } } if (zip_add(intern, name, zs) == -1) { zip_source_free(zs); RETURN_FALSE; } else { zip_error_clear(intern); RETURN_TRUE; } } /* }}} */ /* {{{ proto array ZipArchive::statName(string filename[, int flags]) Returns the information about a the zip entry filename */ static ZIPARCHIVE_METHOD(statName) { struct zip *intern; zval *self = getThis(); zend_long flags = 0; struct zip_stat sb; zend_string *name; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|l", &name, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(name), ZSTR_LEN(name), flags, sb); RETURN_SB(&sb); } /* }}} */ /* {{{ proto resource ZipArchive::statIndex(int index[, int flags]) Returns the zip entry informations using its index */ static ZIPARCHIVE_METHOD(statIndex) { struct zip *intern; zval *self = getThis(); zend_long index, flags = 0; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l", &index, &flags) == FAILURE) { return; } if (zip_stat_index(intern, index, flags, &sb) != 0) { RETURN_FALSE; } RETURN_SB(&sb); } /* }}} */ /* {{{ proto int ZipArchive::locateName(string filename[, int flags]) Returns the index of the entry named filename in the archive */ static ZIPARCHIVE_METHOD(locateName) { struct zip *intern; zval *self = getThis(); zend_long flags = 0; zend_long idx = -1; zend_string *name; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|l", &name, &flags) == FAILURE) { return; } if (ZSTR_LEN(name) < 1) { RETURN_FALSE; } idx = (zend_long)zip_name_locate(intern, (const char *)ZSTR_VAL(name), flags); if (idx >= 0) { RETURN_LONG(idx); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string ZipArchive::getNameIndex(int index [, int flags]) Returns the name of the file at position index */ static ZIPARCHIVE_METHOD(getNameIndex) { struct zip *intern; zval *self = getThis(); const char *name; zend_long flags = 0, index = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l", &index, &flags) == FAILURE) { return; } name = zip_get_name(intern, (int) index, flags); if (name) { RETVAL_STRING((char *)name); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool ZipArchive::setArchiveComment(string comment) Set or remove (NULL/'') the comment of the archive */ static ZIPARCHIVE_METHOD(setArchiveComment) { struct zip *intern; zval *self = getThis(); size_t comment_len; char * comment; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &comment, &comment_len) == FAILURE) { return; } if (zip_set_archive_comment(intern, (const char *)comment, (int)comment_len)) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto string ZipArchive::getArchiveComment([int flags]) Returns the comment of an entry using its index */ static ZIPARCHIVE_METHOD(getArchiveComment) { struct zip *intern; zval *self = getThis(); zend_long flags = 0; const char * comment; int comment_len = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &flags) == FAILURE) { return; } comment = zip_get_archive_comment(intern, &comment_len, (int)flags); if(comment==NULL) { RETURN_FALSE; } RETURN_STRINGL((char *)comment, (zend_long)comment_len); } /* }}} */ /* {{{ proto bool ZipArchive::setCommentName(string name, string comment) Set or remove (NULL/'') the comment of an entry using its Name */ static ZIPARCHIVE_METHOD(setCommentName) { struct zip *intern; zval *self = getThis(); size_t comment_len, name_len; char * comment, *name; int idx; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &name, &name_len, &comment, &comment_len) == FAILURE) { return; } if (name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); } idx = zip_name_locate(intern, name, 0); if (idx < 0) { RETURN_FALSE; } PHP_ZIP_SET_FILE_COMMENT(intern, idx, comment, comment_len); } /* }}} */ /* {{{ proto bool ZipArchive::setCommentIndex(int index, string comment) Set or remove (NULL/'') the comment of an entry using its index */ static ZIPARCHIVE_METHOD(setCommentIndex) { struct zip *intern; zval *self = getThis(); zend_long index; size_t comment_len; char * comment; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls", &index, &comment, &comment_len) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); PHP_ZIP_SET_FILE_COMMENT(intern, index, comment, comment_len); } /* }}} */ /* those constants/functions are only available in libzip since 0.11.2 */ #ifdef ZIP_OPSYS_DEFAULT /* {{{ proto bool ZipArchive::setExternalAttributesName(string name, int opsys, int attr [, int flags]) Set external attributes for file in zip, using its name */ static ZIPARCHIVE_METHOD(setExternalAttributesName) { struct zip *intern; zval *self = getThis(); size_t name_len; char *name; zend_long flags=0, opsys, attr; zip_int64_t idx; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "sll|l", &name, &name_len, &opsys, &attr, &flags) == FAILURE) { return; } if (name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); } idx = zip_name_locate(intern, name, 0); if (idx < 0) { RETURN_FALSE; } if (zip_file_set_external_attributes(intern, idx, (zip_flags_t)flags, (zip_uint8_t)(opsys&0xff), (zip_uint32_t)attr) < 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::setExternalAttributesIndex(int index, int opsys, int attr [, int flags]) Set external attributes for file in zip, using its index */ static ZIPARCHIVE_METHOD(setExternalAttributesIndex) { struct zip *intern; zval *self = getThis(); zend_long index, flags=0, opsys, attr; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "lll|l", &index, &opsys, &attr, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); if (zip_file_set_external_attributes(intern, (zip_uint64_t)index, (zip_flags_t)flags, (zip_uint8_t)(opsys&0xff), (zip_uint32_t)attr) < 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::getExternalAttributesName(string name, int &opsys, int &attr [, int flags]) Get external attributes for file in zip, using its name */ static ZIPARCHIVE_METHOD(getExternalAttributesName) { struct zip *intern; zval *self = getThis(), *z_opsys, *z_attr; size_t name_len; char *name; zend_long flags=0; zip_uint8_t opsys; zip_uint32_t attr; zip_int64_t idx; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz/z/|l", &name, &name_len, &z_opsys, &z_attr, &flags) == FAILURE) { return; } if (name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); } idx = zip_name_locate(intern, name, 0); if (idx < 0) { RETURN_FALSE; } if (zip_file_get_external_attributes(intern, idx, (zip_flags_t)flags, &opsys, &attr) < 0) { RETURN_FALSE; } zval_ptr_dtor(z_opsys); ZVAL_LONG(z_opsys, opsys); zval_ptr_dtor(z_attr); ZVAL_LONG(z_attr, attr); RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::getExternalAttributesIndex(int index, int &opsys, int &attr [, int flags]) Get external attributes for file in zip, using its index */ static ZIPARCHIVE_METHOD(getExternalAttributesIndex) { struct zip *intern; zval *self = getThis(), *z_opsys, *z_attr; zend_long index, flags=0; zip_uint8_t opsys; zip_uint32_t attr; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz/z/|l", &index, &z_opsys, &z_attr, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); if (zip_file_get_external_attributes(intern, (zip_uint64_t)index, (zip_flags_t)flags, &opsys, &attr) < 0) { RETURN_FALSE; } zval_dtor(z_opsys); ZVAL_LONG(z_opsys, opsys); zval_dtor(z_attr); ZVAL_LONG(z_attr, attr); RETURN_TRUE; } /* }}} */ #endif /* ifdef ZIP_OPSYS_DEFAULT */ /* {{{ proto string ZipArchive::getCommentName(string name[, int flags]) Returns the comment of an entry using its name */ static ZIPARCHIVE_METHOD(getCommentName) { struct zip *intern; zval *self = getThis(); size_t name_len; int idx; zend_long flags = 0; int comment_len = 0; const char * comment; char *name; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &name, &name_len, &flags) == FAILURE) { return; } if (name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); RETURN_FALSE; } idx = zip_name_locate(intern, name, 0); if (idx < 0) { RETURN_FALSE; } comment = zip_get_file_comment(intern, idx, &comment_len, (int)flags); RETURN_STRINGL((char *)comment, (zend_long)comment_len); } /* }}} */ /* {{{ proto string ZipArchive::getCommentIndex(int index[, int flags]) Returns the comment of an entry using its index */ static ZIPARCHIVE_METHOD(getCommentIndex) { struct zip *intern; zval *self = getThis(); zend_long index, flags = 0; const char * comment; int comment_len = 0; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l", &index, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); comment = zip_get_file_comment(intern, index, &comment_len, (int)flags); RETURN_STRINGL((char *)comment, (zend_long)comment_len); } /* }}} */ /* {{{ proto bool ZipArchive::setCompressionName(string name, int comp_method[, int comp_flags]) Set the compression of a file in zip, using its name */ static ZIPARCHIVE_METHOD(setCompressionName) { struct zip *intern; zval *this = getThis(); size_t name_len; char *name; zip_int64_t idx; zend_long comp_method, comp_flags = 0; if (!this) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, this); if (zend_parse_parameters(ZEND_NUM_ARGS(), "sl|l", &name, &name_len, &comp_method, &comp_flags) == FAILURE) { return; } if (name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as entry name"); } idx = zip_name_locate(intern, name, 0); if (idx < 0) { RETURN_FALSE; } if (zip_set_file_compression(intern, (zip_uint64_t)idx, (zip_int32_t)comp_method, (zip_uint32_t)comp_flags) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::setCompressionIndex(int index, int comp_method[, int comp_flags]) Set the compression of a file in zip, using its index */ static ZIPARCHIVE_METHOD(setCompressionIndex) { struct zip *intern; zval *this = getThis(); zend_long index; zend_long comp_method, comp_flags = 0; if (!this) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, this); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ll|l", &index, &comp_method, &comp_flags) == FAILURE) { return; } if (zip_set_file_compression(intern, (zip_uint64_t)index, (zip_int32_t)comp_method, (zip_uint32_t)comp_flags) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::deleteIndex(int index) Delete a file using its index */ static ZIPARCHIVE_METHOD(deleteIndex) { struct zip *intern; zval *self = getThis(); zend_long index; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &index) == FAILURE) { return; } if (index < 0) { RETURN_FALSE; } if (zip_delete(intern, index) < 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::deleteName(string name) Delete a file using its index */ static ZIPARCHIVE_METHOD(deleteName) { struct zip *intern; zval *self = getThis(); size_t name_len; char *name; struct zip_stat sb; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &name_len) == FAILURE) { return; } if (name_len < 1) { RETURN_FALSE; } PHP_ZIP_STAT_PATH(intern, name, name_len, 0, sb); if (zip_delete(intern, sb.index)) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::renameIndex(int index, string new_name) Rename an entry selected by its index to new_name */ static ZIPARCHIVE_METHOD(renameIndex) { struct zip *intern; zval *self = getThis(); char *new_name; size_t new_name_len; zend_long index; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ls", &index, &new_name, &new_name_len) == FAILURE) { return; } if (index < 0) { RETURN_FALSE; } if (new_name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as new entry name"); RETURN_FALSE; } if (zip_rename(intern, index, (const char *)new_name) != 0) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::renameName(string name, string new_name) Rename an entry selected by its name to new_name */ static ZIPARCHIVE_METHOD(renameName) { struct zip *intern; zval *self = getThis(); struct zip_stat sb; char *name, *new_name; size_t name_len, new_name_len; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &name, &name_len, &new_name, &new_name_len) == FAILURE) { return; } if (new_name_len < 1) { php_error_docref(NULL, E_NOTICE, "Empty string as new entry name"); RETURN_FALSE; } PHP_ZIP_STAT_PATH(intern, name, name_len, 0, sb); if (zip_rename(intern, sb.index, (const char *)new_name)) { RETURN_FALSE; } RETURN_TRUE; } /* }}} */ /* {{{ proto bool ZipArchive::unchangeIndex(int index) Changes to the file at position index are reverted */ static ZIPARCHIVE_METHOD(unchangeIndex) { struct zip *intern; zval *self = getThis(); zend_long index; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &index) == FAILURE) { return; } if (index < 0) { RETURN_FALSE; } if (zip_unchange(intern, index) != 0) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool ZipArchive::unchangeName(string name) Changes to the file named 'name' are reverted */ static ZIPARCHIVE_METHOD(unchangeName) { struct zip *intern; zval *self = getThis(); struct zip_stat sb; char *name; size_t name_len; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &name, &name_len) == FAILURE) { return; } if (name_len < 1) { RETURN_FALSE; } PHP_ZIP_STAT_PATH(intern, name, name_len, 0, sb); if (zip_unchange(intern, sb.index) != 0) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool ZipArchive::unchangeAll() All changes to files and global information in archive are reverted */ static ZIPARCHIVE_METHOD(unchangeAll) { struct zip *intern; zval *self = getThis(); if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zip_unchange_all(intern) != 0) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool ZipArchive::unchangeArchive() Revert all global changes to the archive archive. For now, this only reverts archive comment changes. */ static ZIPARCHIVE_METHOD(unchangeArchive) { struct zip *intern; zval *self = getThis(); if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zip_unchange_archive(intern) != 0) { RETURN_FALSE; } else { RETURN_TRUE; } } /* }}} */ /* {{{ proto bool ZipArchive::extractTo(string pathto[, mixed files]) Extract one or more file from a zip archive */ /* TODO: * - allow index or array of indeces * - replace path * - patterns */ static ZIPARCHIVE_METHOD(extractTo) { struct zip *intern; zval *self = getThis(); zval *zval_files = NULL; zval *zval_file = NULL; php_stream_statbuf ssb; char *pathto; size_t pathto_len; int ret, i; int nelems; if (!self) { RETURN_FALSE; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|z", &pathto, &pathto_len, &zval_files) == FAILURE) { return; } if (pathto_len < 1) { RETURN_FALSE; } if (php_stream_stat_path_ex(pathto, PHP_STREAM_URL_STAT_QUIET, &ssb, NULL) < 0) { ret = php_stream_mkdir(pathto, 0777, PHP_STREAM_MKDIR_RECURSIVE, NULL); if (!ret) { RETURN_FALSE; } } ZIP_FROM_OBJECT(intern, self); if (zval_files && (Z_TYPE_P(zval_files) != IS_NULL)) { switch (Z_TYPE_P(zval_files)) { case IS_STRING: if (!php_zip_extract_file(intern, pathto, Z_STRVAL_P(zval_files), Z_STRLEN_P(zval_files))) { RETURN_FALSE; } break; case IS_ARRAY: nelems = zend_hash_num_elements(Z_ARRVAL_P(zval_files)); if (nelems == 0 ) { RETURN_FALSE; } for (i = 0; i < nelems; i++) { if ((zval_file = zend_hash_index_find(Z_ARRVAL_P(zval_files), i)) != NULL) { switch (Z_TYPE_P(zval_file)) { case IS_LONG: break; case IS_STRING: if (!php_zip_extract_file(intern, pathto, Z_STRVAL_P(zval_file), Z_STRLEN_P(zval_file))) { RETURN_FALSE; } break; } } } break; case IS_LONG: default: php_error_docref(NULL, E_WARNING, "Invalid argument, expect string or array of strings"); break; } } else { /* Extract all files */ int filecount = zip_get_num_files(intern); if (filecount == -1) { php_error_docref(NULL, E_WARNING, "Illegal archive"); RETURN_FALSE; } for (i = 0; i < filecount; i++) { char *file = (char*)zip_get_name(intern, i, ZIP_FL_UNCHANGED); if (!file || !php_zip_extract_file(intern, pathto, file, strlen(file))) { RETURN_FALSE; } } } RETURN_TRUE; } /* }}} */ static void php_zip_get_from(INTERNAL_FUNCTION_PARAMETERS, int type) /* {{{ */ { struct zip *intern; zval *self = getThis(); struct zip_stat sb; struct zip_file *zf; zend_long index = -1; zend_long flags = 0; zend_long len = 0; zend_string *filename; zend_string *buffer; int n = 0; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (type == 1) { if (zend_parse_parameters(ZEND_NUM_ARGS(), "P|ll", &filename, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_PATH(intern, ZSTR_VAL(filename), ZSTR_LEN(filename), flags, sb); } else { if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|ll", &index, &len, &flags) == FAILURE) { return; } PHP_ZIP_STAT_INDEX(intern, index, 0, sb); } if (sb.size < 1) { RETURN_EMPTY_STRING(); } if (len < 1) { len = sb.size; } if (index >= 0) { zf = zip_fopen_index(intern, index, flags); } else { zf = zip_fopen(intern, ZSTR_VAL(filename), flags); } if (zf == NULL) { RETURN_FALSE; } buffer = zend_string_alloc(len, 0); n = zip_fread(zf, ZSTR_VAL(buffer), ZSTR_LEN(buffer)); if (n < 1) { zend_string_free(buffer); RETURN_EMPTY_STRING(); } zip_fclose(zf); ZSTR_VAL(buffer)[n] = '\0'; ZSTR_LEN(buffer) = n; RETURN_NEW_STR(buffer); } /* }}} */ /* {{{ proto string ZipArchive::getFromName(string entryname[, int len [, int flags]]) get the contents of an entry using its name */ static ZIPARCHIVE_METHOD(getFromName) { php_zip_get_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, 1); } /* }}} */ /* {{{ proto string ZipArchive::getFromIndex(int index[, int len [, int flags]]) get the contents of an entry using its index */ static ZIPARCHIVE_METHOD(getFromIndex) { php_zip_get_from(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto resource ZipArchive::getStream(string entryname) get a stream for an entry using its name */ static ZIPARCHIVE_METHOD(getStream) { struct zip *intern; zval *self = getThis(); struct zip_stat sb; char *mode = "rb"; zend_string *filename; php_stream *stream; ze_zip_object *obj; if (!self) { RETURN_FALSE; } ZIP_FROM_OBJECT(intern, self); if (zend_parse_parameters(ZEND_NUM_ARGS(), "P", &filename) == FAILURE) { return; } if (zip_stat(intern, ZSTR_VAL(filename), 0, &sb) != 0) { RETURN_FALSE; } obj = Z_ZIP_P(self); stream = php_stream_zip_open(obj->filename, ZSTR_VAL(filename), mode STREAMS_CC); if (stream) { php_stream_to_zval(stream, return_value); } else { RETURN_FALSE; } } /* }}} */ /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_open, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setpassword, 0, 0, 1) ZEND_ARG_INFO(0, password) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_ziparchive__void, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_addemptydir, 0, 0, 1) ZEND_ARG_INFO(0, dirname) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_addglob, 0, 0, 1) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, flags) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_addpattern, 0, 0, 1) ZEND_ARG_INFO(0, pattern) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, options) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_addfile, 0, 0, 1) ZEND_ARG_INFO(0, filepath) ZEND_ARG_INFO(0, entryname) ZEND_ARG_INFO(0, start) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_addfromstring, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, content) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_statname, 0, 0, 1) ZEND_ARG_INFO(0, filename) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_statindex, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setarchivecomment, 0, 0, 1) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setcommentindex, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getcommentname, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getcommentindex, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_renameindex, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, new_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_renamename, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, new_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_unchangeindex, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_unchangename, 0, 0, 1) ZEND_ARG_INFO(0, name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_extractto, 0, 0, 1) ZEND_ARG_INFO(0, pathto) ZEND_ARG_INFO(0, files) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getfromname, 0, 0, 1) ZEND_ARG_INFO(0, entryname) ZEND_ARG_INFO(0, len) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getfromindex, 0, 0, 1) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, len) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getarchivecomment, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setcommentname, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, comment) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getstream, 0, 0, 1) ZEND_ARG_INFO(0, entryname) ZEND_END_ARG_INFO() #ifdef ZIP_OPSYS_DEFAULT ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setextattrname, 0, 0, 3) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, opsys) ZEND_ARG_INFO(0, attr) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setextattrindex, 0, 0, 3) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, opsys) ZEND_ARG_INFO(0, attr) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getextattrname, 0, 0, 3) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(1, opsys) ZEND_ARG_INFO(1, attr) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_getextattrindex, 0, 0, 3) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(1, opsys) ZEND_ARG_INFO(1, attr) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() #endif /* ifdef ZIP_OPSYS_DEFAULT */ /* }}} */ ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setcompname, 0, 0, 2) ZEND_ARG_INFO(0, name) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, compflags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_ziparchive_setcompindex, 0, 0, 2) ZEND_ARG_INFO(0, index) ZEND_ARG_INFO(0, method) ZEND_ARG_INFO(0, compflags) ZEND_END_ARG_INFO() /* {{{ ze_zip_object_class_functions */ static const zend_function_entry zip_class_functions[] = { ZIPARCHIVE_ME(open, arginfo_ziparchive_open, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setPassword, arginfo_ziparchive_setpassword, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(close, arginfo_ziparchive__void, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getStatusString, arginfo_ziparchive__void, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(addEmptyDir, arginfo_ziparchive_addemptydir, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(addFromString, arginfo_ziparchive_addfromstring, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(addFile, arginfo_ziparchive_addfile, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(addGlob, arginfo_ziparchive_addglob, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(addPattern, arginfo_ziparchive_addpattern, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(renameIndex, arginfo_ziparchive_renameindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(renameName, arginfo_ziparchive_renamename, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setArchiveComment, arginfo_ziparchive_setarchivecomment, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getArchiveComment, arginfo_ziparchive_getarchivecomment, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setCommentIndex, arginfo_ziparchive_setcommentindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setCommentName, arginfo_ziparchive_setcommentname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getCommentIndex, arginfo_ziparchive_getcommentindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getCommentName, arginfo_ziparchive_getcommentname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(deleteIndex, arginfo_ziparchive_unchangeindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(deleteName, arginfo_ziparchive_unchangename, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(statName, arginfo_ziparchive_statname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(statIndex, arginfo_ziparchive_statindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(locateName, arginfo_ziparchive_statname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getNameIndex, arginfo_ziparchive_statindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(unchangeArchive, arginfo_ziparchive__void, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(unchangeAll, arginfo_ziparchive__void, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(unchangeIndex, arginfo_ziparchive_unchangeindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(unchangeName, arginfo_ziparchive_unchangename, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(extractTo, arginfo_ziparchive_extractto, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getFromName, arginfo_ziparchive_getfromname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getFromIndex, arginfo_ziparchive_getfromindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getStream, arginfo_ziparchive_getstream, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setExternalAttributesName, arginfo_ziparchive_setextattrname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setExternalAttributesIndex, arginfo_ziparchive_setextattrindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getExternalAttributesName, arginfo_ziparchive_getextattrname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(getExternalAttributesIndex, arginfo_ziparchive_getextattrindex, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setCompressionName, arginfo_ziparchive_setcompname, ZEND_ACC_PUBLIC) ZIPARCHIVE_ME(setCompressionIndex, arginfo_ziparchive_setcompindex, ZEND_ACC_PUBLIC) {NULL, NULL, NULL} }; /* }}} */ static void php_zip_free_prop_handler(zval *el) /* {{{ */ { pefree(Z_PTR_P(el), 1); } /* }}} */ /* {{{ PHP_MINIT_FUNCTION */ static PHP_MINIT_FUNCTION(zip) { zend_class_entry ce; memcpy(&zip_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); zip_object_handlers.offset = XtOffsetOf(ze_zip_object, zo); zip_object_handlers.free_obj = php_zip_object_free_storage; zip_object_handlers.clone_obj = NULL; zip_object_handlers.get_property_ptr_ptr = php_zip_get_property_ptr_ptr; zip_object_handlers.get_properties = php_zip_get_properties; zip_object_handlers.read_property = php_zip_read_property; zip_object_handlers.has_property = php_zip_has_property; INIT_CLASS_ENTRY(ce, "ZipArchive", zip_class_functions); ce.create_object = php_zip_object_new; zip_class_entry = zend_register_internal_class(&ce); zend_hash_init(&zip_prop_handlers, 0, NULL, php_zip_free_prop_handler, 1); php_zip_register_prop_handler(&zip_prop_handlers, "status", php_zip_status, NULL, NULL, IS_LONG); php_zip_register_prop_handler(&zip_prop_handlers, "statusSys", php_zip_status_sys, NULL, NULL, IS_LONG); php_zip_register_prop_handler(&zip_prop_handlers, "numFiles", php_zip_get_num_files, NULL, NULL, IS_LONG); php_zip_register_prop_handler(&zip_prop_handlers, "filename", NULL, NULL, php_zipobj_get_filename, IS_STRING); php_zip_register_prop_handler(&zip_prop_handlers, "comment", NULL, php_zipobj_get_zip_comment, NULL, IS_STRING); REGISTER_ZIP_CLASS_CONST_LONG("CREATE", ZIP_CREATE); REGISTER_ZIP_CLASS_CONST_LONG("EXCL", ZIP_EXCL); REGISTER_ZIP_CLASS_CONST_LONG("CHECKCONS", ZIP_CHECKCONS); REGISTER_ZIP_CLASS_CONST_LONG("OVERWRITE", ZIP_OVERWRITE); REGISTER_ZIP_CLASS_CONST_LONG("FL_NOCASE", ZIP_FL_NOCASE); REGISTER_ZIP_CLASS_CONST_LONG("FL_NODIR", ZIP_FL_NODIR); REGISTER_ZIP_CLASS_CONST_LONG("FL_COMPRESSED", ZIP_FL_COMPRESSED); REGISTER_ZIP_CLASS_CONST_LONG("FL_UNCHANGED", ZIP_FL_UNCHANGED); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFAULT", ZIP_CM_DEFAULT); REGISTER_ZIP_CLASS_CONST_LONG("CM_STORE", ZIP_CM_STORE); REGISTER_ZIP_CLASS_CONST_LONG("CM_SHRINK", ZIP_CM_SHRINK); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_1", ZIP_CM_REDUCE_1); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_2", ZIP_CM_REDUCE_2); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_3", ZIP_CM_REDUCE_3); REGISTER_ZIP_CLASS_CONST_LONG("CM_REDUCE_4", ZIP_CM_REDUCE_4); REGISTER_ZIP_CLASS_CONST_LONG("CM_IMPLODE", ZIP_CM_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE", ZIP_CM_DEFLATE); REGISTER_ZIP_CLASS_CONST_LONG("CM_DEFLATE64", ZIP_CM_DEFLATE64); REGISTER_ZIP_CLASS_CONST_LONG("CM_PKWARE_IMPLODE", ZIP_CM_PKWARE_IMPLODE); REGISTER_ZIP_CLASS_CONST_LONG("CM_BZIP2", ZIP_CM_BZIP2); REGISTER_ZIP_CLASS_CONST_LONG("CM_LZMA", ZIP_CM_LZMA); REGISTER_ZIP_CLASS_CONST_LONG("CM_TERSE", ZIP_CM_TERSE); REGISTER_ZIP_CLASS_CONST_LONG("CM_LZ77", ZIP_CM_LZ77); REGISTER_ZIP_CLASS_CONST_LONG("CM_WAVPACK", ZIP_CM_WAVPACK); REGISTER_ZIP_CLASS_CONST_LONG("CM_PPMD", ZIP_CM_PPMD); /* Error code */ REGISTER_ZIP_CLASS_CONST_LONG("ER_OK", ZIP_ER_OK); /* N No error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_MULTIDISK", ZIP_ER_MULTIDISK); /* N Multi-disk zip archives not supported */ REGISTER_ZIP_CLASS_CONST_LONG("ER_RENAME", ZIP_ER_RENAME); /* S Renaming temporary file failed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CLOSE", ZIP_ER_CLOSE); /* S Closing zip archive failed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_SEEK", ZIP_ER_SEEK); /* S Seek error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_READ", ZIP_ER_READ); /* S Read error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_WRITE", ZIP_ER_WRITE); /* S Write error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CRC", ZIP_ER_CRC); /* N CRC error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_ZIPCLOSED", ZIP_ER_ZIPCLOSED); /* N Containing zip archive was closed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_NOENT", ZIP_ER_NOENT); /* N No such file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_EXISTS", ZIP_ER_EXISTS); /* N File already exists */ REGISTER_ZIP_CLASS_CONST_LONG("ER_OPEN", ZIP_ER_OPEN); /* S Can't open file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_TMPOPEN", ZIP_ER_TMPOPEN); /* S Failure to create temporary file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_ZLIB", ZIP_ER_ZLIB); /* Z Zlib error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_MEMORY", ZIP_ER_MEMORY); /* N Malloc failure */ REGISTER_ZIP_CLASS_CONST_LONG("ER_CHANGED", ZIP_ER_CHANGED); /* N Entry has been changed */ REGISTER_ZIP_CLASS_CONST_LONG("ER_COMPNOTSUPP", ZIP_ER_COMPNOTSUPP);/* N Compression method not supported */ REGISTER_ZIP_CLASS_CONST_LONG("ER_EOF", ZIP_ER_EOF); /* N Premature EOF */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INVAL", ZIP_ER_INVAL); /* N Invalid argument */ REGISTER_ZIP_CLASS_CONST_LONG("ER_NOZIP", ZIP_ER_NOZIP); /* N Not a zip archive */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INTERNAL", ZIP_ER_INTERNAL); /* N Internal error */ REGISTER_ZIP_CLASS_CONST_LONG("ER_INCONS", ZIP_ER_INCONS); /* N Zip archive inconsistent */ REGISTER_ZIP_CLASS_CONST_LONG("ER_REMOVE", ZIP_ER_REMOVE); /* S Can't remove file */ REGISTER_ZIP_CLASS_CONST_LONG("ER_DELETED", ZIP_ER_DELETED); /* N Entry has been deleted */ #ifdef ZIP_OPSYS_DEFAULT REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_DOS", ZIP_OPSYS_DOS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_AMIGA", ZIP_OPSYS_AMIGA); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_OPENVMS", ZIP_OPSYS_OPENVMS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_UNIX", ZIP_OPSYS_UNIX); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_VM_CMS", ZIP_OPSYS_VM_CMS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_ATARI_ST", ZIP_OPSYS_ATARI_ST); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_OS_2", ZIP_OPSYS_OS_2); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_MACINTOSH", ZIP_OPSYS_MACINTOSH); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_Z_SYSTEM", ZIP_OPSYS_Z_SYSTEM); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_Z_CPM", ZIP_OPSYS_CPM); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_WINDOWS_NTFS", ZIP_OPSYS_WINDOWS_NTFS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_MVS", ZIP_OPSYS_MVS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_VSE", ZIP_OPSYS_VSE); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_ACORN_RISC", ZIP_OPSYS_ACORN_RISC); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_VFAT", ZIP_OPSYS_VFAT); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_ALTERNATE_MVS", ZIP_OPSYS_ALTERNATE_MVS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_BEOS", ZIP_OPSYS_BEOS); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_TANDEM", ZIP_OPSYS_TANDEM); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_OS_400", ZIP_OPSYS_OS_400); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_OS_X", ZIP_OPSYS_OS_X); REGISTER_ZIP_CLASS_CONST_LONG("OPSYS_DEFAULT", ZIP_OPSYS_DEFAULT); #endif /* ifdef ZIP_OPSYS_DEFAULT */ php_register_url_stream_wrapper("zip", &php_stream_zip_wrapper); le_zip_dir = zend_register_list_destructors_ex(php_zip_free_dir, NULL, le_zip_dir_name, module_number); le_zip_entry = zend_register_list_destructors_ex(php_zip_free_entry, NULL, le_zip_entry_name, module_number); return SUCCESS; } /* }}} */ /* {{{ PHP_MSHUTDOWN_FUNCTION */ static PHP_MSHUTDOWN_FUNCTION(zip) { zend_hash_destroy(&zip_prop_handlers); php_unregister_url_stream_wrapper("zip"); return SUCCESS; } /* }}} */ /* {{{ PHP_MINFO_FUNCTION */ static PHP_MINFO_FUNCTION(zip) { php_info_print_table_start(); php_info_print_table_row(2, "Zip", "enabled"); php_info_print_table_row(2, "Zip version", PHP_ZIP_VERSION); php_info_print_table_row(2, "Libzip version", LIBZIP_VERSION); php_info_print_table_end(); } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-190/c/bad_4988_0
crossvul-cpp_data_bad_155_1
/* * This file is part of Espruino, a JavaScript interpreter for Microcontrollers * * Copyright (C) 2013 Gordon Williams <gw@pur3.co.uk> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * ---------------------------------------------------------------------------- * Misc utils and cheapskate stdlib implementation * ---------------------------------------------------------------------------- */ #include "jsutils.h" #include "jslex.h" #include "jshardware.h" #include "jsinteractive.h" #include "jswrapper.h" #include "jswrap_error.h" #include "jswrap_json.h" /** Error flags for things that we don't really want to report on the console, * but which are good to know about */ volatile JsErrorFlags jsErrorFlags; bool isWhitespace(char ch) { return (ch==0x09) || // \t - tab (ch==0x0B) || // vertical tab (ch==0x0C) || // form feed (ch==0x20) || // space (ch=='\n') || (ch=='\r'); } bool isNumeric(char ch) { return (ch>='0') && (ch<='9'); } bool isHexadecimal(char ch) { return ((ch>='0') && (ch<='9')) || ((ch>='a') && (ch<='f')) || ((ch>='A') && (ch<='F')); } bool isAlpha(char ch) { return ((ch>='a') && (ch<='z')) || ((ch>='A') && (ch<='Z')) || ch=='_'; } bool isIDString(const char *s) { if (!isAlpha(*s)) return false; while (*s) { if (!(isAlpha(*s) || isNumeric(*s))) return false; s++; } return true; } /** escape a character - if it is required. This may return a reference to a static array, so you can't store the value it returns in a variable and call it again. */ const char *escapeCharacter(char ch) { if (ch=='\b') return "\\b"; if (ch=='\f') return "\\f"; if (ch=='\n') return "\\n"; if (ch=='\a') return "\\a"; if (ch=='\r') return "\\r"; if (ch=='\t') return "\\t"; if (ch=='\\') return "\\\\"; if (ch=='"') return "\\\""; static char buf[5]; if (ch<32 || ch>=127) { /** just encode as hex - it's more understandable * and doesn't have the issue of "\16"+"1" != "\161" */ buf[0]='\\'; buf[1]='x'; int n = (ch>>4)&15; buf[2] = (char)((n<10)?('0'+n):('A'+n-10)); n=ch&15; buf[3] = (char)((n<10)?('0'+n):('A'+n-10)); buf[4] = 0; return buf; } buf[1] = 0; buf[0] = ch; return buf; } /** Parse radix prefixes, or return 0 */ NO_INLINE int getRadix(const char **s, int forceRadix, bool *hasError) { int radix = 10; if (forceRadix > 36) { if (hasError) *hasError = true; return 0; } if (**s == '0') { radix = 8; (*s)++; // OctalIntegerLiteral: 0o01, 0O01 if (**s == 'o' || **s == 'O') { radix = 8; if (forceRadix && forceRadix!=8 && forceRadix<25) return 0; (*s)++; // HexIntegerLiteral: 0x01, 0X01 } else if (**s == 'x' || **s == 'X') { radix = 16; if (forceRadix && forceRadix!=16 && forceRadix<34) return 0; (*s)++; // BinaryIntegerLiteral: 0b01, 0B01 } else if (**s == 'b' || **s == 'B') { radix = 2; if (forceRadix && forceRadix!=2 && forceRadix<12) return 0; else (*s)++; } else if (!forceRadix) { // check for '.' or digits 8 or 9 - if so it's decimal const char *p; for (p=*s;*p;p++) if (*p=='.' || *p=='8' || *p=='9') radix = 10; else if (*p<'0' || *p>'9') break; } } if (forceRadix>0 && forceRadix<=36) radix = forceRadix; return radix; } // Convert a character to the hexadecimal equivalent (or -1) int chtod(char ch) { if (ch >= '0' && ch <= '9') return ch - '0'; else if (ch >= 'a' && ch <= 'z') return 10 + ch - 'a'; else if (ch >= 'A' && ch <= 'Z') return 10 + ch - 'A'; else return -1; } /* convert a number in the given radix to an int */ long long stringToIntWithRadix(const char *s, int forceRadix, //!< if radix=0, autodetect bool *hasError, //!< If nonzero, set to whether there was an error or not const char **endOfInteger //!< If nonzero, this is set to the point at which the integer finished in the string ) { // skip whitespace (strange parseInt behaviour) while (isWhitespace(*s)) s++; bool isNegated = false; long long v = 0; if (*s == '-') { isNegated = true; s++; } else if (*s == '+') { s++; } const char *numberStart = s; if (endOfInteger) (*endOfInteger)=s; int radix = getRadix(&s, forceRadix, hasError); if (!radix) return 0; while (*s) { int digit = chtod(*s); if (digit<0 || digit>=radix) break; v = v*radix + digit; s++; } if (hasError) *hasError = s==numberStart; // we had an error if we didn't manage to parse any chars at all if (endOfInteger) (*endOfInteger)=s; if (isNegated) return -v; return v; } /** * Convert hex, binary, octal or decimal string into an int. */ long long stringToInt(const char *s) { return stringToIntWithRadix(s,0,NULL,NULL); } #ifndef USE_FLASH_MEMORY // JsError, jsWarn, jsExceptionHere implementations that expect the format string to be in normal // RAM where is can be accessed normally. NO_INLINE void jsError(const char *fmt, ...) { jsiConsoleRemoveInputLine(); jsiConsolePrint("ERROR: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, fmt, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsWarn(const char *fmt, ...) { jsiConsoleRemoveInputLine(); jsiConsolePrint("WARNING: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, fmt, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsExceptionHere(JsExceptionType type, const char *fmt, ...) { // If we already had an exception, forget this if (jspHasError()) return; jsiConsoleRemoveInputLine(); JsVar *var = jsvNewFromEmptyString(); if (!var) { jspSetError(false); return; // out of memory } JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); vcbprintf_callback cb = (vcbprintf_callback)jsvStringIteratorPrintfCallback; va_list argp; va_start(argp, fmt); vcbprintf(cb,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); if (type != JSET_STRING) { JsVar *obj = 0; if (type == JSET_ERROR) obj = jswrap_error_constructor(var); else if (type == JSET_SYNTAXERROR) obj = jswrap_syntaxerror_constructor(var); else if (type == JSET_TYPEERROR) obj = jswrap_typeerror_constructor(var); else if (type == JSET_INTERNALERROR) obj = jswrap_internalerror_constructor(var); else if (type == JSET_REFERENCEERROR) obj = jswrap_referenceerror_constructor(var); jsvUnLock(var); var = obj; } jspSetException(var); jsvUnLock(var); } #else // JsError, jsWarn, jsExceptionHere implementations that expect the format string to be in FLASH // and first copy it into RAM in order to prevent issues with byte access, this is necessary on // platforms, like the esp8266, where data flash can only be accessed using word-aligned reads. NO_INLINE void jsError_flash(const char *fmt, ...) { size_t len = flash_strlen(fmt); char buff[len+1]; flash_strncpy(buff, fmt, len+1); jsiConsoleRemoveInputLine(); jsiConsolePrint("ERROR: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, buff, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsWarn_flash(const char *fmt, ...) { size_t len = flash_strlen(fmt); char buff[len+1]; flash_strncpy(buff, fmt, len+1); jsiConsoleRemoveInputLine(); jsiConsolePrint("WARNING: "); va_list argp; va_start(argp, fmt); vcbprintf((vcbprintf_callback)jsiConsolePrintString,0, buff, argp); va_end(argp); jsiConsolePrint("\n"); } NO_INLINE void jsExceptionHere_flash(JsExceptionType type, const char *ffmt, ...) { size_t len = flash_strlen(ffmt); char fmt[len+1]; flash_strncpy(fmt, ffmt, len+1); // If we already had an exception, forget this if (jspHasError()) return; jsiConsoleRemoveInputLine(); JsVar *var = jsvNewFromEmptyString(); if (!var) { jspSetError(false); return; // out of memory } JsvStringIterator it; jsvStringIteratorNew(&it, var, 0); jsvStringIteratorGotoEnd(&it); vcbprintf_callback cb = (vcbprintf_callback)jsvStringIteratorPrintfCallback; va_list argp; va_start(argp, ffmt); vcbprintf(cb,&it, fmt, argp); va_end(argp); jsvStringIteratorFree(&it); if (type != JSET_STRING) { JsVar *obj = 0; if (type == JSET_ERROR) obj = jswrap_error_constructor(var); else if (type == JSET_SYNTAXERROR) obj = jswrap_syntaxerror_constructor(var); else if (type == JSET_TYPEERROR) obj = jswrap_typeerror_constructor(var); else if (type == JSET_INTERNALERROR) obj = jswrap_internalerror_constructor(var); else if (type == JSET_REFERENCEERROR) obj = jswrap_referenceerror_constructor(var); jsvUnLock(var); var = obj; } jspSetException(var); jsvUnLock(var); } #endif NO_INLINE void jsAssertFail(const char *file, int line, const char *expr) { static bool inAssertFail = false; bool wasInAssertFail = inAssertFail; inAssertFail = true; jsiConsoleRemoveInputLine(); if (expr) { #ifndef USE_FLASH_MEMORY jsiConsolePrintf("ASSERT(%s) FAILED AT ", expr); #else jsiConsolePrintString("ASSERT("); // string is in flash and requires word access, thus copy it onto the stack size_t len = flash_strlen(expr); char buff[len+1]; flash_strncpy(buff, expr, len+1); jsiConsolePrintString(buff); jsiConsolePrintString(") FAILED AT "); #endif } else { jsiConsolePrint("ASSERT FAILED AT "); } jsiConsolePrintf("%s:%d\n",file,line); if (!wasInAssertFail) { jsvTrace(jsvFindOrCreateRoot(), 2); } #if defined(ARM) jsiConsolePrint("REBOOTING.\n"); jshTransmitFlush(); NVIC_SystemReset(); #elif defined(ESP8266) // typically the Espruino console is over telnet, in which case nothing we do here will ever // show up, so we instead jump through some hoops to print to UART int os_printf_plus(const char *format, ...) __attribute__((format(printf, 1, 2))); os_printf_plus("ASSERT FAILED AT %s:%d\n", file,line); jsiConsolePrint("---console end---\n"); int c, console = jsiGetConsoleDevice(); while ((c=jshGetCharToTransmit(console)) >= 0) os_printf_plus("%c", c); os_printf_plus("CRASHING.\n"); *(int*)0xdead = 0xbeef; extern void jswrap_ESP8266_reboot(void); jswrap_ESP8266_reboot(); while(1) ; #elif defined(LINUX) jsiConsolePrint("EXITING.\n"); exit(1); #else jsiConsolePrint("HALTING.\n"); while (1); #endif inAssertFail = false; } #ifdef USE_FLASH_MEMORY // Helpers to deal with constant strings stored in flash that have to be accessed using word-aligned // and word-sized reads // Get the length of a string in flash size_t flash_strlen(const char *str) { size_t len = 0; uint32_t *s = (uint32_t *)str; while (1) { uint32_t w = *s++; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; w >>= 8; if ((w & 0xff) == 0) break; len++; } return len; } // Copy a string from flash char *flash_strncpy(char *dst, const char *src, size_t c) { char *d = dst; uint32_t *s = (uint32_t *)src; size_t slen = flash_strlen(src); size_t len = slen > c ? c : slen; // copy full words from source string while (len >= 4) { uint32_t w = *s++; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; len -= 4; } // copy any remaining bytes if (len > 0) { uint32_t w = *s++; while (len-- > 0) { *d++ = w & 0xff; w >>= 8; } } // terminating null if (slen < c) *d = 0; return dst; } // Compare a string in memory with a string in flash int flash_strcmp(const char *mem, const char *flash) { while (1) { char m = *mem++; char c = READ_FLASH_UINT8(flash++); if (m == 0) return c != 0 ? -1 : 0; if (c == 0) return 1; if (c > m) return -1; if (m > c) return 1; } } // memcopy a string from flash unsigned char *flash_memcpy(unsigned char *dst, const unsigned char *src, size_t c) { unsigned char *d = dst; uint32_t *s = (uint32_t *)src; size_t len = c; // copy full words from source string while (len >= 4) { uint32_t w = *s++; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; w >>= 8; *d++ = w & 0xff; len -= 4; } // copy any remaining bytes if (len > 0) { uint32_t w = *s++; while (len-- > 0) { *d++ = w & 0xff; w >>= 8; } } return dst; } #endif /** Convert a string to a JS float variable where the string is of a specific radix. */ JsVarFloat stringToFloatWithRadix( const char *s, //!< The string to be converted to a float int forceRadix, //!< The radix of the string data, or 0 to guess const char **endOfFloat //!< If nonzero, this is set to the point at which the float finished in the string ) { // skip whitespace (strange parseFloat behaviour) while (isWhitespace(*s)) s++; bool isNegated = false; if (*s == '-') { isNegated = true; s++; } else if (*s == '+') { s++; } const char *numberStart = s; if (endOfFloat) (*endOfFloat)=s; int radix = getRadix(&s, forceRadix, 0); if (!radix) return NAN; JsVarFloat v = 0; JsVarFloat mul = 0.1; // handle integer part while (*s) { int digit = chtod(*s); if (digit<0 || digit>=radix) break; v = (v*radix) + digit; s++; } if (radix == 10) { // handle decimal point if (*s == '.') { s++; // skip . while (*s) { if (*s >= '0' && *s <= '9') v += mul*(*s - '0'); else break; mul /= 10; s++; } } // handle exponentials if (*s == 'e' || *s == 'E') { s++; // skip E bool isENegated = false; if (*s == '-' || *s == '+') { isENegated = *s=='-'; s++; } int e = 0; while (*s) { if (*s >= '0' && *s <= '9') e = (e*10) + (*s - '0'); else break; s++; } if (isENegated) e=-e; // TODO: faster INTEGER pow? Normal pow has floating point inaccuracies while (e>0) { v*=10; e--; } while (e<0) { v/=10; e++; } } } if (endOfFloat) (*endOfFloat)=s; // check that we managed to parse something at least if (numberStart==s || (numberStart[0]=='.' && numberStart[1]==0)) return NAN; if (isNegated) return -v; return v; } /** convert a string to a floating point JS variable. */ JsVarFloat stringToFloat(const char *s) { return stringToFloatWithRadix(s, 0, NULL); // don't force the radix to anything in particular } char itoch(int val) { if (val<10) return (char)('0'+val); return (char)('a'+val-10); } void itostr_extra(JsVarInt vals,char *str,bool signedVal, unsigned int base) { JsVarIntUnsigned val; // handle negative numbers if (signedVal && vals<0) { *(str++)='-'; val = (JsVarIntUnsigned)(-vals); } else { val = (JsVarIntUnsigned)vals; } // work out how many digits JsVarIntUnsigned tmp = val; int digits = 1; while (tmp>=base) { digits++; tmp /= base; } // for each digit... int i; for (i=digits-1;i>=0;i--) { str[i] = itoch((int)(val % base)); val /= base; } str[digits] = 0; } void ftoa_bounded_extra(JsVarFloat val,char *str, size_t len, int radix, int fractionalDigits) { const JsVarFloat stopAtError = 0.0000001; if (isnan(val)) strncpy(str,"NaN",len); else if (!isfinite(val)) { if (val<0) strncpy(str,"-Infinity",len); else strncpy(str,"Infinity",len); } else { if (val<0) { if (--len <= 0) { *str=0; return; } // bounds check *(str++) = '-'; val = -val; } // what if we're really close to an integer? Just use that... if (((JsVarInt)(val+stopAtError)) == (1+(JsVarInt)val)) val = (JsVarFloat)(1+(JsVarInt)val); JsVarFloat d = 1; while (d*radix <= val) d*=radix; while (d >= 1) { int v = (int)(val / d); val -= v*d; if (--len <= 0) { *str=0; return; } // bounds check *(str++) = itoch(v); d /= radix; } #ifndef USE_NO_FLOATS if (((fractionalDigits<0) && val>0) || fractionalDigits>0) { bool hasPt = false; val*=radix; while (((fractionalDigits<0) && (fractionalDigits>-12) && (val > stopAtError)) || (fractionalDigits > 0)) { int v = (int)(val+((fractionalDigits==1) ? 0.4 : 0.00000001) ); val = (val-v)*radix; if (v==radix) v=radix-1; if (!hasPt) { hasPt = true; if (--len <= 0) { *str=0; return; } // bounds check *(str++)='.'; } if (--len <= 0) { *str=0; return; } // bounds check *(str++)=itoch(v); fractionalDigits--; } } #endif *(str++)=0; } } void ftoa_bounded(JsVarFloat val,char *str, size_t len) { ftoa_bounded_extra(val, str, len, 10, -1); } /// Wrap a value so it is always between 0 and size (eg. wrapAround(angle, 360)) JsVarFloat wrapAround(JsVarFloat val, JsVarFloat size) { val = val / size; val = val - (int)val; return val * size; } /** * Espruino-special printf with a callback. * * The supported format specifiers are: * * `%d` = int * * `%0#d` or `%0#x` = int padded to length # with 0s * * `%x` = int as hex * * `%L` = JsVarInt * * `%Lx`= JsVarInt as hex * * `%f` = JsVarFloat * * `%s` = string (char *) * * `%c` = char * * `%v` = JsVar * (doesn't have to be a string - it'll be converted) * * `%q` = JsVar * (in quotes, and escaped) * * `%j` = Variable printed as JSON * * `%t` = Type of variable * * `%p` = Pin * * Anything else will assert */ void vcbprintf( vcbprintf_callback user_callback, //!< Unknown void *user_data, //!< Unknown const char *fmt, //!< The format specified va_list argp //!< List of parameter values ) { char buf[32]; while (*fmt) { if (*fmt == '%') { fmt++; char fmtChar = *fmt++; switch (fmtChar) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { const char *pad = " "; if (fmtChar=='0') { pad = "0"; fmtChar = *fmt++; } int digits = fmtChar - '0'; // of the form '%02d' int v = va_arg(argp, int); if (*fmt=='x') itostr_extra(v, buf, false, 16); else { assert('d' == *fmt); itostr(v, buf, 10); } fmt++; // skip over 'd' int len = (int)strlen(buf); while (len < digits) { user_callback(pad,user_data); len++; } user_callback(buf,user_data); break; } case 'd': itostr(va_arg(argp, int), buf, 10); user_callback(buf,user_data); break; case 'x': itostr_extra(va_arg(argp, int), buf, false, 16); user_callback(buf,user_data); break; case 'L': { unsigned int rad = 10; bool signedVal = true; if (*fmt=='x') { rad=16; fmt++; signedVal = false; } itostr_extra(va_arg(argp, JsVarInt), buf, signedVal, rad); user_callback(buf,user_data); } break; case 'f': ftoa_bounded(va_arg(argp, JsVarFloat), buf, sizeof(buf)); user_callback(buf,user_data); break; case 's': user_callback(va_arg(argp, char *), user_data); break; case 'c': buf[0]=(char)va_arg(argp, int/*char*/);buf[1]=0; user_callback(buf, user_data); break; case 'q': case 'v': { bool quoted = fmtChar=='q'; if (quoted) user_callback("\"",user_data); JsVar *v = jsvAsString(va_arg(argp, JsVar*), false/*no unlock*/); buf[1] = 0; if (jsvIsString(v)) { JsvStringIterator it; jsvStringIteratorNew(&it, v, 0); // OPT: this could be faster than it is (sending whole blocks at once) while (jsvStringIteratorHasChar(&it)) { buf[0] = jsvStringIteratorGetChar(&it); if (quoted) { user_callback(escapeCharacter(buf[0]), user_data); } else { user_callback(buf,user_data); } jsvStringIteratorNext(&it); } jsvStringIteratorFree(&it); jsvUnLock(v); } if (quoted) user_callback("\"",user_data); } break; case 'j': { JsVar *v = va_arg(argp, JsVar*); jsfGetJSONWithCallback(v, JSON_SOME_NEWLINES | JSON_PRETTY | JSON_SHOW_DEVICES, 0, user_callback, user_data); break; } case 't': { JsVar *v = va_arg(argp, JsVar*); const char *n = jsvIsNull(v)?"null":jswGetBasicObjectName(v); if (!n) n = jsvGetTypeOf(v); user_callback(n, user_data); break; } case 'p': jshGetPinString(buf, (Pin)va_arg(argp, int/*Pin*/)); user_callback(buf, user_data); break; default: assert(0); return; // eep } } else { buf[0] = *(fmt++); buf[1] = 0; user_callback(&buf[0], user_data); } } } void cbprintf(vcbprintf_callback user_callback, void *user_data, const char *fmt, ...) { va_list argp; va_start(argp, fmt); vcbprintf(user_callback,user_data, fmt, argp); va_end(argp); } typedef struct { char *outPtr; size_t idx; size_t len; } espruino_snprintf_data; void espruino_snprintf_cb(const char *str, void *userdata) { espruino_snprintf_data *d = (espruino_snprintf_data*)userdata; while (*str) { if (d->idx < d->len) d->outPtr[d->idx] = *str; d->idx++; str++; } } /// a snprintf replacement so mbedtls doesn't try and pull in the whole stdlib to cat two strings together int espruino_snprintf( char * s, size_t n, const char * fmt, ... ) { espruino_snprintf_data d; d.outPtr = s; d.idx = 0; d.len = n; va_list argp; va_start(argp, fmt); vcbprintf(espruino_snprintf_cb,&d, fmt, argp); va_end(argp); if (d.idx < d.len) d.outPtr[d.idx] = 0; else d.outPtr[d.len-1] = 0; return (int)d.idx; } #ifdef ARM extern int LINKER_END_VAR; // should be 'void', but 'int' avoids warnings #endif /** get the amount of free stack we have, in bytes */ size_t jsuGetFreeStack() { #ifdef ARM void *frame = __builtin_frame_address(0); size_t stackPos = (size_t)((char*)frame); size_t stackEnd = (size_t)((char*)&LINKER_END_VAR); if (stackPos < stackEnd) return 0; // should never happen, but just in case of overflow! return stackPos - stackEnd; #elif defined(LINUX) // On linux, we set STACK_BASE from `main`. char ptr; // this is on the stack extern void *STACK_BASE; uint32_t count = (uint32_t)((size_t)STACK_BASE - (size_t)&ptr); return 1000000 - count; // give it 1 megabyte of stack #else // stack depth seems pretty platform-specific :( Default to a value that disables it return 1000000; // no stack depth check on this platform #endif } unsigned int rand_m_w = 0xDEADBEEF; /* must not be zero */ unsigned int rand_m_z = 0xCAFEBABE; /* must not be zero */ int rand() { rand_m_z = 36969 * (rand_m_z & 65535) + (rand_m_z >> 16); rand_m_w = 18000 * (rand_m_w & 65535) + (rand_m_w >> 16); return (int)RAND_MAX & (int)((rand_m_z << 16) + rand_m_w); /* 32-bit result */ } void srand(unsigned int seed) { rand_m_w = (seed&0xFFFF) | (seed<<16); rand_m_z = (seed&0xFFFF0000) | (seed>>16); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_155_1
crossvul-cpp_data_good_222_0
/* * A framebuffer driver for VBE 2.0+ compliant video cards * * (c) 2007 Michal Januszewski <spock@gentoo.org> * Loosely based upon the vesafb driver. * */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/init.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/skbuff.h> #include <linux/timer.h> #include <linux/completion.h> #include <linux/connector.h> #include <linux/random.h> #include <linux/platform_device.h> #include <linux/limits.h> #include <linux/fb.h> #include <linux/io.h> #include <linux/mutex.h> #include <linux/slab.h> #include <video/edid.h> #include <video/uvesafb.h> #ifdef CONFIG_X86 #include <video/vga.h> #endif #include "edid.h" static struct cb_id uvesafb_cn_id = { .idx = CN_IDX_V86D, .val = CN_VAL_V86D_UVESAFB }; static char v86d_path[PATH_MAX] = "/sbin/v86d"; static char v86d_started; /* has v86d been started by uvesafb? */ static const struct fb_fix_screeninfo uvesafb_fix = { .id = "VESA VGA", .type = FB_TYPE_PACKED_PIXELS, .accel = FB_ACCEL_NONE, .visual = FB_VISUAL_TRUECOLOR, }; static int mtrr = 3; /* enable mtrr by default */ static bool blank = 1; /* enable blanking by default */ static int ypan = 1; /* 0: scroll, 1: ypan, 2: ywrap */ static bool pmi_setpal = true; /* use PMI for palette changes */ static bool nocrtc; /* ignore CRTC settings */ static bool noedid; /* don't try DDC transfers */ static int vram_remap; /* set amt. of memory to be used */ static int vram_total; /* set total amount of memory */ static u16 maxclk; /* maximum pixel clock */ static u16 maxvf; /* maximum vertical frequency */ static u16 maxhf; /* maximum horizontal frequency */ static u16 vbemode; /* force use of a specific VBE mode */ static char *mode_option; static u8 dac_width = 6; static struct uvesafb_ktask *uvfb_tasks[UVESAFB_TASKS_MAX]; static DEFINE_MUTEX(uvfb_lock); /* * A handler for replies from userspace. * * Make sure each message passes consistency checks and if it does, * find the kernel part of the task struct, copy the registers and * the buffer contents and then complete the task. */ static void uvesafb_cn_callback(struct cn_msg *msg, struct netlink_skb_parms *nsp) { struct uvesafb_task *utask; struct uvesafb_ktask *task; if (!capable(CAP_SYS_ADMIN)) return; if (msg->seq >= UVESAFB_TASKS_MAX) return; mutex_lock(&uvfb_lock); task = uvfb_tasks[msg->seq]; if (!task || msg->ack != task->ack) { mutex_unlock(&uvfb_lock); return; } utask = (struct uvesafb_task *)msg->data; /* Sanity checks for the buffer length. */ if (task->t.buf_len < utask->buf_len || utask->buf_len > msg->len - sizeof(*utask)) { mutex_unlock(&uvfb_lock); return; } uvfb_tasks[msg->seq] = NULL; mutex_unlock(&uvfb_lock); memcpy(&task->t, utask, sizeof(*utask)); if (task->t.buf_len && task->buf) memcpy(task->buf, utask + 1, task->t.buf_len); complete(task->done); return; } static int uvesafb_helper_start(void) { char *envp[] = { "HOME=/", "PATH=/sbin:/bin", NULL, }; char *argv[] = { v86d_path, NULL, }; return call_usermodehelper(v86d_path, argv, envp, UMH_WAIT_PROC); } /* * Execute a uvesafb task. * * Returns 0 if the task is executed successfully. * * A message sent to the userspace consists of the uvesafb_task * struct and (optionally) a buffer. The uvesafb_task struct is * a simplified version of uvesafb_ktask (its kernel counterpart) * containing only the register values, flags and the length of * the buffer. * * Each message is assigned a sequence number (increased linearly) * and a random ack number. The sequence number is used as a key * for the uvfb_tasks array which holds pointers to uvesafb_ktask * structs for all requests. */ static int uvesafb_exec(struct uvesafb_ktask *task) { static int seq; struct cn_msg *m; int err; int len = sizeof(task->t) + task->t.buf_len; /* * Check whether the message isn't longer than the maximum * allowed by connector. */ if (sizeof(*m) + len > CONNECTOR_MAX_MSG_SIZE) { pr_warn("message too long (%d), can't execute task\n", (int)(sizeof(*m) + len)); return -E2BIG; } m = kzalloc(sizeof(*m) + len, GFP_KERNEL); if (!m) return -ENOMEM; init_completion(task->done); memcpy(&m->id, &uvesafb_cn_id, sizeof(m->id)); m->seq = seq; m->len = len; m->ack = prandom_u32(); /* uvesafb_task structure */ memcpy(m + 1, &task->t, sizeof(task->t)); /* Buffer */ memcpy((u8 *)(m + 1) + sizeof(task->t), task->buf, task->t.buf_len); /* * Save the message ack number so that we can find the kernel * part of this task when a reply is received from userspace. */ task->ack = m->ack; mutex_lock(&uvfb_lock); /* If all slots are taken -- bail out. */ if (uvfb_tasks[seq]) { mutex_unlock(&uvfb_lock); err = -EBUSY; goto out; } /* Save a pointer to the kernel part of the task struct. */ uvfb_tasks[seq] = task; mutex_unlock(&uvfb_lock); err = cn_netlink_send(m, 0, 0, GFP_KERNEL); if (err == -ESRCH) { /* * Try to start the userspace helper if sending * the request failed the first time. */ err = uvesafb_helper_start(); if (err) { pr_err("failed to execute %s\n", v86d_path); pr_err("make sure that the v86d helper is installed and executable\n"); } else { v86d_started = 1; err = cn_netlink_send(m, 0, 0, gfp_any()); if (err == -ENOBUFS) err = 0; } } else if (err == -ENOBUFS) err = 0; if (!err && !(task->t.flags & TF_EXIT)) err = !wait_for_completion_timeout(task->done, msecs_to_jiffies(UVESAFB_TIMEOUT)); mutex_lock(&uvfb_lock); uvfb_tasks[seq] = NULL; mutex_unlock(&uvfb_lock); seq++; if (seq >= UVESAFB_TASKS_MAX) seq = 0; out: kfree(m); return err; } /* * Free a uvesafb_ktask struct. */ static void uvesafb_free(struct uvesafb_ktask *task) { if (task) { kfree(task->done); kfree(task); } } /* * Prepare a uvesafb_ktask struct to be used again. */ static void uvesafb_reset(struct uvesafb_ktask *task) { struct completion *cpl = task->done; memset(task, 0, sizeof(*task)); task->done = cpl; } /* * Allocate and prepare a uvesafb_ktask struct. */ static struct uvesafb_ktask *uvesafb_prep(void) { struct uvesafb_ktask *task; task = kzalloc(sizeof(*task), GFP_KERNEL); if (task) { task->done = kzalloc(sizeof(*task->done), GFP_KERNEL); if (!task->done) { kfree(task); task = NULL; } } return task; } static void uvesafb_setup_var(struct fb_var_screeninfo *var, struct fb_info *info, struct vbe_mode_ib *mode) { struct uvesafb_par *par = info->par; var->vmode = FB_VMODE_NONINTERLACED; var->sync = FB_SYNC_VERT_HIGH_ACT; var->xres = mode->x_res; var->yres = mode->y_res; var->xres_virtual = mode->x_res; var->yres_virtual = (par->ypan) ? info->fix.smem_len / mode->bytes_per_scan_line : mode->y_res; var->xoffset = 0; var->yoffset = 0; var->bits_per_pixel = mode->bits_per_pixel; if (var->bits_per_pixel == 15) var->bits_per_pixel = 16; if (var->bits_per_pixel > 8) { var->red.offset = mode->red_off; var->red.length = mode->red_len; var->green.offset = mode->green_off; var->green.length = mode->green_len; var->blue.offset = mode->blue_off; var->blue.length = mode->blue_len; var->transp.offset = mode->rsvd_off; var->transp.length = mode->rsvd_len; } else { var->red.offset = 0; var->green.offset = 0; var->blue.offset = 0; var->transp.offset = 0; var->red.length = 8; var->green.length = 8; var->blue.length = 8; var->transp.length = 0; } } static int uvesafb_vbe_find_mode(struct uvesafb_par *par, int xres, int yres, int depth, unsigned char flags) { int i, match = -1, h = 0, d = 0x7fffffff; for (i = 0; i < par->vbe_modes_cnt; i++) { h = abs(par->vbe_modes[i].x_res - xres) + abs(par->vbe_modes[i].y_res - yres) + abs(depth - par->vbe_modes[i].depth); /* * We have an exact match in terms of resolution * and depth. */ if (h == 0) return i; if (h < d || (h == d && par->vbe_modes[i].depth > depth)) { d = h; match = i; } } i = 1; if (flags & UVESAFB_EXACT_DEPTH && par->vbe_modes[match].depth != depth) i = 0; if (flags & UVESAFB_EXACT_RES && d > 24) i = 0; if (i != 0) return match; else return -1; } static u8 *uvesafb_vbe_state_save(struct uvesafb_par *par) { struct uvesafb_ktask *task; u8 *state; int err; if (!par->vbe_state_size) return NULL; state = kmalloc(par->vbe_state_size, GFP_KERNEL); if (!state) return ERR_PTR(-ENOMEM); task = uvesafb_prep(); if (!task) { kfree(state); return NULL; } task->t.regs.eax = 0x4f04; task->t.regs.ecx = 0x000f; task->t.regs.edx = 0x0001; task->t.flags = TF_BUF_RET | TF_BUF_ESBX; task->t.buf_len = par->vbe_state_size; task->buf = state; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) { pr_warn("VBE get state call failed (eax=0x%x, err=%d)\n", task->t.regs.eax, err); kfree(state); state = NULL; } uvesafb_free(task); return state; } static void uvesafb_vbe_state_restore(struct uvesafb_par *par, u8 *state_buf) { struct uvesafb_ktask *task; int err; if (!state_buf) return; task = uvesafb_prep(); if (!task) return; task->t.regs.eax = 0x4f04; task->t.regs.ecx = 0x000f; task->t.regs.edx = 0x0002; task->t.buf_len = par->vbe_state_size; task->t.flags = TF_BUF_ESBX; task->buf = state_buf; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) pr_warn("VBE state restore call failed (eax=0x%x, err=%d)\n", task->t.regs.eax, err); uvesafb_free(task); } static int uvesafb_vbe_getinfo(struct uvesafb_ktask *task, struct uvesafb_par *par) { int err; task->t.regs.eax = 0x4f00; task->t.flags = TF_VBEIB; task->t.buf_len = sizeof(struct vbe_ib); task->buf = &par->vbe_ib; strncpy(par->vbe_ib.vbe_signature, "VBE2", 4); err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) { pr_err("Getting VBE info block failed (eax=0x%x, err=%d)\n", (u32)task->t.regs.eax, err); return -EINVAL; } if (par->vbe_ib.vbe_version < 0x0200) { pr_err("Sorry, pre-VBE 2.0 cards are not supported\n"); return -EINVAL; } if (!par->vbe_ib.mode_list_ptr) { pr_err("Missing mode list!\n"); return -EINVAL; } pr_info(""); /* * Convert string pointers and the mode list pointer into * usable addresses. Print informational messages about the * video adapter and its vendor. */ if (par->vbe_ib.oem_vendor_name_ptr) pr_cont("%s, ", ((char *)task->buf) + par->vbe_ib.oem_vendor_name_ptr); if (par->vbe_ib.oem_product_name_ptr) pr_cont("%s, ", ((char *)task->buf) + par->vbe_ib.oem_product_name_ptr); if (par->vbe_ib.oem_product_rev_ptr) pr_cont("%s, ", ((char *)task->buf) + par->vbe_ib.oem_product_rev_ptr); if (par->vbe_ib.oem_string_ptr) pr_cont("OEM: %s, ", ((char *)task->buf) + par->vbe_ib.oem_string_ptr); pr_cont("VBE v%d.%d\n", (par->vbe_ib.vbe_version & 0xff00) >> 8, par->vbe_ib.vbe_version & 0xff); return 0; } static int uvesafb_vbe_getmodes(struct uvesafb_ktask *task, struct uvesafb_par *par) { int off = 0, err; u16 *mode; par->vbe_modes_cnt = 0; /* Count available modes. */ mode = (u16 *) (((u8 *)&par->vbe_ib) + par->vbe_ib.mode_list_ptr); while (*mode != 0xffff) { par->vbe_modes_cnt++; mode++; } par->vbe_modes = kzalloc(sizeof(struct vbe_mode_ib) * par->vbe_modes_cnt, GFP_KERNEL); if (!par->vbe_modes) return -ENOMEM; /* Get info about all available modes. */ mode = (u16 *) (((u8 *)&par->vbe_ib) + par->vbe_ib.mode_list_ptr); while (*mode != 0xffff) { struct vbe_mode_ib *mib; uvesafb_reset(task); task->t.regs.eax = 0x4f01; task->t.regs.ecx = (u32) *mode; task->t.flags = TF_BUF_RET | TF_BUF_ESDI; task->t.buf_len = sizeof(struct vbe_mode_ib); task->buf = par->vbe_modes + off; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) { pr_warn("Getting mode info block for mode 0x%x failed (eax=0x%x, err=%d)\n", *mode, (u32)task->t.regs.eax, err); mode++; par->vbe_modes_cnt--; continue; } mib = task->buf; mib->mode_id = *mode; /* * We only want modes that are supported with the current * hardware configuration, color, graphics and that have * support for the LFB. */ if ((mib->mode_attr & VBE_MODE_MASK) == VBE_MODE_MASK && mib->bits_per_pixel >= 8) off++; else par->vbe_modes_cnt--; mode++; mib->depth = mib->red_len + mib->green_len + mib->blue_len; /* * Handle 8bpp modes and modes with broken color component * lengths. */ if (mib->depth == 0 || (mib->depth == 24 && mib->bits_per_pixel == 32)) mib->depth = mib->bits_per_pixel; } if (par->vbe_modes_cnt > 0) return 0; else return -EINVAL; } /* * The Protected Mode Interface is 32-bit x86 code, so we only run it on * x86 and not x86_64. */ #ifdef CONFIG_X86_32 static int uvesafb_vbe_getpmi(struct uvesafb_ktask *task, struct uvesafb_par *par) { int i, err; uvesafb_reset(task); task->t.regs.eax = 0x4f0a; task->t.regs.ebx = 0x0; err = uvesafb_exec(task); if ((task->t.regs.eax & 0xffff) != 0x4f || task->t.regs.es < 0xc000) { par->pmi_setpal = par->ypan = 0; } else { par->pmi_base = (u16 *)phys_to_virt(((u32)task->t.regs.es << 4) + task->t.regs.edi); par->pmi_start = (u8 *)par->pmi_base + par->pmi_base[1]; par->pmi_pal = (u8 *)par->pmi_base + par->pmi_base[2]; pr_info("protected mode interface info at %04x:%04x\n", (u16)task->t.regs.es, (u16)task->t.regs.edi); pr_info("pmi: set display start = %p, set palette = %p\n", par->pmi_start, par->pmi_pal); if (par->pmi_base[3]) { pr_info("pmi: ports ="); for (i = par->pmi_base[3]/2; par->pmi_base[i] != 0xffff; i++) pr_cont(" %x", par->pmi_base[i]); pr_cont("\n"); if (par->pmi_base[i] != 0xffff) { pr_info("can't handle memory requests, pmi disabled\n"); par->ypan = par->pmi_setpal = 0; } } } return 0; } #endif /* CONFIG_X86_32 */ /* * Check whether a video mode is supported by the Video BIOS and is * compatible with the monitor limits. */ static int uvesafb_is_valid_mode(struct fb_videomode *mode, struct fb_info *info) { if (info->monspecs.gtf) { fb_videomode_to_var(&info->var, mode); if (fb_validate_mode(&info->var, info)) return 0; } if (uvesafb_vbe_find_mode(info->par, mode->xres, mode->yres, 8, UVESAFB_EXACT_RES) == -1) return 0; return 1; } static int uvesafb_vbe_getedid(struct uvesafb_ktask *task, struct fb_info *info) { struct uvesafb_par *par = info->par; int err = 0; if (noedid || par->vbe_ib.vbe_version < 0x0300) return -EINVAL; task->t.regs.eax = 0x4f15; task->t.regs.ebx = 0; task->t.regs.ecx = 0; task->t.buf_len = 0; task->t.flags = 0; err = uvesafb_exec(task); if ((task->t.regs.eax & 0xffff) != 0x004f || err) return -EINVAL; if ((task->t.regs.ebx & 0x3) == 3) { pr_info("VBIOS/hardware supports both DDC1 and DDC2 transfers\n"); } else if ((task->t.regs.ebx & 0x3) == 2) { pr_info("VBIOS/hardware supports DDC2 transfers\n"); } else if ((task->t.regs.ebx & 0x3) == 1) { pr_info("VBIOS/hardware supports DDC1 transfers\n"); } else { pr_info("VBIOS/hardware doesn't support DDC transfers\n"); return -EINVAL; } task->t.regs.eax = 0x4f15; task->t.regs.ebx = 1; task->t.regs.ecx = task->t.regs.edx = 0; task->t.flags = TF_BUF_RET | TF_BUF_ESDI; task->t.buf_len = EDID_LENGTH; task->buf = kzalloc(EDID_LENGTH, GFP_KERNEL); if (!task->buf) return -ENOMEM; err = uvesafb_exec(task); if ((task->t.regs.eax & 0xffff) == 0x004f && !err) { fb_edid_to_monspecs(task->buf, &info->monspecs); if (info->monspecs.vfmax && info->monspecs.hfmax) { /* * If the maximum pixel clock wasn't specified in * the EDID block, set it to 300 MHz. */ if (info->monspecs.dclkmax == 0) info->monspecs.dclkmax = 300 * 1000000; info->monspecs.gtf = 1; } } else { err = -EINVAL; } kfree(task->buf); return err; } static void uvesafb_vbe_getmonspecs(struct uvesafb_ktask *task, struct fb_info *info) { struct uvesafb_par *par = info->par; int i; memset(&info->monspecs, 0, sizeof(info->monspecs)); /* * If we don't get all necessary data from the EDID block, * mark it as incompatible with the GTF and set nocrtc so * that we always use the default BIOS refresh rate. */ if (uvesafb_vbe_getedid(task, info)) { info->monspecs.gtf = 0; par->nocrtc = 1; } /* Kernel command line overrides. */ if (maxclk) info->monspecs.dclkmax = maxclk * 1000000; if (maxvf) info->monspecs.vfmax = maxvf; if (maxhf) info->monspecs.hfmax = maxhf * 1000; /* * In case DDC transfers are not supported, the user can provide * monitor limits manually. Lower limits are set to "safe" values. */ if (info->monspecs.gtf == 0 && maxclk && maxvf && maxhf) { info->monspecs.dclkmin = 0; info->monspecs.vfmin = 60; info->monspecs.hfmin = 29000; info->monspecs.gtf = 1; par->nocrtc = 0; } if (info->monspecs.gtf) pr_info("monitor limits: vf = %d Hz, hf = %d kHz, clk = %d MHz\n", info->monspecs.vfmax, (int)(info->monspecs.hfmax / 1000), (int)(info->monspecs.dclkmax / 1000000)); else pr_info("no monitor limits have been set, default refresh rate will be used\n"); /* Add VBE modes to the modelist. */ for (i = 0; i < par->vbe_modes_cnt; i++) { struct fb_var_screeninfo var; struct vbe_mode_ib *mode; struct fb_videomode vmode; mode = &par->vbe_modes[i]; memset(&var, 0, sizeof(var)); var.xres = mode->x_res; var.yres = mode->y_res; fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON, 60, &var, info); fb_var_to_videomode(&vmode, &var); fb_add_videomode(&vmode, &info->modelist); } /* Add valid VESA modes to our modelist. */ for (i = 0; i < VESA_MODEDB_SIZE; i++) { if (uvesafb_is_valid_mode((struct fb_videomode *) &vesa_modes[i], info)) fb_add_videomode(&vesa_modes[i], &info->modelist); } for (i = 0; i < info->monspecs.modedb_len; i++) { if (uvesafb_is_valid_mode(&info->monspecs.modedb[i], info)) fb_add_videomode(&info->monspecs.modedb[i], &info->modelist); } return; } static void uvesafb_vbe_getstatesize(struct uvesafb_ktask *task, struct uvesafb_par *par) { int err; uvesafb_reset(task); /* * Get the VBE state buffer size. We want all available * hardware state data (CL = 0x0f). */ task->t.regs.eax = 0x4f04; task->t.regs.ecx = 0x000f; task->t.regs.edx = 0x0000; task->t.flags = 0; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) { pr_warn("VBE state buffer size cannot be determined (eax=0x%x, err=%d)\n", task->t.regs.eax, err); par->vbe_state_size = 0; return; } par->vbe_state_size = 64 * (task->t.regs.ebx & 0xffff); } static int uvesafb_vbe_init(struct fb_info *info) { struct uvesafb_ktask *task = NULL; struct uvesafb_par *par = info->par; int err; task = uvesafb_prep(); if (!task) return -ENOMEM; err = uvesafb_vbe_getinfo(task, par); if (err) goto out; err = uvesafb_vbe_getmodes(task, par); if (err) goto out; par->nocrtc = nocrtc; #ifdef CONFIG_X86_32 par->pmi_setpal = pmi_setpal; par->ypan = ypan; if (par->pmi_setpal || par->ypan) { if (__supported_pte_mask & _PAGE_NX) { par->pmi_setpal = par->ypan = 0; pr_warn("NX protection is active, better not use the PMI\n"); } else { uvesafb_vbe_getpmi(task, par); } } #else /* The protected mode interface is not available on non-x86. */ par->pmi_setpal = par->ypan = 0; #endif INIT_LIST_HEAD(&info->modelist); uvesafb_vbe_getmonspecs(task, info); uvesafb_vbe_getstatesize(task, par); out: uvesafb_free(task); return err; } static int uvesafb_vbe_init_mode(struct fb_info *info) { struct list_head *pos; struct fb_modelist *modelist; struct fb_videomode *mode; struct uvesafb_par *par = info->par; int i, modeid; /* Has the user requested a specific VESA mode? */ if (vbemode) { for (i = 0; i < par->vbe_modes_cnt; i++) { if (par->vbe_modes[i].mode_id == vbemode) { modeid = i; uvesafb_setup_var(&info->var, info, &par->vbe_modes[modeid]); fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON, 60, &info->var, info); /* * With pixclock set to 0, the default BIOS * timings will be used in set_par(). */ info->var.pixclock = 0; goto gotmode; } } pr_info("requested VBE mode 0x%x is unavailable\n", vbemode); vbemode = 0; } /* Count the modes in the modelist */ i = 0; list_for_each(pos, &info->modelist) i++; /* * Convert the modelist into a modedb so that we can use it with * fb_find_mode(). */ mode = kzalloc(i * sizeof(*mode), GFP_KERNEL); if (mode) { i = 0; list_for_each(pos, &info->modelist) { modelist = list_entry(pos, struct fb_modelist, list); mode[i] = modelist->mode; i++; } if (!mode_option) mode_option = UVESAFB_DEFAULT_MODE; i = fb_find_mode(&info->var, info, mode_option, mode, i, NULL, 8); kfree(mode); } /* fb_find_mode() failed */ if (i == 0) { info->var.xres = 640; info->var.yres = 480; mode = (struct fb_videomode *) fb_find_best_mode(&info->var, &info->modelist); if (mode) { fb_videomode_to_var(&info->var, mode); } else { modeid = par->vbe_modes[0].mode_id; uvesafb_setup_var(&info->var, info, &par->vbe_modes[modeid]); fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON, 60, &info->var, info); goto gotmode; } } /* Look for a matching VBE mode. */ modeid = uvesafb_vbe_find_mode(par, info->var.xres, info->var.yres, info->var.bits_per_pixel, UVESAFB_EXACT_RES); if (modeid == -1) return -EINVAL; uvesafb_setup_var(&info->var, info, &par->vbe_modes[modeid]); gotmode: /* * If we are not VBE3.0+ compliant, we're done -- the BIOS will * ignore our timings anyway. */ if (par->vbe_ib.vbe_version < 0x0300 || par->nocrtc) fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON, 60, &info->var, info); return modeid; } static int uvesafb_setpalette(struct uvesafb_pal_entry *entries, int count, int start, struct fb_info *info) { struct uvesafb_ktask *task; #ifdef CONFIG_X86 struct uvesafb_par *par = info->par; int i = par->mode_idx; #endif int err = 0; /* * We support palette modifications for 8 bpp modes only, so * there can never be more than 256 entries. */ if (start + count > 256) return -EINVAL; #ifdef CONFIG_X86 /* Use VGA registers if mode is VGA-compatible. */ if (i >= 0 && i < par->vbe_modes_cnt && par->vbe_modes[i].mode_attr & VBE_MODE_VGACOMPAT) { for (i = 0; i < count; i++) { outb_p(start + i, dac_reg); outb_p(entries[i].red, dac_val); outb_p(entries[i].green, dac_val); outb_p(entries[i].blue, dac_val); } } #ifdef CONFIG_X86_32 else if (par->pmi_setpal) { __asm__ __volatile__( "call *(%%esi)" : /* no return value */ : "a" (0x4f09), /* EAX */ "b" (0), /* EBX */ "c" (count), /* ECX */ "d" (start), /* EDX */ "D" (entries), /* EDI */ "S" (&par->pmi_pal)); /* ESI */ } #endif /* CONFIG_X86_32 */ else #endif /* CONFIG_X86 */ { task = uvesafb_prep(); if (!task) return -ENOMEM; task->t.regs.eax = 0x4f09; task->t.regs.ebx = 0x0; task->t.regs.ecx = count; task->t.regs.edx = start; task->t.flags = TF_BUF_ESDI; task->t.buf_len = sizeof(struct uvesafb_pal_entry) * count; task->buf = entries; err = uvesafb_exec(task); if ((task->t.regs.eax & 0xffff) != 0x004f) err = 1; uvesafb_free(task); } return err; } static int uvesafb_setcolreg(unsigned regno, unsigned red, unsigned green, unsigned blue, unsigned transp, struct fb_info *info) { struct uvesafb_pal_entry entry; int shift = 16 - dac_width; int err = 0; if (regno >= info->cmap.len) return -EINVAL; if (info->var.bits_per_pixel == 8) { entry.red = red >> shift; entry.green = green >> shift; entry.blue = blue >> shift; entry.pad = 0; err = uvesafb_setpalette(&entry, 1, regno, info); } else if (regno < 16) { switch (info->var.bits_per_pixel) { case 16: if (info->var.red.offset == 10) { /* 1:5:5:5 */ ((u32 *) (info->pseudo_palette))[regno] = ((red & 0xf800) >> 1) | ((green & 0xf800) >> 6) | ((blue & 0xf800) >> 11); } else { /* 0:5:6:5 */ ((u32 *) (info->pseudo_palette))[regno] = ((red & 0xf800) ) | ((green & 0xfc00) >> 5) | ((blue & 0xf800) >> 11); } break; case 24: case 32: red >>= 8; green >>= 8; blue >>= 8; ((u32 *)(info->pseudo_palette))[regno] = (red << info->var.red.offset) | (green << info->var.green.offset) | (blue << info->var.blue.offset); break; } } return err; } static int uvesafb_setcmap(struct fb_cmap *cmap, struct fb_info *info) { struct uvesafb_pal_entry *entries; int shift = 16 - dac_width; int i, err = 0; if (info->var.bits_per_pixel == 8) { if (cmap->start + cmap->len > info->cmap.start + info->cmap.len || cmap->start < info->cmap.start) return -EINVAL; entries = kmalloc_array(cmap->len, sizeof(*entries), GFP_KERNEL); if (!entries) return -ENOMEM; for (i = 0; i < cmap->len; i++) { entries[i].red = cmap->red[i] >> shift; entries[i].green = cmap->green[i] >> shift; entries[i].blue = cmap->blue[i] >> shift; entries[i].pad = 0; } err = uvesafb_setpalette(entries, cmap->len, cmap->start, info); kfree(entries); } else { /* * For modes with bpp > 8, we only set the pseudo palette in * the fb_info struct. We rely on uvesafb_setcolreg to do all * sanity checking. */ for (i = 0; i < cmap->len; i++) { err |= uvesafb_setcolreg(cmap->start + i, cmap->red[i], cmap->green[i], cmap->blue[i], 0, info); } } return err; } static int uvesafb_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { #ifdef CONFIG_X86_32 int offset; struct uvesafb_par *par = info->par; offset = (var->yoffset * info->fix.line_length + var->xoffset) / 4; /* * It turns out it's not the best idea to do panning via vm86, * so we only allow it if we have a PMI. */ if (par->pmi_start) { __asm__ __volatile__( "call *(%%edi)" : /* no return value */ : "a" (0x4f07), /* EAX */ "b" (0), /* EBX */ "c" (offset), /* ECX */ "d" (offset >> 16), /* EDX */ "D" (&par->pmi_start)); /* EDI */ } #endif return 0; } static int uvesafb_blank(int blank, struct fb_info *info) { struct uvesafb_ktask *task; int err = 1; #ifdef CONFIG_X86 struct uvesafb_par *par = info->par; if (par->vbe_ib.capabilities & VBE_CAP_VGACOMPAT) { int loop = 10000; u8 seq = 0, crtc17 = 0; if (blank == FB_BLANK_POWERDOWN) { seq = 0x20; crtc17 = 0x00; err = 0; } else { seq = 0x00; crtc17 = 0x80; err = (blank == FB_BLANK_UNBLANK) ? 0 : -EINVAL; } vga_wseq(NULL, 0x00, 0x01); seq |= vga_rseq(NULL, 0x01) & ~0x20; vga_wseq(NULL, 0x00, seq); crtc17 |= vga_rcrt(NULL, 0x17) & ~0x80; while (loop--); vga_wcrt(NULL, 0x17, crtc17); vga_wseq(NULL, 0x00, 0x03); } else #endif /* CONFIG_X86 */ { task = uvesafb_prep(); if (!task) return -ENOMEM; task->t.regs.eax = 0x4f10; switch (blank) { case FB_BLANK_UNBLANK: task->t.regs.ebx = 0x0001; break; case FB_BLANK_NORMAL: task->t.regs.ebx = 0x0101; /* standby */ break; case FB_BLANK_POWERDOWN: task->t.regs.ebx = 0x0401; /* powerdown */ break; default: goto out; } err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) err = 1; out: uvesafb_free(task); } return err; } static int uvesafb_open(struct fb_info *info, int user) { struct uvesafb_par *par = info->par; int cnt = atomic_read(&par->ref_count); u8 *buf = NULL; if (!cnt && par->vbe_state_size) { buf = uvesafb_vbe_state_save(par); if (IS_ERR(buf)) { pr_warn("save hardware state failed, error code is %ld!\n", PTR_ERR(buf)); } else { par->vbe_state_orig = buf; } } atomic_inc(&par->ref_count); return 0; } static int uvesafb_release(struct fb_info *info, int user) { struct uvesafb_ktask *task = NULL; struct uvesafb_par *par = info->par; int cnt = atomic_read(&par->ref_count); if (!cnt) return -EINVAL; if (cnt != 1) goto out; task = uvesafb_prep(); if (!task) goto out; /* First, try to set the standard 80x25 text mode. */ task->t.regs.eax = 0x0003; uvesafb_exec(task); /* * Now try to restore whatever hardware state we might have * saved when the fb device was first opened. */ uvesafb_vbe_state_restore(par, par->vbe_state_orig); out: atomic_dec(&par->ref_count); uvesafb_free(task); return 0; } static int uvesafb_set_par(struct fb_info *info) { struct uvesafb_par *par = info->par; struct uvesafb_ktask *task = NULL; struct vbe_crtc_ib *crtc = NULL; struct vbe_mode_ib *mode = NULL; int i, err = 0, depth = info->var.bits_per_pixel; if (depth > 8 && depth != 32) depth = info->var.red.length + info->var.green.length + info->var.blue.length; i = uvesafb_vbe_find_mode(par, info->var.xres, info->var.yres, depth, UVESAFB_EXACT_RES | UVESAFB_EXACT_DEPTH); if (i >= 0) mode = &par->vbe_modes[i]; else return -EINVAL; task = uvesafb_prep(); if (!task) return -ENOMEM; setmode: task->t.regs.eax = 0x4f02; task->t.regs.ebx = mode->mode_id | 0x4000; /* use LFB */ if (par->vbe_ib.vbe_version >= 0x0300 && !par->nocrtc && info->var.pixclock != 0) { task->t.regs.ebx |= 0x0800; /* use CRTC data */ task->t.flags = TF_BUF_ESDI; crtc = kzalloc(sizeof(struct vbe_crtc_ib), GFP_KERNEL); if (!crtc) { err = -ENOMEM; goto out; } crtc->horiz_start = info->var.xres + info->var.right_margin; crtc->horiz_end = crtc->horiz_start + info->var.hsync_len; crtc->horiz_total = crtc->horiz_end + info->var.left_margin; crtc->vert_start = info->var.yres + info->var.lower_margin; crtc->vert_end = crtc->vert_start + info->var.vsync_len; crtc->vert_total = crtc->vert_end + info->var.upper_margin; crtc->pixel_clock = PICOS2KHZ(info->var.pixclock) * 1000; crtc->refresh_rate = (u16)(100 * (crtc->pixel_clock / (crtc->vert_total * crtc->horiz_total))); if (info->var.vmode & FB_VMODE_DOUBLE) crtc->flags |= 0x1; if (info->var.vmode & FB_VMODE_INTERLACED) crtc->flags |= 0x2; if (!(info->var.sync & FB_SYNC_HOR_HIGH_ACT)) crtc->flags |= 0x4; if (!(info->var.sync & FB_SYNC_VERT_HIGH_ACT)) crtc->flags |= 0x8; memcpy(&par->crtc, crtc, sizeof(*crtc)); } else { memset(&par->crtc, 0, sizeof(*crtc)); } task->t.buf_len = sizeof(struct vbe_crtc_ib); task->buf = &par->crtc; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f) { /* * The mode switch might have failed because we tried to * use our own timings. Try again with the default timings. */ if (crtc != NULL) { pr_warn("mode switch failed (eax=0x%x, err=%d) - trying again with default timings\n", task->t.regs.eax, err); uvesafb_reset(task); kfree(crtc); crtc = NULL; info->var.pixclock = 0; goto setmode; } else { pr_err("mode switch failed (eax=0x%x, err=%d)\n", task->t.regs.eax, err); err = -EINVAL; goto out; } } par->mode_idx = i; /* For 8bpp modes, always try to set the DAC to 8 bits. */ if (par->vbe_ib.capabilities & VBE_CAP_CAN_SWITCH_DAC && mode->bits_per_pixel <= 8) { uvesafb_reset(task); task->t.regs.eax = 0x4f08; task->t.regs.ebx = 0x0800; err = uvesafb_exec(task); if (err || (task->t.regs.eax & 0xffff) != 0x004f || ((task->t.regs.ebx & 0xff00) >> 8) != 8) { dac_width = 6; } else { dac_width = 8; } } info->fix.visual = (info->var.bits_per_pixel == 8) ? FB_VISUAL_PSEUDOCOLOR : FB_VISUAL_TRUECOLOR; info->fix.line_length = mode->bytes_per_scan_line; out: kfree(crtc); uvesafb_free(task); return err; } static void uvesafb_check_limits(struct fb_var_screeninfo *var, struct fb_info *info) { const struct fb_videomode *mode; struct uvesafb_par *par = info->par; /* * If pixclock is set to 0, then we're using default BIOS timings * and thus don't have to perform any checks here. */ if (!var->pixclock) return; if (par->vbe_ib.vbe_version < 0x0300) { fb_get_mode(FB_VSYNCTIMINGS | FB_IGNOREMON, 60, var, info); return; } if (!fb_validate_mode(var, info)) return; mode = fb_find_best_mode(var, &info->modelist); if (mode) { if (mode->xres == var->xres && mode->yres == var->yres && !(mode->vmode & (FB_VMODE_INTERLACED | FB_VMODE_DOUBLE))) { fb_videomode_to_var(var, mode); return; } } if (info->monspecs.gtf && !fb_get_mode(FB_MAXTIMINGS, 0, var, info)) return; /* Use default refresh rate */ var->pixclock = 0; } static int uvesafb_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { struct uvesafb_par *par = info->par; struct vbe_mode_ib *mode = NULL; int match = -1; int depth = var->red.length + var->green.length + var->blue.length; /* * Various apps will use bits_per_pixel to set the color depth, * which is theoretically incorrect, but which we'll try to handle * here. */ if (depth == 0 || abs(depth - var->bits_per_pixel) >= 8) depth = var->bits_per_pixel; match = uvesafb_vbe_find_mode(par, var->xres, var->yres, depth, UVESAFB_EXACT_RES); if (match == -1) return -EINVAL; mode = &par->vbe_modes[match]; uvesafb_setup_var(var, info, mode); /* * Check whether we have remapped enough memory for this mode. * We might be called at an early stage, when we haven't remapped * any memory yet, in which case we simply skip the check. */ if (var->yres * mode->bytes_per_scan_line > info->fix.smem_len && info->fix.smem_len) return -EINVAL; if ((var->vmode & FB_VMODE_DOUBLE) && !(par->vbe_modes[match].mode_attr & 0x100)) var->vmode &= ~FB_VMODE_DOUBLE; if ((var->vmode & FB_VMODE_INTERLACED) && !(par->vbe_modes[match].mode_attr & 0x200)) var->vmode &= ~FB_VMODE_INTERLACED; uvesafb_check_limits(var, info); var->xres_virtual = var->xres; var->yres_virtual = (par->ypan) ? info->fix.smem_len / mode->bytes_per_scan_line : var->yres; return 0; } static struct fb_ops uvesafb_ops = { .owner = THIS_MODULE, .fb_open = uvesafb_open, .fb_release = uvesafb_release, .fb_setcolreg = uvesafb_setcolreg, .fb_setcmap = uvesafb_setcmap, .fb_pan_display = uvesafb_pan_display, .fb_blank = uvesafb_blank, .fb_fillrect = cfb_fillrect, .fb_copyarea = cfb_copyarea, .fb_imageblit = cfb_imageblit, .fb_check_var = uvesafb_check_var, .fb_set_par = uvesafb_set_par, }; static void uvesafb_init_info(struct fb_info *info, struct vbe_mode_ib *mode) { unsigned int size_vmode; unsigned int size_remap; unsigned int size_total; struct uvesafb_par *par = info->par; int i, h; info->pseudo_palette = ((u8 *)info->par + sizeof(struct uvesafb_par)); info->fix = uvesafb_fix; info->fix.ypanstep = par->ypan ? 1 : 0; info->fix.ywrapstep = (par->ypan > 1) ? 1 : 0; /* Disable blanking if the user requested so. */ if (!blank) info->fbops->fb_blank = NULL; /* * Find out how much IO memory is required for the mode with * the highest resolution. */ size_remap = 0; for (i = 0; i < par->vbe_modes_cnt; i++) { h = par->vbe_modes[i].bytes_per_scan_line * par->vbe_modes[i].y_res; if (h > size_remap) size_remap = h; } size_remap *= 2; /* * size_vmode -- that is the amount of memory needed for the * used video mode, i.e. the minimum amount of * memory we need. */ size_vmode = info->var.yres * mode->bytes_per_scan_line; /* * size_total -- all video memory we have. Used for mtrr * entries, resource allocation and bounds * checking. */ size_total = par->vbe_ib.total_memory * 65536; if (vram_total) size_total = vram_total * 1024 * 1024; if (size_total < size_vmode) size_total = size_vmode; /* * size_remap -- the amount of video memory we are going to * use for vesafb. With modern cards it is no * option to simply use size_total as th * wastes plenty of kernel address space. */ if (vram_remap) size_remap = vram_remap * 1024 * 1024; if (size_remap < size_vmode) size_remap = size_vmode; if (size_remap > size_total) size_remap = size_total; info->fix.smem_len = size_remap; info->fix.smem_start = mode->phys_base_ptr; /* * We have to set yres_virtual here because when setup_var() was * called, smem_len wasn't defined yet. */ info->var.yres_virtual = info->fix.smem_len / mode->bytes_per_scan_line; if (par->ypan && info->var.yres_virtual > info->var.yres) { pr_info("scrolling: %s using protected mode interface, yres_virtual=%d\n", (par->ypan > 1) ? "ywrap" : "ypan", info->var.yres_virtual); } else { pr_info("scrolling: redraw\n"); info->var.yres_virtual = info->var.yres; par->ypan = 0; } info->flags = FBINFO_FLAG_DEFAULT | (par->ypan ? FBINFO_HWACCEL_YPAN : 0); if (!par->ypan) info->fbops->fb_pan_display = NULL; } static void uvesafb_init_mtrr(struct fb_info *info) { struct uvesafb_par *par = info->par; if (mtrr && !(info->fix.smem_start & (PAGE_SIZE - 1))) { int temp_size = info->fix.smem_len; int rc; /* Find the largest power-of-two */ temp_size = roundup_pow_of_two(temp_size); /* Try and find a power of two to add */ do { rc = arch_phys_wc_add(info->fix.smem_start, temp_size); temp_size >>= 1; } while (temp_size >= PAGE_SIZE && rc == -EINVAL); if (rc >= 0) par->mtrr_handle = rc; } } static void uvesafb_ioremap(struct fb_info *info) { info->screen_base = ioremap_wc(info->fix.smem_start, info->fix.smem_len); } static ssize_t uvesafb_show_vbe_ver(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; return snprintf(buf, PAGE_SIZE, "%.4x\n", par->vbe_ib.vbe_version); } static DEVICE_ATTR(vbe_version, S_IRUGO, uvesafb_show_vbe_ver, NULL); static ssize_t uvesafb_show_vbe_modes(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; int ret = 0, i; for (i = 0; i < par->vbe_modes_cnt && ret < PAGE_SIZE; i++) { ret += snprintf(buf + ret, PAGE_SIZE - ret, "%dx%d-%d, 0x%.4x\n", par->vbe_modes[i].x_res, par->vbe_modes[i].y_res, par->vbe_modes[i].depth, par->vbe_modes[i].mode_id); } return ret; } static DEVICE_ATTR(vbe_modes, S_IRUGO, uvesafb_show_vbe_modes, NULL); static ssize_t uvesafb_show_vendor(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; if (par->vbe_ib.oem_vendor_name_ptr) return snprintf(buf, PAGE_SIZE, "%s\n", (char *) (&par->vbe_ib) + par->vbe_ib.oem_vendor_name_ptr); else return 0; } static DEVICE_ATTR(oem_vendor, S_IRUGO, uvesafb_show_vendor, NULL); static ssize_t uvesafb_show_product_name(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; if (par->vbe_ib.oem_product_name_ptr) return snprintf(buf, PAGE_SIZE, "%s\n", (char *) (&par->vbe_ib) + par->vbe_ib.oem_product_name_ptr); else return 0; } static DEVICE_ATTR(oem_product_name, S_IRUGO, uvesafb_show_product_name, NULL); static ssize_t uvesafb_show_product_rev(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; if (par->vbe_ib.oem_product_rev_ptr) return snprintf(buf, PAGE_SIZE, "%s\n", (char *) (&par->vbe_ib) + par->vbe_ib.oem_product_rev_ptr); else return 0; } static DEVICE_ATTR(oem_product_rev, S_IRUGO, uvesafb_show_product_rev, NULL); static ssize_t uvesafb_show_oem_string(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; if (par->vbe_ib.oem_string_ptr) return snprintf(buf, PAGE_SIZE, "%s\n", (char *)(&par->vbe_ib) + par->vbe_ib.oem_string_ptr); else return 0; } static DEVICE_ATTR(oem_string, S_IRUGO, uvesafb_show_oem_string, NULL); static ssize_t uvesafb_show_nocrtc(struct device *dev, struct device_attribute *attr, char *buf) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; return snprintf(buf, PAGE_SIZE, "%d\n", par->nocrtc); } static ssize_t uvesafb_store_nocrtc(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { struct fb_info *info = platform_get_drvdata(to_platform_device(dev)); struct uvesafb_par *par = info->par; if (count > 0) { if (buf[0] == '0') par->nocrtc = 0; else par->nocrtc = 1; } return count; } static DEVICE_ATTR(nocrtc, S_IRUGO | S_IWUSR, uvesafb_show_nocrtc, uvesafb_store_nocrtc); static struct attribute *uvesafb_dev_attrs[] = { &dev_attr_vbe_version.attr, &dev_attr_vbe_modes.attr, &dev_attr_oem_vendor.attr, &dev_attr_oem_product_name.attr, &dev_attr_oem_product_rev.attr, &dev_attr_oem_string.attr, &dev_attr_nocrtc.attr, NULL, }; static const struct attribute_group uvesafb_dev_attgrp = { .name = NULL, .attrs = uvesafb_dev_attrs, }; static int uvesafb_probe(struct platform_device *dev) { struct fb_info *info; struct vbe_mode_ib *mode = NULL; struct uvesafb_par *par; int err = 0, i; info = framebuffer_alloc(sizeof(*par) + sizeof(u32) * 256, &dev->dev); if (!info) return -ENOMEM; par = info->par; err = uvesafb_vbe_init(info); if (err) { pr_err("vbe_init() failed with %d\n", err); goto out; } info->fbops = &uvesafb_ops; i = uvesafb_vbe_init_mode(info); if (i < 0) { err = -EINVAL; goto out; } else { mode = &par->vbe_modes[i]; } if (fb_alloc_cmap(&info->cmap, 256, 0) < 0) { err = -ENXIO; goto out; } uvesafb_init_info(info, mode); if (!request_region(0x3c0, 32, "uvesafb")) { pr_err("request region 0x3c0-0x3e0 failed\n"); err = -EIO; goto out_mode; } if (!request_mem_region(info->fix.smem_start, info->fix.smem_len, "uvesafb")) { pr_err("cannot reserve video memory at 0x%lx\n", info->fix.smem_start); err = -EIO; goto out_reg; } uvesafb_init_mtrr(info); uvesafb_ioremap(info); if (!info->screen_base) { pr_err("abort, cannot ioremap 0x%x bytes of video memory at 0x%lx\n", info->fix.smem_len, info->fix.smem_start); err = -EIO; goto out_mem; } platform_set_drvdata(dev, info); if (register_framebuffer(info) < 0) { pr_err("failed to register framebuffer device\n"); err = -EINVAL; goto out_unmap; } pr_info("framebuffer at 0x%lx, mapped to 0x%p, using %dk, total %dk\n", info->fix.smem_start, info->screen_base, info->fix.smem_len / 1024, par->vbe_ib.total_memory * 64); fb_info(info, "%s frame buffer device\n", info->fix.id); err = sysfs_create_group(&dev->dev.kobj, &uvesafb_dev_attgrp); if (err != 0) fb_warn(info, "failed to register attributes\n"); return 0; out_unmap: iounmap(info->screen_base); out_mem: release_mem_region(info->fix.smem_start, info->fix.smem_len); out_reg: release_region(0x3c0, 32); out_mode: if (!list_empty(&info->modelist)) fb_destroy_modelist(&info->modelist); fb_destroy_modedb(info->monspecs.modedb); fb_dealloc_cmap(&info->cmap); out: kfree(par->vbe_modes); framebuffer_release(info); return err; } static int uvesafb_remove(struct platform_device *dev) { struct fb_info *info = platform_get_drvdata(dev); if (info) { struct uvesafb_par *par = info->par; sysfs_remove_group(&dev->dev.kobj, &uvesafb_dev_attgrp); unregister_framebuffer(info); release_region(0x3c0, 32); iounmap(info->screen_base); arch_phys_wc_del(par->mtrr_handle); release_mem_region(info->fix.smem_start, info->fix.smem_len); fb_destroy_modedb(info->monspecs.modedb); fb_dealloc_cmap(&info->cmap); kfree(par->vbe_modes); kfree(par->vbe_state_orig); kfree(par->vbe_state_saved); framebuffer_release(info); } return 0; } static struct platform_driver uvesafb_driver = { .probe = uvesafb_probe, .remove = uvesafb_remove, .driver = { .name = "uvesafb", }, }; static struct platform_device *uvesafb_device; #ifndef MODULE static int uvesafb_setup(char *options) { char *this_opt; if (!options || !*options) return 0; while ((this_opt = strsep(&options, ",")) != NULL) { if (!*this_opt) continue; if (!strcmp(this_opt, "redraw")) ypan = 0; else if (!strcmp(this_opt, "ypan")) ypan = 1; else if (!strcmp(this_opt, "ywrap")) ypan = 2; else if (!strcmp(this_opt, "vgapal")) pmi_setpal = 0; else if (!strcmp(this_opt, "pmipal")) pmi_setpal = 1; else if (!strncmp(this_opt, "mtrr:", 5)) mtrr = simple_strtoul(this_opt+5, NULL, 0); else if (!strcmp(this_opt, "nomtrr")) mtrr = 0; else if (!strcmp(this_opt, "nocrtc")) nocrtc = 1; else if (!strcmp(this_opt, "noedid")) noedid = 1; else if (!strcmp(this_opt, "noblank")) blank = 0; else if (!strncmp(this_opt, "vtotal:", 7)) vram_total = simple_strtoul(this_opt + 7, NULL, 0); else if (!strncmp(this_opt, "vremap:", 7)) vram_remap = simple_strtoul(this_opt + 7, NULL, 0); else if (!strncmp(this_opt, "maxhf:", 6)) maxhf = simple_strtoul(this_opt + 6, NULL, 0); else if (!strncmp(this_opt, "maxvf:", 6)) maxvf = simple_strtoul(this_opt + 6, NULL, 0); else if (!strncmp(this_opt, "maxclk:", 7)) maxclk = simple_strtoul(this_opt + 7, NULL, 0); else if (!strncmp(this_opt, "vbemode:", 8)) vbemode = simple_strtoul(this_opt + 8, NULL, 0); else if (this_opt[0] >= '0' && this_opt[0] <= '9') { mode_option = this_opt; } else { pr_warn("unrecognized option %s\n", this_opt); } } if (mtrr != 3 && mtrr != 0) pr_warn("uvesafb: mtrr should be set to 0 or 3; %d is unsupported", mtrr); return 0; } #endif /* !MODULE */ static ssize_t v86d_show(struct device_driver *dev, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", v86d_path); } static ssize_t v86d_store(struct device_driver *dev, const char *buf, size_t count) { strncpy(v86d_path, buf, PATH_MAX); return count; } static DRIVER_ATTR_RW(v86d); static int uvesafb_init(void) { int err; #ifndef MODULE char *option = NULL; if (fb_get_options("uvesafb", &option)) return -ENODEV; uvesafb_setup(option); #endif err = cn_add_callback(&uvesafb_cn_id, "uvesafb", uvesafb_cn_callback); if (err) return err; err = platform_driver_register(&uvesafb_driver); if (!err) { uvesafb_device = platform_device_alloc("uvesafb", 0); if (uvesafb_device) err = platform_device_add(uvesafb_device); else err = -ENOMEM; if (err) { platform_device_put(uvesafb_device); platform_driver_unregister(&uvesafb_driver); cn_del_callback(&uvesafb_cn_id); return err; } err = driver_create_file(&uvesafb_driver.driver, &driver_attr_v86d); if (err) { pr_warn("failed to register attributes\n"); err = 0; } } return err; } module_init(uvesafb_init); static void uvesafb_exit(void) { struct uvesafb_ktask *task; if (v86d_started) { task = uvesafb_prep(); if (task) { task->t.flags = TF_EXIT; uvesafb_exec(task); uvesafb_free(task); } } cn_del_callback(&uvesafb_cn_id); driver_remove_file(&uvesafb_driver.driver, &driver_attr_v86d); platform_device_unregister(uvesafb_device); platform_driver_unregister(&uvesafb_driver); } module_exit(uvesafb_exit); static int param_set_scroll(const char *val, const struct kernel_param *kp) { ypan = 0; if (!strcmp(val, "redraw")) ypan = 0; else if (!strcmp(val, "ypan")) ypan = 1; else if (!strcmp(val, "ywrap")) ypan = 2; else return -EINVAL; return 0; } static const struct kernel_param_ops param_ops_scroll = { .set = param_set_scroll, }; #define param_check_scroll(name, p) __param_check(name, p, void) module_param_named(scroll, ypan, scroll, 0); MODULE_PARM_DESC(scroll, "Scrolling mode, set to 'redraw', 'ypan', or 'ywrap'"); module_param_named(vgapal, pmi_setpal, invbool, 0); MODULE_PARM_DESC(vgapal, "Set palette using VGA registers"); module_param_named(pmipal, pmi_setpal, bool, 0); MODULE_PARM_DESC(pmipal, "Set palette using PMI calls"); module_param(mtrr, uint, 0); MODULE_PARM_DESC(mtrr, "Memory Type Range Registers setting. Use 0 to disable."); module_param(blank, bool, 0); MODULE_PARM_DESC(blank, "Enable hardware blanking"); module_param(nocrtc, bool, 0); MODULE_PARM_DESC(nocrtc, "Ignore CRTC timings when setting modes"); module_param(noedid, bool, 0); MODULE_PARM_DESC(noedid, "Ignore EDID-provided monitor limits when setting modes"); module_param(vram_remap, uint, 0); MODULE_PARM_DESC(vram_remap, "Set amount of video memory to be used [MiB]"); module_param(vram_total, uint, 0); MODULE_PARM_DESC(vram_total, "Set total amount of video memoery [MiB]"); module_param(maxclk, ushort, 0); MODULE_PARM_DESC(maxclk, "Maximum pixelclock [MHz], overrides EDID data"); module_param(maxhf, ushort, 0); MODULE_PARM_DESC(maxhf, "Maximum horizontal frequency [kHz], overrides EDID data"); module_param(maxvf, ushort, 0); MODULE_PARM_DESC(maxvf, "Maximum vertical frequency [Hz], overrides EDID data"); module_param(mode_option, charp, 0); MODULE_PARM_DESC(mode_option, "Specify initial video mode as \"<xres>x<yres>[-<bpp>][@<refresh>]\""); module_param(vbemode, ushort, 0); MODULE_PARM_DESC(vbemode, "VBE mode number to set, overrides the 'mode' option"); module_param_string(v86d, v86d_path, PATH_MAX, 0660); MODULE_PARM_DESC(v86d, "Path to the v86d userspace helper."); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Michal Januszewski <spock@gentoo.org>"); MODULE_DESCRIPTION("Framebuffer driver for VBE2.0+ compliant graphics boards");
./CrossVul/dataset_final_sorted/CWE-190/c/good_222_0
crossvul-cpp_data_bad_402_0
/* * Description: network buf manager * History: yang@haipo.me, 2016/03/16, create */ # include <errno.h> # include <string.h> # include "nw_buf.h" # define NW_BUF_POOL_INIT_SIZE 64 # define NW_CACHE_INIT_SIZE 64 size_t nw_buf_size(nw_buf *buf) { return buf->wpos - buf->rpos; } size_t nw_buf_avail(nw_buf *buf) { return buf->size - buf->wpos; } size_t nw_buf_write(nw_buf *buf, const void *data, size_t len) { size_t available = buf->size - buf->wpos; size_t wlen = len > available ? available : len; memcpy(buf->data + buf->wpos, data, wlen); buf->wpos += wlen; return wlen; } void nw_buf_shift(nw_buf *buf) { if (buf->rpos == buf->wpos) { buf->rpos = buf->wpos = 0; } else if (buf->rpos != 0) { memmove(buf->data, buf->data + buf->rpos, buf->wpos - buf->rpos); buf->wpos -= buf->rpos; buf->rpos = 0; } } nw_buf_pool *nw_buf_pool_create(uint32_t size) { nw_buf_pool *pool = malloc(sizeof(nw_buf_pool)); if (pool == NULL) return NULL; pool->size = size; pool->used = 0; pool->free = 0; pool->free_total = NW_BUF_POOL_INIT_SIZE; pool->free_arr = malloc(pool->free_total * sizeof(nw_buf *)); if (pool->free_arr == NULL) { free(pool); return NULL; } return pool; } nw_buf *nw_buf_alloc(nw_buf_pool *pool) { if (pool->free) { nw_buf *buf = pool->free_arr[--pool->free]; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } nw_buf *buf = malloc(sizeof(nw_buf) + pool->size); if (buf == NULL) return NULL; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } } void nw_buf_pool_release(nw_buf_pool *pool) { for (uint32_t i = 0; i < pool->free; ++i) { free(pool->free_arr[i]); } free(pool->free_arr); free(pool); } nw_buf_list *nw_buf_list_create(nw_buf_pool *pool, uint32_t limit) { nw_buf_list *list = malloc(sizeof(nw_buf_list)); if (list == NULL) return NULL; list->pool = pool; list->count = 0; list->limit = limit; list->head = NULL; list->tail = NULL; return list; } size_t nw_buf_list_write(nw_buf_list *list, const void *data, size_t len) { const void *pos = data; size_t left = len; if (list->tail && nw_buf_avail(list->tail)) { size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } while (left) { if (list->limit && list->count >= list->limit) return len - left; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return len - left; if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } return len; } size_t nw_buf_list_append(nw_buf_list *list, const void *data, size_t len) { if (list->limit && list->count >= list->limit) return 0; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return 0; if (len > buf->size) { nw_buf_free(list->pool, buf); return 0; } nw_buf_write(buf, data, len); if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; return len; } void nw_buf_list_shift(nw_buf_list *list) { if (list->head) { nw_buf *tmp = list->head; list->head = tmp->next; if (list->head == NULL) { list->tail = NULL; } list->count--; nw_buf_free(list->pool, tmp); } } void nw_buf_list_release(nw_buf_list *list) { nw_buf *curr = list->head; nw_buf *next = NULL; while (curr) { next = curr->next; nw_buf_free(list->pool, curr); curr = next; } free(list); } nw_cache *nw_cache_create(uint32_t size) { nw_cache *cache = malloc(sizeof(nw_cache)); if (cache == NULL) return NULL; cache->size = size; cache->used = 0; cache->free = 0; cache->free_total = NW_CACHE_INIT_SIZE; cache->free_arr = malloc(cache->free_total * sizeof(void *)); if (cache->free_arr == NULL) { free(cache); return NULL; } return cache; } void *nw_cache_alloc(nw_cache *cache) { if (cache->free) return cache->free_arr[--cache->free]; return malloc(cache->size); } void nw_cache_free(nw_cache *cache, void *obj) { if (cache->free < cache->free_total) { cache->free_arr[cache->free++] = obj; } else { uint32_t new_free_total = cache->free_total * 2; void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *)); if (new_arr) { cache->free_total = new_free_total; cache->free_arr = new_arr; cache->free_arr[cache->free++] = obj; } else { free(obj); } } } void nw_cache_release(nw_cache *cache) { for (uint32_t i = 0; i < cache->free; ++i) { free(cache->free_arr[i]); } free(cache->free_arr); free(cache); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_402_0
crossvul-cpp_data_good_3179_0
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * undo.c: multi level undo facility * * The saved lines are stored in a list of lists (one for each buffer): * * b_u_oldhead------------------------------------------------+ * | * V * +--------------+ +--------------+ +--------------+ * b_u_newhead--->| u_header | | u_header | | u_header | * | uh_next------>| uh_next------>| uh_next---->NULL * NULL<--------uh_prev |<---------uh_prev |<---------uh_prev | * | uh_entry | | uh_entry | | uh_entry | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ +--------------+ +--------------+ * | u_entry | | u_entry | | u_entry | * | ue_next | | ue_next | | ue_next | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ NULL NULL * | u_entry | * | ue_next | * +--------|-----+ * | * V * etc. * * Each u_entry list contains the information for one undo or redo. * curbuf->b_u_curhead points to the header of the last undo (the next redo), * or is NULL if nothing has been undone (end of the branch). * * For keeping alternate undo/redo branches the uh_alt field is used. Thus at * each point in the list a branch may appear for an alternate to redo. The * uh_seq field is numbered sequentially to be able to find a newer or older * branch. * * +---------------+ +---------------+ * b_u_oldhead --->| u_header | | u_header | * | uh_alt_next ---->| uh_alt_next ----> NULL * NULL <----- uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next | | uh_alt_next | * b_u_newhead --->| uh_alt_prev | | uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * NULL +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next ---->| uh_alt_next | * | uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * etc. etc. * * * All data is allocated and will all be freed when the buffer is unloaded. */ /* Uncomment the next line for including the u_check() function. This warns * for errors in the debug information. */ /* #define U_DEBUG 1 */ #define UH_MAGIC 0x18dade /* value for uh_magic when in use */ #define UE_MAGIC 0xabc123 /* value for ue_magic when in use */ /* Size of buffer used for encryption. */ #define CRYPT_BUF_SIZE 8192 #include "vim.h" /* Structure passed around between functions. * Avoids passing cryptstate_T when encryption not available. */ typedef struct { buf_T *bi_buf; FILE *bi_fp; #ifdef FEAT_CRYPT cryptstate_T *bi_state; char_u *bi_buffer; /* CRYPT_BUF_SIZE, NULL when not buffering */ size_t bi_used; /* bytes written to/read from bi_buffer */ size_t bi_avail; /* bytes available in bi_buffer */ #endif } bufinfo_T; static long get_undolevel(void); static void u_unch_branch(u_header_T *uhp); static u_entry_T *u_get_headentry(void); static void u_getbot(void); static void u_doit(int count); static void u_undoredo(int undo); static void u_undo_end(int did_undo, int absolute); static void u_add_time(char_u *buf, size_t buflen, time_t tt); static void u_freeheader(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freebranch(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentries(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentry(u_entry_T *, long); #ifdef FEAT_PERSISTENT_UNDO static void corruption_error(char *mesg, char_u *file_name); static void u_free_uhp(u_header_T *uhp); static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len); # ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi); # endif static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len); static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len); static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp); static int undo_read_4c(bufinfo_T *bi); static int undo_read_2c(bufinfo_T *bi); static int undo_read_byte(bufinfo_T *bi); static time_t undo_read_time(bufinfo_T *bi); static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size); static char_u *read_string_decrypt(bufinfo_T *bi, int len); static int serialize_header(bufinfo_T *bi, char_u *hash); static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp); static u_header_T *unserialize_uhp(bufinfo_T *bi, char_u *file_name); static int serialize_uep(bufinfo_T *bi, u_entry_T *uep); static u_entry_T *unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name); static void serialize_pos(bufinfo_T *bi, pos_T pos); static void unserialize_pos(bufinfo_T *bi, pos_T *pos); static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); #endif #define U_ALLOC_LINE(size) lalloc((long_u)(size), FALSE) static char_u *u_save_line(linenr_T); /* used in undo_end() to report number of added and deleted lines */ static long u_newcount, u_oldcount; /* * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember * the action that "u" should do. */ static int undo_undoes = FALSE; static int lastmark = 0; #if defined(U_DEBUG) || defined(PROTO) /* * Check the undo structures for being valid. Print a warning when something * looks wrong. */ static int seen_b_u_curhead; static int seen_b_u_newhead; static int header_count; static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) { u_entry_T *uep; if (uhp == NULL) return; ++header_count; if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1) { EMSG("b_u_curhead found twice (looping?)"); return; } if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1) { EMSG("b_u_newhead found twice (looping?)"); return; } if (uhp->uh_magic != UH_MAGIC) EMSG("uh_magic wrong (may be using freed memory)"); else { /* Check pointers back are correct. */ if (uhp->uh_next.ptr != exp_uh_next) { EMSG("uh_next wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_next, uhp->uh_next.ptr); } if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev) { EMSG("uh_alt_prev wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_alt_prev, uhp->uh_alt_prev.ptr); } /* Check the undo tree at this header. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { if (uep->ue_magic != UE_MAGIC) { EMSG("ue_magic wrong (may be using freed memory)"); break; } } /* Check the next alt tree. */ u_check_tree(uhp->uh_alt_next.ptr, uhp->uh_next.ptr, uhp); /* Check the next header in this branch. */ u_check_tree(uhp->uh_prev.ptr, uhp, NULL); } } static void u_check(int newhead_may_be_NULL) { seen_b_u_newhead = 0; seen_b_u_curhead = 0; header_count = 0; u_check_tree(curbuf->b_u_oldhead, NULL, NULL); if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL)) EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0) EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); if (header_count != curbuf->b_u_numhead) { EMSG("b_u_numhead invalid"); smsg((char_u *)"expected: %ld, actual: %ld", (long)header_count, (long)curbuf->b_u_numhead); } } #endif /* * Save the current line for both the "u" and "U" command. * Careful: may trigger autocommands that reload the buffer. * Returns OK or FAIL. */ int u_save_cursor(void) { return (u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + 1))); } /* * Save the lines between "top" and "bot" for both the "u" and "U" command. * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_save(linenr_T top, linenr_T bot) { if (undo_off) return OK; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) return FALSE; /* rely on caller to do error messages */ if (top + 2 == bot) u_saveline((linenr_T)(top + 1)); return (u_savecommon(top, bot, (linenr_T)0, FALSE)); } /* * Save the line "lnum" (used by ":s" and "~" command). * The line is replaced, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savesub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE)); } /* * A new line is inserted before line "lnum" (used by :s command). * The line is inserted, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_inssub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum, lnum + 1, FALSE)); } /* * Save the lines "lnum" - "lnum" + nlines (used by delete command). * The lines are deleted, so the new bottom line is lnum, unless the buffer * becomes empty. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savedel(linenr_T lnum, long nlines) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + nlines, nlines == curbuf->b_ml.ml_line_count ? 2 : lnum, FALSE)); } /* * Return TRUE when undo is allowed. Otherwise give an error message and * return FALSE. */ int undo_allowed(void) { /* Don't allow changes when 'modifiable' is off. */ if (!curbuf->b_p_ma) { EMSG(_(e_modifiable)); return FALSE; } #ifdef HAVE_SANDBOX /* In the sandbox it's not allowed to change the text. */ if (sandbox != 0) { EMSG(_(e_sandbox)); return FALSE; } #endif /* Don't allow changes in the buffer while editing the cmdline. The * caller of getcmdline() may get confused. */ if (textlock != 0) { EMSG(_(e_secure)); return FALSE; } return TRUE; } /* * Get the undolevle value for the current buffer. */ static long get_undolevel(void) { if (curbuf->b_p_ul == NO_LOCAL_UNDOLEVEL) return p_ul; return curbuf->b_p_ul; } /* * Common code for various ways to save text before a change. * "top" is the line above the first changed line. * "bot" is the line below the last changed line. * "newbot" is the new bottom line. Use zero when not known. * "reload" is TRUE when saving for a buffer reload. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savecommon( linenr_T top, linenr_T bot, linenr_T newbot, int reload) { linenr_T lnum; long i; u_header_T *uhp; u_header_T *old_curhead; u_entry_T *uep; u_entry_T *prev_uep; long size; if (!reload) { /* When making changes is not allowed return FAIL. It's a crude way * to make all change commands fail. */ if (!undo_allowed()) return FAIL; #ifdef FEAT_NETBEANS_INTG /* * Netbeans defines areas that cannot be modified. Bail out here when * trying to change text in a guarded area. */ if (netbeans_active()) { if (netbeans_is_guarded(top, bot)) { EMSG(_(e_guarded)); return FAIL; } if (curbuf->b_p_ro) { EMSG(_(e_nbreadonly)); return FAIL; } } #endif #ifdef FEAT_AUTOCMD /* * Saving text for undo means we are going to make a change. Give a * warning for a read-only file before making the change, so that the * FileChangedRO event can replace the buffer with a read-write version * (e.g., obtained from a source control system). */ change_warning(0); if (bot > curbuf->b_ml.ml_line_count + 1) { /* This happens when the FileChangedRO autocommand changes the * file in a way it becomes shorter. */ EMSG(_("E881: Line count changed unexpectedly")); return FAIL; } #endif } #ifdef U_DEBUG u_check(FALSE); #endif size = bot - top - 1; /* * If curbuf->b_u_synced == TRUE make a new header. */ if (curbuf->b_u_synced) { #ifdef FEAT_JUMPLIST /* Need to create new entry in b_changelist. */ curbuf->b_new_change = TRUE; #endif if (get_undolevel() >= 0) { /* * Make a new header entry. Do this first so that we don't mess * up the undo info when out of memory. */ uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) goto nomem; #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif } else uhp = NULL; /* * If we undid more than we redid, move the entry lists before and * including curbuf->b_u_curhead to an alternate branch. */ old_curhead = curbuf->b_u_curhead; if (old_curhead != NULL) { curbuf->b_u_newhead = old_curhead->uh_next.ptr; curbuf->b_u_curhead = NULL; } /* * free headers to keep the size right */ while (curbuf->b_u_numhead > get_undolevel() && curbuf->b_u_oldhead != NULL) { u_header_T *uhfree = curbuf->b_u_oldhead; if (uhfree == old_curhead) /* Can't reconnect the branch, delete all of it. */ u_freebranch(curbuf, uhfree, &old_curhead); else if (uhfree->uh_alt_next.ptr == NULL) /* There is no branch, only free one header. */ u_freeheader(curbuf, uhfree, &old_curhead); else { /* Free the oldest alternate branch as a whole. */ while (uhfree->uh_alt_next.ptr != NULL) uhfree = uhfree->uh_alt_next.ptr; u_freebranch(curbuf, uhfree, &old_curhead); } #ifdef U_DEBUG u_check(TRUE); #endif } if (uhp == NULL) /* no undo at all */ { if (old_curhead != NULL) u_freebranch(curbuf, old_curhead, NULL); curbuf->b_u_synced = FALSE; return OK; } uhp->uh_prev.ptr = NULL; uhp->uh_next.ptr = curbuf->b_u_newhead; uhp->uh_alt_next.ptr = old_curhead; if (old_curhead != NULL) { uhp->uh_alt_prev.ptr = old_curhead->uh_alt_prev.ptr; if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = uhp; old_curhead->uh_alt_prev.ptr = uhp; if (curbuf->b_u_oldhead == old_curhead) curbuf->b_u_oldhead = uhp; } else uhp->uh_alt_prev.ptr = NULL; if (curbuf->b_u_newhead != NULL) curbuf->b_u_newhead->uh_prev.ptr = uhp; uhp->uh_seq = ++curbuf->b_u_seq_last; curbuf->b_u_seq_cur = uhp->uh_seq; uhp->uh_time = vim_time(); uhp->uh_save_nr = 0; curbuf->b_u_time_cur = uhp->uh_time + 1; uhp->uh_walk = 0; uhp->uh_entry = NULL; uhp->uh_getbot_entry = NULL; uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */ #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curwin->w_cursor.coladd > 0) uhp->uh_cursor_vcol = getviscol(); else uhp->uh_cursor_vcol = -1; #endif /* save changed and buffer empty flag for undo */ uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); /* save named marks and Visual marks for undo */ mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); uhp->uh_visual = curbuf->b_visual; curbuf->b_u_newhead = uhp; if (curbuf->b_u_oldhead == NULL) curbuf->b_u_oldhead = uhp; ++curbuf->b_u_numhead; } else { if (get_undolevel() < 0) /* no undo at all */ return OK; /* * When saving a single line, and it has been saved just before, it * doesn't make sense saving it again. Saves a lot of memory when * making lots of changes inside the same line. * This is only possible if the previous change didn't increase or * decrease the number of lines. * Check the ten last changes. More doesn't make sense and takes too * long. */ if (size == 1) { uep = u_get_headentry(); prev_uep = NULL; for (i = 0; i < 10; ++i) { if (uep == NULL) break; /* If lines have been inserted/deleted we give up. * Also when the line was included in a multi-line save. */ if ((curbuf->b_u_newhead->uh_getbot_entry != uep ? (uep->ue_top + uep->ue_size + 1 != (uep->ue_bot == 0 ? curbuf->b_ml.ml_line_count + 1 : uep->ue_bot)) : uep->ue_lcount != curbuf->b_ml.ml_line_count) || (uep->ue_size > 1 && top >= uep->ue_top && top + 2 <= uep->ue_top + uep->ue_size + 1)) break; /* If it's the same line we can skip saving it again. */ if (uep->ue_size == 1 && uep->ue_top == top) { if (i > 0) { /* It's not the last entry: get ue_bot for the last * entry now. Following deleted/inserted lines go to * the re-used entry. */ u_getbot(); curbuf->b_u_synced = FALSE; /* Move the found entry to become the last entry. The * order of undo/redo doesn't matter for the entries * we move it over, since they don't change the line * count and don't include this line. It does matter * for the found entry if the line count is changed by * the executed command. */ prev_uep->ue_next = uep->ue_next; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; } /* The executed command may change the line count. */ if (newbot != 0) uep->ue_bot = newbot; else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } return OK; } prev_uep = uep; uep = uep->ue_next; } } /* find line number for ue_bot for previous u_save() */ u_getbot(); } #if !defined(UNIX) && !defined(WIN32) /* * With Amiga we can't handle big undo's, because * then u_alloc_line would have to allocate a block larger than 32K */ if (size >= 8000) goto nomem; #endif /* * add lines in front of entry list */ uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) goto nomem; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_size = size; uep->ue_top = top; if (newbot != 0) uep->ue_bot = newbot; /* * Use 0 for ue_bot if bot is below last line. * Otherwise we have to compute ue_bot later. */ else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } if (size > 0) { if ((uep->ue_array = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * size)) == NULL) { u_freeentry(uep, 0L); goto nomem; } for (i = 0, lnum = top + 1; i < size; ++i) { fast_breakcheck(); if (got_int) { u_freeentry(uep, i); return FAIL; } if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL) { u_freeentry(uep, i); goto nomem; } } } else uep->ue_array = NULL; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; curbuf->b_u_synced = FALSE; undo_undoes = FALSE; #ifdef U_DEBUG u_check(FALSE); #endif return OK; nomem: msg_silent = 0; /* must display the prompt */ if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE) == 'y') { undo_off = TRUE; /* will be reset when character typed */ return OK; } do_outofmem_msg((long_u)0); return FAIL; } #if defined(FEAT_PERSISTENT_UNDO) || defined(PROTO) # define UF_START_MAGIC "Vim\237UnDo\345" /* magic at start of undofile */ # define UF_START_MAGIC_LEN 9 # define UF_HEADER_MAGIC 0x5fd0 /* magic at start of header */ # define UF_HEADER_END_MAGIC 0xe7aa /* magic after last header */ # define UF_ENTRY_MAGIC 0xf518 /* magic at start of entry */ # define UF_ENTRY_END_MAGIC 0x3581 /* magic after last entry */ # define UF_VERSION 2 /* 2-byte undofile version number */ # define UF_VERSION_CRYPT 0x8002 /* idem, encrypted */ /* extra fields for header */ # define UF_LAST_SAVE_NR 1 /* extra fields for uhp */ # define UHP_SAVE_NR 1 static char_u e_not_open[] = N_("E828: Cannot open undo file for writing: %s"); /* * Compute the hash for the current buffer text into hash[UNDO_HASH_SIZE]. */ void u_compute_hash(char_u *hash) { context_sha256_T ctx; linenr_T lnum; char_u *p; sha256_start(&ctx); for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { p = ml_get(lnum); sha256_update(&ctx, p, (UINT32_T)(STRLEN(p) + 1)); } sha256_finish(&ctx, hash); } /* * Return an allocated string of the full path of the target undofile. * When "reading" is TRUE find the file to read, go over all directories in * 'undodir'. * When "reading" is FALSE use the first name where the directory exists. * Returns NULL when there is no place to write or no file to read. */ char_u * u_get_undo_file_name(char_u *buf_ffname, int reading) { char_u *dirp; char_u dir_name[IOSIZE + 1]; char_u *munged_name = NULL; char_u *undo_file_name = NULL; int dir_len; char_u *p; stat_T st; char_u *ffname = buf_ffname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif if (ffname == NULL) return NULL; #ifdef HAVE_READLINK /* Expand symlink in the file name, so that we put the undo file with the * actual file instead of with the symlink. */ if (resolve_symlink(ffname, fname_buf) == OK) ffname = fname_buf; #endif /* Loop over 'undodir'. When reading find the first file that exists. * When not reading use the first directory that exists or ".". */ dirp = p_udir; while (*dirp != NUL) { dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ","); if (dir_len == 1 && dir_name[0] == '.') { /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ undo_file_name = vim_strnsave(ffname, (int)(STRLEN(ffname) + 5)); if (undo_file_name == NULL) break; p = gettail(undo_file_name); #ifdef VMS /* VMS can not handle more than one dot in the filenames * use "dir/name" -> "dir/_un_name" - add _un_ * at the beginning to keep the extension */ mch_memmove(p + 4, p, STRLEN(p) + 1); mch_memmove(p, "_un_", 4); #else /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ mch_memmove(p + 1, p, STRLEN(p) + 1); *p = '.'; STRCAT(p, ".un~"); #endif } else { dir_name[dir_len] = NUL; if (mch_isdir(dir_name)) { if (munged_name == NULL) { munged_name = vim_strsave(ffname); if (munged_name == NULL) return NULL; for (p = munged_name; *p != NUL; mb_ptr_adv(p)) if (vim_ispathsep(*p)) *p = '%'; } undo_file_name = concat_fnames(dir_name, munged_name, TRUE); } } /* When reading check if the file exists. */ if (undo_file_name != NULL && (!reading || mch_stat((char *)undo_file_name, &st) >= 0)) break; vim_free(undo_file_name); undo_file_name = NULL; } vim_free(munged_name); return undo_file_name; } static void corruption_error(char *mesg, char_u *file_name) { EMSG3(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); } static void u_free_uhp(u_header_T *uhp) { u_entry_T *nuep; u_entry_T *uep; uep = uhp->uh_entry; while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } vim_free(uhp); } /* * Write a sequence of bytes to the undo file. * Buffers and encrypts as needed. * Returns OK or FAIL. */ static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { size_t len_todo = len; char_u *p = ptr; while (bi->bi_used + len_todo >= CRYPT_BUF_SIZE) { size_t n = CRYPT_BUF_SIZE - bi->bi_used; mch_memmove(bi->bi_buffer + bi->bi_used, p, n); len_todo -= n; p += n; bi->bi_used = CRYPT_BUF_SIZE; if (undo_flush(bi) == FAIL) return FAIL; } if (len_todo > 0) { mch_memmove(bi->bi_buffer + bi->bi_used, p, len_todo); bi->bi_used += len_todo; } return OK; } #endif if (fwrite(ptr, len, (size_t)1, bi->bi_fp) != 1) return FAIL; return OK; } #ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi) { if (bi->bi_buffer != NULL && bi->bi_used > 0) { crypt_encode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_used); if (fwrite(bi->bi_buffer, bi->bi_used, (size_t)1, bi->bi_fp) != 1) return FAIL; bi->bi_used = 0; } return OK; } #endif /* * Write "ptr[len]" and crypt the bytes when needed. * Returns OK or FAIL. */ static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT char_u *copy; char_u small_buf[100]; size_t i; if (bi->bi_state != NULL && bi->bi_buffer == NULL) { /* crypting every piece of text separately */ if (len < 100) copy = small_buf; /* no malloc()/free() for short strings */ else { copy = lalloc(len, FALSE); if (copy == NULL) return 0; } crypt_encode(bi->bi_state, ptr, len, copy); i = fwrite(copy, len, (size_t)1, bi->bi_fp); if (copy != small_buf) vim_free(copy); return i == 1 ? OK : FAIL; } #endif return undo_write(bi, ptr, len); } /* * Write a number, MSB first, in "len" bytes. * Must match with undo_read_?c() functions. * Returns OK or FAIL. */ static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len) { char_u buf[8]; int i; int bufi = 0; for (i = len - 1; i >= 0; --i) buf[bufi++] = (char_u)(nr >> (i * 8)); return undo_write(bi, buf, (size_t)len); } /* * Write the pointer to an undo header. Instead of writing the pointer itself * we use the sequence number of the header. This is converted back to * pointers when reading. */ static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp) { undo_write_bytes(bi, (long_u)(uhp != NULL ? uhp->uh_seq : 0), 4); } static int undo_read_4c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[4]; int n; undo_read(bi, buf, (size_t)4); n = ((unsigned)buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; return n; } #endif return get4c(bi->bi_fp); } static int undo_read_2c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[2]; int n; undo_read(bi, buf, (size_t)2); n = (buf[0] << 8) + buf[1]; return n; } #endif return get2c(bi->bi_fp); } static int undo_read_byte(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[1]; undo_read(bi, buf, (size_t)1); return buf[0]; } #endif return getc(bi->bi_fp); } static time_t undo_read_time(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[8]; time_t n = 0; int i; undo_read(bi, buf, (size_t)8); for (i = 0; i < 8; ++i) n = (n << 8) + buf[i]; return n; } #endif return get8ctime(bi->bi_fp); } /* * Read "buffer[size]" from the undo file. * Return OK or FAIL. */ static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { int size_todo = (int)size; char_u *p = buffer; while (size_todo > 0) { size_t n; if (bi->bi_used >= bi->bi_avail) { n = fread(bi->bi_buffer, 1, (size_t)CRYPT_BUF_SIZE, bi->bi_fp); if (n == 0) { /* Error may be checked for only later. Fill with zeros, * so that the reader won't use garbage. */ vim_memset(p, 0, size_todo); return FAIL; } bi->bi_avail = n; bi->bi_used = 0; crypt_decode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_avail); } n = size_todo; if (n > bi->bi_avail - bi->bi_used) n = bi->bi_avail - bi->bi_used; mch_memmove(p, bi->bi_buffer + bi->bi_used, n); bi->bi_used += n; size_todo -= (int)n; p += n; } return OK; } #endif if (fread(buffer, (size_t)size, 1, bi->bi_fp) != 1) return FAIL; return OK; } /* * Read a string of length "len" from "bi->bi_fd". * "len" can be zero to allocate an empty line. * Decrypt the bytes if needed. * Append a NUL. * Returns a pointer to allocated memory or NULL for failure. */ static char_u * read_string_decrypt(bufinfo_T *bi, int len) { char_u *ptr = alloc((unsigned)len + 1); if (ptr != NULL) { if (len > 0 && undo_read(bi, ptr, len) == FAIL) { vim_free(ptr); return NULL; } ptr[len] = NUL; #ifdef FEAT_CRYPT if (bi->bi_state != NULL && bi->bi_buffer == NULL) crypt_decode_inplace(bi->bi_state, ptr, len); #endif } return ptr; } /* * Writes the (not encrypted) header and initializes encryption if needed. */ static int serialize_header(bufinfo_T *bi, char_u *hash) { int len; buf_T *buf = bi->bi_buf; FILE *fp = bi->bi_fp; char_u time_buf[8]; /* Start writing, first the magic marker and undo info version. */ if (fwrite(UF_START_MAGIC, (size_t)UF_START_MAGIC_LEN, (size_t)1, fp) != 1) return FAIL; /* If the buffer is encrypted then all text bytes following will be * encrypted. Numbers and other info is not crypted. */ #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) { char_u *header; int header_len; undo_write_bytes(bi, (long_u)UF_VERSION_CRYPT, 2); bi->bi_state = crypt_create_for_writing(crypt_get_method_nr(buf), buf->b_p_key, &header, &header_len); if (bi->bi_state == NULL) return FAIL; len = (int)fwrite(header, (size_t)header_len, (size_t)1, fp); vim_free(header); if (len != 1) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } if (crypt_whole_undofile(crypt_get_method_nr(buf))) { bi->bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi->bi_buffer == NULL) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } bi->bi_used = 0; } } else #endif undo_write_bytes(bi, (long_u)UF_VERSION, 2); /* Write a hash of the buffer text, so that we can verify it is still the * same when reading the buffer text. */ if (undo_write(bi, hash, (size_t)UNDO_HASH_SIZE) == FAIL) return FAIL; /* buffer-specific data */ undo_write_bytes(bi, (long_u)buf->b_ml.ml_line_count, 4); len = buf->b_u_line_ptr != NULL ? (int)STRLEN(buf->b_u_line_ptr) : 0; undo_write_bytes(bi, (long_u)len, 4); if (len > 0 && fwrite_crypt(bi, buf->b_u_line_ptr, (size_t)len) == FAIL) return FAIL; undo_write_bytes(bi, (long_u)buf->b_u_line_lnum, 4); undo_write_bytes(bi, (long_u)buf->b_u_line_colnr, 4); /* Undo structures header data */ put_header_ptr(bi, buf->b_u_oldhead); put_header_ptr(bi, buf->b_u_newhead); put_header_ptr(bi, buf->b_u_curhead); undo_write_bytes(bi, (long_u)buf->b_u_numhead, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_last, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_cur, 4); time_to_bytes(buf->b_u_time_cur, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UF_LAST_SAVE_NR, 1); undo_write_bytes(bi, (long_u)buf->b_u_save_nr_last, 4); undo_write_bytes(bi, 0, 1); /* end marker */ return OK; } static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp) { int i; u_entry_T *uep; char_u time_buf[8]; if (undo_write_bytes(bi, (long_u)UF_HEADER_MAGIC, 2) == FAIL) return FAIL; put_header_ptr(bi, uhp->uh_next.ptr); put_header_ptr(bi, uhp->uh_prev.ptr); put_header_ptr(bi, uhp->uh_alt_next.ptr); put_header_ptr(bi, uhp->uh_alt_prev.ptr); undo_write_bytes(bi, uhp->uh_seq, 4); serialize_pos(bi, uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)uhp->uh_cursor_vcol, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif undo_write_bytes(bi, (long_u)uhp->uh_flags, 2); /* Assume NMARKS will stay the same. */ for (i = 0; i < NMARKS; ++i) serialize_pos(bi, uhp->uh_namedm[i]); serialize_visualinfo(bi, &uhp->uh_visual); time_to_bytes(uhp->uh_time, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UHP_SAVE_NR, 1); undo_write_bytes(bi, (long_u)uhp->uh_save_nr, 4); undo_write_bytes(bi, 0, 1); /* end marker */ /* Write all the entries. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { undo_write_bytes(bi, (long_u)UF_ENTRY_MAGIC, 2); if (serialize_uep(bi, uep) == FAIL) return FAIL; } undo_write_bytes(bi, (long_u)UF_ENTRY_END_MAGIC, 2); return OK; } static u_header_T * unserialize_uhp(bufinfo_T *bi, char_u *file_name) { u_header_T *uhp; int i; u_entry_T *uep, *last_uep; int c; int error; uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) return NULL; vim_memset(uhp, 0, sizeof(u_header_T)); #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif uhp->uh_next.seq = undo_read_4c(bi); uhp->uh_prev.seq = undo_read_4c(bi); uhp->uh_alt_next.seq = undo_read_4c(bi); uhp->uh_alt_prev.seq = undo_read_4c(bi); uhp->uh_seq = undo_read_4c(bi); if (uhp->uh_seq <= 0) { corruption_error("uh_seq", file_name); vim_free(uhp); return NULL; } unserialize_pos(bi, &uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT uhp->uh_cursor_vcol = undo_read_4c(bi); #else (void)undo_read_4c(bi); #endif uhp->uh_flags = undo_read_2c(bi); for (i = 0; i < NMARKS; ++i) unserialize_pos(bi, &uhp->uh_namedm[i]); unserialize_visualinfo(bi, &uhp->uh_visual); uhp->uh_time = undo_read_time(bi); /* Optional fields. */ for (;;) { int len = undo_read_byte(bi); int what; if (len == 0) break; what = undo_read_byte(bi); switch (what) { case UHP_SAVE_NR: uhp->uh_save_nr = undo_read_4c(bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(bi); } } /* Unserialize the uep list. */ last_uep = NULL; while ((c = undo_read_2c(bi)) == UF_ENTRY_MAGIC) { error = FALSE; uep = unserialize_uep(bi, &error, file_name); if (last_uep == NULL) uhp->uh_entry = uep; else last_uep->ue_next = uep; last_uep = uep; if (uep == NULL || error) { u_free_uhp(uhp); return NULL; } } if (c != UF_ENTRY_END_MAGIC) { corruption_error("entry end", file_name); u_free_uhp(uhp); return NULL; } return uhp; } /* * Serialize "uep". */ static int serialize_uep( bufinfo_T *bi, u_entry_T *uep) { int i; size_t len; undo_write_bytes(bi, (long_u)uep->ue_top, 4); undo_write_bytes(bi, (long_u)uep->ue_bot, 4); undo_write_bytes(bi, (long_u)uep->ue_lcount, 4); undo_write_bytes(bi, (long_u)uep->ue_size, 4); for (i = 0; i < uep->ue_size; ++i) { len = STRLEN(uep->ue_array[i]); if (undo_write_bytes(bi, (long_u)len, 4) == FAIL) return FAIL; if (len > 0 && fwrite_crypt(bi, uep->ue_array[i], len) == FAIL) return FAIL; } return OK; } static u_entry_T * unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name) { int i; u_entry_T *uep; char_u **array = NULL; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = undo_read_4c(bi); uep->ue_bot = undo_read_4c(bi); uep->ue_lcount = undo_read_4c(bi); uep->ue_size = undo_read_4c(bi); if (uep->ue_size > 0) { if (uep->ue_size < LONG_MAX / (int)sizeof(char_u *)) array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = undo_read_4c(bi); if (line_len >= 0) line = read_string_decrypt(bi, line_len); else { line = NULL; corruption_error("line length", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; } /* * Serialize "pos". */ static void serialize_pos(bufinfo_T *bi, pos_T pos) { undo_write_bytes(bi, (long_u)pos.lnum, 4); undo_write_bytes(bi, (long_u)pos.col, 4); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)pos.coladd, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif } /* * Unserialize the pos_T at the current position. */ static void unserialize_pos(bufinfo_T *bi, pos_T *pos) { pos->lnum = undo_read_4c(bi); if (pos->lnum < 0) pos->lnum = 0; pos->col = undo_read_4c(bi); if (pos->col < 0) pos->col = 0; #ifdef FEAT_VIRTUALEDIT pos->coladd = undo_read_4c(bi); if (pos->coladd < 0) pos->coladd = 0; #else (void)undo_read_4c(bi); #endif } /* * Serialize "info". */ static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { serialize_pos(bi, info->vi_start); serialize_pos(bi, info->vi_end); undo_write_bytes(bi, (long_u)info->vi_mode, 4); undo_write_bytes(bi, (long_u)info->vi_curswant, 4); } /* * Unserialize the visualinfo_T at the current position. */ static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { unserialize_pos(bi, &info->vi_start); unserialize_pos(bi, &info->vi_end); info->vi_mode = undo_read_4c(bi); info->vi_curswant = undo_read_4c(bi); } /* * Write the undo tree in an undo file. * When "name" is not NULL, use it as the name of the undo file. * Otherwise use buf->b_ffname to generate the undo file name. * "buf" must never be null, buf->b_ffname is used to obtain the original file * permissions. * "forceit" is TRUE for ":wundo!", FALSE otherwise. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_write_undo( char_u *name, int forceit, buf_T *buf, char_u *hash) { u_header_T *uhp; char_u *file_name; int mark; #ifdef U_DEBUG int headers_written = 0; #endif int fd; FILE *fp = NULL; int perm; int write_ok = FALSE; #ifdef UNIX int st_old_valid = FALSE; stat_T st_old; stat_T st_new; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(buf->b_ffname, FALSE); if (file_name == NULL) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *) _("Cannot write undo file in any directory in 'undodir'")); verbose_leave(); } return; } } else file_name = name; /* * Decide about the permission to use for the undo file. If the buffer * has a name use the permission of the original file. Otherwise only * allow the user to access the undo file. */ perm = 0600; if (buf->b_ffname != NULL) { #ifdef UNIX if (mch_stat((char *)buf->b_ffname, &st_old) >= 0) { perm = st_old.st_mode; st_old_valid = TRUE; } #else perm = mch_getperm(buf->b_ffname); if (perm < 0) perm = 0600; #endif } /* strip any s-bit and executable bit */ perm = perm & 0666; /* If the undo file already exists, verify that it actually is an undo * file, and delete it. */ if (mch_getperm(file_name) >= 0) { if (name == NULL || !forceit) { /* Check we can read it and it's an undo file. */ fd = mch_open((char *)file_name, O_RDONLY|O_EXTRA, 0); if (fd < 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite with undo file, cannot read: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } else { char_u mbuf[UF_START_MAGIC_LEN]; int len; len = read_eintr(fd, mbuf, UF_START_MAGIC_LEN); close(fd); if (len < UF_START_MAGIC_LEN || memcmp(mbuf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite, this is not an undo file: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } } } mch_remove(file_name); } /* If there is no undo information at all, quit here after deleting any * existing undo file. */ if (buf->b_u_numhead == 0 && buf->b_u_line_ptr == NULL) { if (p_verbose > 0) verb_msg((char_u *)_("Skipping undo file write, nothing to undo")); goto theend; } fd = mch_open((char *)file_name, O_CREAT|O_EXTRA|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) { EMSG2(_(e_not_open), file_name); goto theend; } (void)mch_setperm(file_name, perm); if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Writing undo file: %s"), file_name); verbose_leave(); } #ifdef U_DEBUG /* Check there is no problem in undo info before writing. */ u_check(FALSE); #endif #ifdef UNIX /* * Try to set the group of the undo file same as the original file. If * this fails, set the protection bits for the group same as the * protection bits for others. */ if (st_old_valid && mch_stat((char *)file_name, &st_new) >= 0 && st_new.st_gid != st_old.st_gid # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ && fchown(fd, (uid_t)-1, st_old.st_gid) != 0 # endif ) mch_setperm(file_name, (perm & 0707) | ((perm & 07) << 3)); # if defined(HAVE_SELINUX) || defined(HAVE_SMACK) if (buf->b_ffname != NULL) mch_copy_sec(buf->b_ffname, file_name); # endif #endif fp = fdopen(fd, "w"); if (fp == NULL) { EMSG2(_(e_not_open), file_name); close(fd); mch_remove(file_name); goto theend; } /* Undo must be synced. */ u_sync(TRUE); /* * Write the header. Initializes encryption, if enabled. */ bi.bi_buf = buf; bi.bi_fp = fp; if (serialize_header(&bi, hash) == FAIL) goto write_error; /* * Iteratively serialize UHPs and their UEPs from the top down. */ mark = ++lastmark; uhp = buf->b_u_oldhead; while (uhp != NULL) { /* Serialize current UHP if we haven't seen it */ if (uhp->uh_walk != mark) { uhp->uh_walk = mark; #ifdef U_DEBUG ++headers_written; #endif if (serialize_uhp(&bi, uhp) == FAIL) goto write_error; } /* Now walk through the tree - algorithm from undo_time(). */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != mark) uhp = uhp->uh_next.ptr; else if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } if (undo_write_bytes(&bi, (long_u)UF_HEADER_END_MAGIC, 2) == OK) write_ok = TRUE; #ifdef U_DEBUG if (headers_written != buf->b_u_numhead) { EMSGN("Written %ld headers, ...", headers_written); EMSGN("... but numhead is %ld", buf->b_u_numhead); } #endif #ifdef FEAT_CRYPT if (bi.bi_state != NULL && undo_flush(&bi) == FAIL) write_ok = FALSE; #endif write_error: fclose(fp); if (!write_ok) EMSG2(_("E829: write error in undo file: %s"), file_name); #if defined(MACOS_CLASSIC) || defined(WIN3264) /* Copy file attributes; for systems where this can only be done after * closing the file. */ if (buf->b_ffname != NULL) (void)mch_copy_file_attribute(buf->b_ffname, file_name); #endif #ifdef HAVE_ACL if (buf->b_ffname != NULL) { vim_acl_T acl; /* For systems that support ACL: get the ACL from the original file. */ acl = mch_get_acl(buf->b_ffname); mch_set_acl(file_name, acl); mch_free_acl(acl); } #endif theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (file_name != name) vim_free(file_name); } /* * Load the undo tree from an undo file. * If "name" is not NULL use it as the undo file name. This also means being * a bit more verbose. * Otherwise use curbuf->b_ffname to generate the undo file name. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_read_undo(char_u *name, char_u *hash, char_u *orig_name) { char_u *file_name; FILE *fp; long version, str_len; char_u *line_ptr = NULL; linenr_T line_lnum; colnr_T line_colnr; linenr_T line_count; long num_head = 0; long old_header_seq, new_header_seq, cur_header_seq; long seq_last, seq_cur; long last_save_nr = 0; short old_idx = -1, new_idx = -1, cur_idx = -1; long num_read_uhps = 0; time_t seq_time; int i, j; int c; u_header_T *uhp; u_header_T **uhp_table = NULL; char_u read_hash[UNDO_HASH_SIZE]; char_u magic_buf[UF_START_MAGIC_LEN]; #ifdef U_DEBUG int *uhp_table_used; #endif #ifdef UNIX stat_T st_orig; stat_T st_undo; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(curbuf->b_ffname, TRUE); if (file_name == NULL) return; #ifdef UNIX /* For safety we only read an undo file if the owner is equal to the * owner of the text file or equal to the current user. */ if (mch_stat((char *)orig_name, &st_orig) >= 0 && mch_stat((char *)file_name, &st_undo) >= 0 && st_orig.st_uid != st_undo.st_uid && st_undo.st_uid != getuid()) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Not reading undo file, owner differs: %s"), file_name); verbose_leave(); } return; } #endif } else file_name = name; if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Reading undo file: %s"), file_name); verbose_leave(); } fp = mch_fopen((char *)file_name, "r"); if (fp == NULL) { if (name != NULL || p_verbose > 0) EMSG2(_("E822: Cannot open undo file for reading: %s"), file_name); goto error; } bi.bi_buf = curbuf; bi.bi_fp = fp; /* * Read the undo file header. */ if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1 || memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { EMSG2(_("E823: Not an undo file: %s"), file_name); goto error; } version = get2c(fp); if (version == UF_VERSION_CRYPT) { #ifdef FEAT_CRYPT if (*curbuf->b_p_key == NUL) { EMSG2(_("E832: Non-encrypted file has encrypted undo file: %s"), file_name); goto error; } bi.bi_state = crypt_create_from_file(fp, curbuf->b_p_key); if (bi.bi_state == NULL) { EMSG2(_("E826: Undo file decryption failed: %s"), file_name); goto error; } if (crypt_whole_undofile(bi.bi_state->method_nr)) { bi.bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi.bi_buffer == NULL) { crypt_free_state(bi.bi_state); bi.bi_state = NULL; goto error; } bi.bi_avail = 0; bi.bi_used = 0; } #else EMSG2(_("E827: Undo file is encrypted: %s"), file_name); goto error; #endif } else if (version != UF_VERSION) { EMSG2(_("E824: Incompatible undo file: %s"), file_name); goto error; } if (undo_read(&bi, read_hash, (size_t)UNDO_HASH_SIZE) == FAIL) { corruption_error("hash", file_name); goto error; } line_count = (linenr_T)undo_read_4c(&bi); if (memcmp(hash, read_hash, UNDO_HASH_SIZE) != 0 || line_count != curbuf->b_ml.ml_line_count) { if (p_verbose > 0 || name != NULL) { if (name == NULL) verbose_enter(); give_warning((char_u *) _("File contents changed, cannot use undo info"), TRUE); if (name == NULL) verbose_leave(); } goto error; } /* Read undo data for "U" command. */ str_len = undo_read_4c(&bi); if (str_len < 0) goto error; if (str_len > 0) line_ptr = read_string_decrypt(&bi, str_len); line_lnum = (linenr_T)undo_read_4c(&bi); line_colnr = (colnr_T)undo_read_4c(&bi); if (line_lnum < 0 || line_colnr < 0) { corruption_error("line lnum/col", file_name); goto error; } /* Begin general undo data */ old_header_seq = undo_read_4c(&bi); new_header_seq = undo_read_4c(&bi); cur_header_seq = undo_read_4c(&bi); num_head = undo_read_4c(&bi); seq_last = undo_read_4c(&bi); seq_cur = undo_read_4c(&bi); seq_time = undo_read_time(&bi); /* Optional header fields. */ for (;;) { int len = undo_read_byte(&bi); int what; if (len == 0 || len == EOF) break; what = undo_read_byte(&bi); switch (what) { case UF_LAST_SAVE_NR: last_save_nr = undo_read_4c(&bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(&bi); } } /* uhp_table will store the freshly created undo headers we allocate * until we insert them into curbuf. The table remains sorted by the * sequence numbers of the headers. * When there are no headers uhp_table is NULL. */ if (num_head > 0) { if (num_head < LONG_MAX / (long)sizeof(u_header_T *)) uhp_table = (u_header_T **)U_ALLOC_LINE( num_head * sizeof(u_header_T *)); if (uhp_table == NULL) goto error; } while ((c = undo_read_2c(&bi)) == UF_HEADER_MAGIC) { if (num_read_uhps >= num_head) { corruption_error("num_head too small", file_name); goto error; } uhp = unserialize_uhp(&bi, file_name); if (uhp == NULL) goto error; uhp_table[num_read_uhps++] = uhp; } if (num_read_uhps != num_head) { corruption_error("num_head", file_name); goto error; } if (c != UF_HEADER_END_MAGIC) { corruption_error("end marker", file_name); goto error; } #ifdef U_DEBUG uhp_table_used = (int *)alloc_clear( (unsigned)(sizeof(int) * num_head + 1)); # define SET_FLAG(j) ++uhp_table_used[j] #else # define SET_FLAG(j) #endif /* We have put all of the headers into a table. Now we iterate through the * table and swizzle each sequence number we have stored in uh_*_seq into * a pointer corresponding to the header with that sequence number. */ for (i = 0; i < num_head; i++) { uhp = uhp_table[i]; if (uhp == NULL) continue; for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && i != j && uhp_table[i]->uh_seq == uhp_table[j]->uh_seq) { corruption_error("duplicate uh_seq", file_name); goto error; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_next.seq) { uhp->uh_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_prev.seq) { uhp->uh_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_next.seq) { uhp->uh_alt_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_prev.seq) { uhp->uh_alt_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq) { old_idx = i; SET_FLAG(i); } if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq) { new_idx = i; SET_FLAG(i); } if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq) { cur_idx = i; SET_FLAG(i); } } /* Now that we have read the undo info successfully, free the current undo * info and use the info from the file. */ u_blockfree(curbuf); curbuf->b_u_oldhead = old_idx < 0 ? NULL : uhp_table[old_idx]; curbuf->b_u_newhead = new_idx < 0 ? NULL : uhp_table[new_idx]; curbuf->b_u_curhead = cur_idx < 0 ? NULL : uhp_table[cur_idx]; curbuf->b_u_line_ptr = line_ptr; curbuf->b_u_line_lnum = line_lnum; curbuf->b_u_line_colnr = line_colnr; curbuf->b_u_numhead = num_head; curbuf->b_u_seq_last = seq_last; curbuf->b_u_seq_cur = seq_cur; curbuf->b_u_time_cur = seq_time; curbuf->b_u_save_nr_last = last_save_nr; curbuf->b_u_save_nr_cur = last_save_nr; curbuf->b_u_synced = TRUE; vim_free(uhp_table); #ifdef U_DEBUG for (i = 0; i < num_head; ++i) if (uhp_table_used[i] == 0) EMSGN("uhp_table entry %ld not used, leaking memory", i); vim_free(uhp_table_used); u_check(TRUE); #endif if (name != NULL) smsg((char_u *)_("Finished reading undo file %s"), file_name); goto theend; error: vim_free(line_ptr); if (uhp_table != NULL) { for (i = 0; i < num_read_uhps; i++) if (uhp_table[i] != NULL) u_free_uhp(uhp_table[i]); vim_free(uhp_table); } theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (fp != NULL) fclose(fp); if (file_name != name) vim_free(file_name); return; } #endif /* FEAT_PERSISTENT_UNDO */ /* * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible). * If 'cpoptions' does not contain 'u': Always undo. */ void u_undo(int count) { /* * If we get an undo command while executing a macro, we behave like the * original vi. If this happens twice in one macro the result will not * be compatible. */ if (curbuf->b_u_synced == FALSE) { u_sync(TRUE); count = 1; } if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = TRUE; else undo_undoes = !undo_undoes; u_doit(count); } /* * If 'cpoptions' contains 'u': Repeat the previous undo or redo. * If 'cpoptions' does not contain 'u': Always redo. */ void u_redo(int count) { if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = FALSE; u_doit(count); } /* * Undo or redo, depending on 'undo_undoes', 'count' times. */ static void u_doit(int startcount) { int count = startcount; if (!undo_allowed()) return; u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; while (count--) { /* Do the change warning now, so that it triggers FileChangedRO when * needed. This may cause the file to be reloaded, that must happen * before we do anything, because it may change curbuf->b_u_curhead * and more. */ change_warning(0); if (undo_undoes) { if (curbuf->b_u_curhead == NULL) /* first undo */ curbuf->b_u_curhead = curbuf->b_u_newhead; else if (get_undolevel() > 0) /* multi level undo */ /* get next undo */ curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next.ptr; /* nothing to undo */ if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL) { /* stick curbuf->b_u_curhead at end */ curbuf->b_u_curhead = curbuf->b_u_oldhead; beep_flush(); if (count == startcount - 1) { MSG(_("Already at oldest change")); return; } break; } u_undoredo(TRUE); } else { if (curbuf->b_u_curhead == NULL || get_undolevel() <= 0) { beep_flush(); /* nothing to redo */ if (count == startcount - 1) { MSG(_("Already at newest change")); return; } break; } u_undoredo(FALSE); /* Advance for next redo. Set "newhead" when at the end of the * redoable changes. */ if (curbuf->b_u_curhead->uh_prev.ptr == NULL) curbuf->b_u_newhead = curbuf->b_u_curhead; curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev.ptr; } } u_undo_end(undo_undoes, FALSE); } /* * Undo or redo over the timeline. * When "step" is negative go back in time, otherwise goes forward in time. * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as * seconds. * When "file" is TRUE use "step" as a number of file writes. * When "absolute" is TRUE use "step" as the sequence number to jump to. * "sec" must be FALSE then. */ void undo_time( long step, int sec, int file, int absolute) { long target; long closest; long closest_start; long closest_seq = 0; long val; u_header_T *uhp; u_header_T *last; int mark; int nomark; int round; int dosec = sec; int dofile = file; int above = FALSE; int did_undo = TRUE; /* First make sure the current undoable change is synced. */ if (curbuf->b_u_synced == FALSE) u_sync(TRUE); u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; /* "target" is the node below which we want to be. * Init "closest" to a value we can't reach. */ if (absolute) { if (step == 0) { /* target 0 does not exist, got to 1 and above it. */ target = 1; above = TRUE; } else target = step; closest = -1; } else { if (dosec) target = (long)(curbuf->b_u_time_cur) + step; else if (dofile) { if (step < 0) { /* Going back to a previous write. If there were changes after * the last write, count that as moving one file-write, so * that ":earlier 1f" undoes all changes since the last save. */ uhp = curbuf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = curbuf->b_u_newhead; if (uhp != NULL && uhp->uh_save_nr != 0) /* "uh_save_nr" was set in the last block, that means * there were no changes since the last write */ target = curbuf->b_u_save_nr_cur + step; else /* count the changes since the last write as one step */ target = curbuf->b_u_save_nr_cur + step + 1; if (target <= 0) /* Go to before first write: before the oldest change. Use * the sequence number for that. */ dofile = FALSE; } else { /* Moving forward to a newer write. */ target = curbuf->b_u_save_nr_cur + step; if (target > curbuf->b_u_save_nr_last) { /* Go to after last write: after the latest change. Use * the sequence number for that. */ target = curbuf->b_u_seq_last + 1; dofile = FALSE; } } } else target = curbuf->b_u_seq_cur + step; if (step < 0) { if (target < 0) target = 0; closest = -1; } else { if (dosec) closest = (long)(vim_time() + 1); else if (dofile) closest = curbuf->b_u_save_nr_last + 2; else closest = curbuf->b_u_seq_last + 2; if (target >= closest) target = closest - 1; } } closest_start = closest; closest_seq = curbuf->b_u_seq_cur; /* * May do this twice: * 1. Search for "target", update "closest" to the best match found. * 2. If "target" not found search for "closest". * * When using the closest time we use the sequence number in the second * round, because there may be several entries with the same time. */ for (round = 1; round <= 2; ++round) { /* Find the path from the current state to where we want to go. The * desired state can be anywhere in the undo tree, need to go all over * it. We put "nomark" in uh_walk where we have been without success, * "mark" where it could possibly be. */ mark = ++lastmark; nomark = ++lastmark; if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */ uhp = curbuf->b_u_newhead; else uhp = curbuf->b_u_curhead; while (uhp != NULL) { uhp->uh_walk = mark; if (dosec) val = (long)(uhp->uh_time); else if (dofile) val = uhp->uh_save_nr; else val = uhp->uh_seq; if (round == 1 && !(dofile && val == 0)) { /* Remember the header that is closest to the target. * It must be at least in the right direction (checked with * "b_u_seq_cur"). When the timestamp is equal find the * highest/lowest sequence number. */ if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur : uhp->uh_seq > curbuf->b_u_seq_cur) && ((dosec && val == closest) ? (step < 0 ? uhp->uh_seq < closest_seq : uhp->uh_seq > closest_seq) : closest == closest_start || (val > target ? (closest > target ? val - target <= closest - target : val - target <= target - closest) : (closest > target ? target - val <= closest - target : target - val <= target - closest)))) { closest = val; closest_seq = uhp->uh_seq; } } /* Quit searching when we found a match. But when searching for a * time we need to continue looking for the best uh_seq. */ if (target == val && !dosec) { target = uhp->uh_seq; break; } /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { /* If still at the start we don't go through this change. */ if (uhp == curbuf->b_u_curhead) uhp->uh_walk = nomark; uhp = uhp->uh_next.ptr; } else { /* need to backtrack; mark this node as useless */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } } if (uhp != NULL) /* found it */ break; if (absolute) { EMSGN(_("E830: Undo number %ld not found"), step); return; } if (closest == closest_start) { if (step < 0) MSG(_("Already at oldest change")); else MSG(_("Already at newest change")); return; } target = closest_seq; dosec = FALSE; dofile = FALSE; if (step < 0) above = TRUE; /* stop above the header */ } /* If we found it: Follow the path to go to where we want to be. */ if (uhp != NULL) { /* * First go up the tree as much as needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) uhp = curbuf->b_u_newhead; else uhp = uhp->uh_next.ptr; if (uhp == NULL || uhp->uh_walk != mark || (uhp->uh_seq == target && !above)) break; curbuf->b_u_curhead = uhp; u_undoredo(TRUE); uhp->uh_walk = nomark; /* don't go back down here */ } /* * And now go down the tree (redo), branching off where needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) break; /* Go back to the first branch with a mark. */ while (uhp->uh_alt_prev.ptr != NULL && uhp->uh_alt_prev.ptr->uh_walk == mark) uhp = uhp->uh_alt_prev.ptr; /* Find the last branch with a mark, that's the one. */ last = uhp; while (last->uh_alt_next.ptr != NULL && last->uh_alt_next.ptr->uh_walk == mark) last = last->uh_alt_next.ptr; if (last != uhp) { /* Make the used branch the first entry in the list of * alternatives to make "u" and CTRL-R take this branch. */ while (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; if (last->uh_alt_next.ptr != NULL) last->uh_alt_next.ptr->uh_alt_prev.ptr = last->uh_alt_prev.ptr; last->uh_alt_prev.ptr->uh_alt_next.ptr = last->uh_alt_next.ptr; last->uh_alt_prev.ptr = NULL; last->uh_alt_next.ptr = uhp; uhp->uh_alt_prev.ptr = last; if (curbuf->b_u_oldhead == uhp) curbuf->b_u_oldhead = last; uhp = last; if (uhp->uh_next.ptr != NULL) uhp->uh_next.ptr->uh_prev.ptr = uhp; } curbuf->b_u_curhead = uhp; if (uhp->uh_walk != mark) break; /* must have reached the target */ /* Stop when going backwards in time and didn't find the exact * header we were looking for. */ if (uhp->uh_seq == target && above) { curbuf->b_u_seq_cur = target - 1; break; } u_undoredo(FALSE); /* Advance "curhead" to below the header we last used. If it * becomes NULL then we need to set "newhead" to this leaf. */ if (uhp->uh_prev.ptr == NULL) curbuf->b_u_newhead = uhp; curbuf->b_u_curhead = uhp->uh_prev.ptr; did_undo = FALSE; if (uhp->uh_seq == target) /* found it! */ break; uhp = uhp->uh_prev.ptr; if (uhp == NULL || uhp->uh_walk != mark) { /* Need to redo more but can't find it... */ internal_error("undo_time()"); break; } } } u_undo_end(did_undo, absolute); } /* * u_undoredo: common code for undo and redo * * The lines in the file are replaced by the lines in the entry list at * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry * list for the next undo/redo. * * When "undo" is TRUE we go up in the tree, when FALSE we go down. */ static void u_undoredo(int undo) { char_u **newarray = NULL; linenr_T oldsize; linenr_T newsize; linenr_T top, bot; linenr_T lnum; linenr_T newlnum = MAXLNUM; long i; u_entry_T *uep, *nuep; u_entry_T *newlist = NULL; int old_flags; int new_flags; pos_T namedm[NMARKS]; visualinfo_T visualinfo; int empty_buffer; /* buffer became empty */ u_header_T *curhead = curbuf->b_u_curhead; #ifdef FEAT_AUTOCMD /* Don't want autocommands using the undo structures here, they are * invalid till the end. */ block_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif old_flags = curhead->uh_flags; new_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); setpcmark(); /* * save marks before undo/redo */ mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); visualinfo = curbuf->b_visual; curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count; curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = 0; curbuf->b_op_end.col = 0; for (uep = curhead->uh_entry; uep != NULL; uep = nuep) { top = uep->ue_top; bot = uep->ue_bot; if (bot == 0) bot = curbuf->b_ml.ml_line_count + 1; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) { #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif IEMSG(_("E438: u_undo: line numbers wrong")); changed(); /* don't want UNCHANGED now */ return; } oldsize = bot - top - 1; /* number of lines before undo */ newsize = uep->ue_size; /* number of lines after undo */ if (top < newlnum) { /* If the saved cursor is somewhere in this undo block, move it to * the remembered position. Makes "gwap" put the cursor back * where it was. */ lnum = curhead->uh_cursor.lnum; if (lnum >= top && lnum <= top + newsize + 1) { curwin->w_cursor = curhead->uh_cursor; newlnum = curwin->w_cursor.lnum - 1; } else { /* Use the first line that actually changed. Avoids that * undoing auto-formatting puts the cursor in the previous * line. */ for (i = 0; i < newsize && i < oldsize; ++i) if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0) break; if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL) { newlnum = top; curwin->w_cursor.lnum = newlnum + 1; } else if (i < newsize) { newlnum = top + i; curwin->w_cursor.lnum = newlnum + 1; } } } empty_buffer = FALSE; /* delete the lines between top and bot and save them in newarray */ if (oldsize > 0) { if ((newarray = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * oldsize)) == NULL) { do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize)); /* * We have messed up the entry list, repair is impossible. * we have to free the rest of the list. */ while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } break; } /* delete backwards, it goes faster in most cases */ for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum) { /* what can we do when we run out of memory? */ if ((newarray[i] = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); /* remember we deleted the last line in the buffer, and a * dummy empty line will be inserted */ if (curbuf->b_ml.ml_line_count == 1) empty_buffer = TRUE; ml_delete(lnum, FALSE); } } else newarray = NULL; /* insert the lines in u_array between top and bot */ if (newsize) { for (lnum = top, i = 0; i < newsize; ++i, ++lnum) { /* * If the file is empty, there is an empty line 1 that we * should get rid of, by replacing it with the new line */ if (empty_buffer && lnum == 0) ml_replace((linenr_T)1, uep->ue_array[i], TRUE); else ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE); vim_free(uep->ue_array[i]); } vim_free((char_u *)uep->ue_array); } /* adjust marks */ if (oldsize != newsize) { mark_adjust(top + 1, top + oldsize, (long)MAXLNUM, (long)newsize - (long)oldsize); if (curbuf->b_op_start.lnum > top + oldsize) curbuf->b_op_start.lnum += newsize - oldsize; if (curbuf->b_op_end.lnum > top + oldsize) curbuf->b_op_end.lnum += newsize - oldsize; } changed_lines(top + 1, 0, bot, newsize - oldsize); /* set '[ and '] mark */ if (top + 1 < curbuf->b_op_start.lnum) curbuf->b_op_start.lnum = top + 1; if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + 1; else if (top + newsize > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + newsize; u_newcount += newsize; u_oldcount += oldsize; uep->ue_size = oldsize; uep->ue_array = newarray; uep->ue_bot = top + newsize + 1; /* * insert this entry in front of the new entry list */ nuep = uep->ue_next; uep->ue_next = newlist; newlist = uep; } curhead->uh_entry = newlist; curhead->uh_flags = new_flags; if ((old_flags & UH_EMPTYBUF) && bufempty()) curbuf->b_ml.ml_flags |= ML_EMPTY; if (old_flags & UH_CHANGED) changed(); else #ifdef FEAT_NETBEANS_INTG /* per netbeans undo rules, keep it as modified */ if (!isNetbeansModified(curbuf)) #endif unchanged(curbuf, FALSE); /* * restore marks from before undo/redo */ for (i = 0; i < NMARKS; ++i) { if (curhead->uh_namedm[i].lnum != 0) curbuf->b_namedm[i] = curhead->uh_namedm[i]; if (namedm[i].lnum != 0) curhead->uh_namedm[i] = namedm[i]; else curhead->uh_namedm[i].lnum = 0; } if (curhead->uh_visual.vi_start.lnum != 0) { curbuf->b_visual = curhead->uh_visual; curhead->uh_visual = visualinfo; } /* * If the cursor is only off by one line, put it at the same position as * before starting the change (for the "o" command). * Otherwise the cursor should go to the first undone line. */ if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum && curwin->w_cursor.lnum > 1) --curwin->w_cursor.lnum; if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count) { if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = curhead->uh_cursor.col; #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curhead->uh_cursor_vcol >= 0) coladvance((colnr_T)curhead->uh_cursor_vcol); else curwin->w_cursor.coladd = 0; #endif } else beginline(BL_SOL | BL_FIX); } else { /* We get here with the current cursor line being past the end (eg * after adding lines at the end of the file, and then undoing it). * check_cursor() will move the cursor to the last line. Move it to * the first column here. */ curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif } /* Make sure the cursor is on an existing line and column. */ check_cursor(); /* Remember where we are for "g-" and ":earlier 10s". */ curbuf->b_u_seq_cur = curhead->uh_seq; if (undo) /* We are below the previous undo. However, to make ":earlier 1s" * work we compute this as being just above the just undone change. */ --curbuf->b_u_seq_cur; /* Remember where we are for ":earlier 1f" and ":later 1f". */ if (curhead->uh_save_nr != 0) { if (undo) curbuf->b_u_save_nr_cur = curhead->uh_save_nr - 1; else curbuf->b_u_save_nr_cur = curhead->uh_save_nr; } /* The timestamp can be the same for multiple changes, just use the one of * the undone/redone change. */ curbuf->b_u_time_cur = curhead->uh_time; #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif } /* * If we deleted or added lines, report the number of less/more lines. * Otherwise, report the number of changes (this may be incorrect * in some cases, but it's better than nothing). */ static void u_undo_end( int did_undo, /* just did an undo */ int absolute) /* used ":undo N" */ { char *msgstr; u_header_T *uhp; char_u msgbuf[80]; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_UNDO) && KeyTyped) foldOpenCursor(); #endif if (global_busy /* no messages now, wait until global is finished */ || !messaging()) /* 'lazyredraw' set, don't do messages now */ return; if (curbuf->b_ml.ml_flags & ML_EMPTY) --u_newcount; u_oldcount -= u_newcount; if (u_oldcount == -1) msgstr = N_("more line"); else if (u_oldcount < 0) msgstr = N_("more lines"); else if (u_oldcount == 1) msgstr = N_("line less"); else if (u_oldcount > 1) msgstr = N_("fewer lines"); else { u_oldcount = u_newcount; if (u_newcount == 1) msgstr = N_("change"); else msgstr = N_("changes"); } if (curbuf->b_u_curhead != NULL) { /* For ":undo N" we prefer a "after #N" message. */ if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL) { uhp = curbuf->b_u_curhead->uh_next.ptr; did_undo = FALSE; } else if (did_undo) uhp = curbuf->b_u_curhead; else uhp = curbuf->b_u_curhead->uh_next.ptr; } else uhp = curbuf->b_u_newhead; if (uhp == NULL) *msgbuf = NUL; else u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time); #ifdef FEAT_CONCEAL { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == curbuf && wp->w_p_cole > 0) redraw_win_later(wp, NOT_VALID); } } #endif smsg((char_u *)_("%ld %s; %s #%ld %s"), u_oldcount < 0 ? -u_oldcount : u_oldcount, _(msgstr), did_undo ? _("before") : _("after"), uhp == NULL ? 0L : uhp->uh_seq, msgbuf); } /* * u_sync: stop adding to the current entry list */ void u_sync( int force) /* Also sync when no_u_sync is set. */ { /* Skip it when already synced or syncing is disabled. */ if (curbuf->b_u_synced || (!force && no_u_sync > 0)) return; #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) if (im_is_preediting()) return; /* XIM is busy, don't break an undo sequence */ #endif if (get_undolevel() < 0) curbuf->b_u_synced = TRUE; /* no entries, nothing to do */ else { u_getbot(); /* compute ue_bot of previous u_save */ curbuf->b_u_curhead = NULL; } } /* * ":undolist": List the leafs of the undo tree */ void ex_undolist(exarg_T *eap UNUSED) { garray_T ga; u_header_T *uhp; int mark; int nomark; int changes = 1; int i; /* * 1: walk the tree to find all leafs, put the info in "ga". * 2: sort the lines * 3: display the list */ mark = ++lastmark; nomark = ++lastmark; ga_init2(&ga, (int)sizeof(char *), 20); uhp = curbuf->b_u_oldhead; while (uhp != NULL) { if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark && uhp->uh_walk != mark) { if (ga_grow(&ga, 1) == FAIL) break; vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ", uhp->uh_seq, changes); u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time); if (uhp->uh_save_nr > 0) { while (STRLEN(IObuff) < 33) STRCAT(IObuff, " "); vim_snprintf_add((char *)IObuff, IOSIZE, " %3ld", uhp->uh_save_nr); } ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff); } uhp->uh_walk = mark; /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) { uhp = uhp->uh_prev.ptr; ++changes; } /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { uhp = uhp->uh_next.ptr; --changes; } else { /* need to backtrack; mark this node as done */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else { uhp = uhp->uh_next.ptr; --changes; } } } if (ga.ga_len == 0) MSG(_("Nothing to undo")); else { sort_strings((char_u **)ga.ga_data, ga.ga_len); msg_start(); msg_puts_attr((char_u *)_("number changes when saved"), hl_attr(HLF_T)); for (i = 0; i < ga.ga_len && !got_int; ++i) { msg_putchar('\n'); if (got_int) break; msg_puts(((char_u **)ga.ga_data)[i]); } msg_end(); ga_clear_strings(&ga); } } /* * Put the timestamp of an undo header in "buf[buflen]" in a nice format. */ static void u_add_time(char_u *buf, size_t buflen, time_t tt) { #ifdef HAVE_STRFTIME struct tm *curtime; if (vim_time() - tt >= 100) { curtime = localtime(&tt); if (vim_time() - tt < (60L * 60L * 12L)) /* within 12 hours */ (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime); else /* longer ago */ (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime); } else #endif vim_snprintf((char *)buf, buflen, _("%ld seconds ago"), (long)(vim_time() - tt)); } /* * ":undojoin": continue adding to the last entry list */ void ex_undojoin(exarg_T *eap UNUSED) { if (curbuf->b_u_newhead == NULL) return; /* nothing changed before */ if (curbuf->b_u_curhead != NULL) { EMSG(_("E790: undojoin is not allowed after undo")); return; } if (!curbuf->b_u_synced) return; /* already unsynced */ if (get_undolevel() < 0) return; /* no entries, nothing to do */ else /* Append next change to the last entry */ curbuf->b_u_synced = FALSE; } /* * Called after writing or reloading the file and setting b_changed to FALSE. * Now an undo means that the buffer is modified. */ void u_unchanged(buf_T *buf) { u_unch_branch(buf->b_u_oldhead); buf->b_did_warn = FALSE; } /* * After reloading a buffer which was saved for 'undoreload': Find the first * line that was changed and set the cursor there. */ void u_find_first_changed(void) { u_header_T *uhp = curbuf->b_u_newhead; u_entry_T *uep; linenr_T lnum; if (curbuf->b_u_curhead != NULL || uhp == NULL) return; /* undid something in an autocmd? */ /* Check that the last undo block was for the whole file. */ uep = uhp->uh_entry; if (uep->ue_top != 0 || uep->ue_bot != 0) return; for (lnum = 1; lnum < curbuf->b_ml.ml_line_count && lnum <= uep->ue_size; ++lnum) if (STRCMP(ml_get_buf(curbuf, lnum, FALSE), uep->ue_array[lnum - 1]) != 0) { clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; return; } if (curbuf->b_ml.ml_line_count != uep->ue_size) { /* lines added or deleted at the end, put the cursor there */ clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; } } /* * Increase the write count, store it in the last undo header, what would be * used for "u". */ void u_update_save_nr(buf_T *buf) { u_header_T *uhp; ++buf->b_u_save_nr_last; buf->b_u_save_nr_cur = buf->b_u_save_nr_last; uhp = buf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = buf->b_u_newhead; if (uhp != NULL) uhp->uh_save_nr = buf->b_u_save_nr_last; } static void u_unch_branch(u_header_T *uhp) { u_header_T *uh; for (uh = uhp; uh != NULL; uh = uh->uh_prev.ptr) { uh->uh_flags |= UH_CHANGED; if (uh->uh_alt_next.ptr != NULL) u_unch_branch(uh->uh_alt_next.ptr); /* recursive */ } } /* * Get pointer to last added entry. * If it's not valid, give an error message and return NULL. */ static u_entry_T * u_get_headentry(void) { if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL) { IEMSG(_("E439: undo list corrupt")); return NULL; } return curbuf->b_u_newhead->uh_entry; } /* * u_getbot(): compute the line number of the previous u_save * It is called only when b_u_synced is FALSE. */ static void u_getbot(void) { u_entry_T *uep; linenr_T extra; uep = u_get_headentry(); /* check for corrupt undo list */ if (uep == NULL) return; uep = curbuf->b_u_newhead->uh_getbot_entry; if (uep != NULL) { /* * the new ue_bot is computed from the number of lines that has been * inserted (0 - deleted) since calling u_save. This is equal to the * old line count subtracted from the current line count. */ extra = curbuf->b_ml.ml_line_count - uep->ue_lcount; uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra; if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count) { IEMSG(_("E440: undo line missing")); uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will * get all the old lines back * without deleting the current * ones */ } curbuf->b_u_newhead->uh_getbot_entry = NULL; } curbuf->b_u_synced = TRUE; } /* * Free one header "uhp" and its entry list and adjust the pointers. */ static void u_freeheader( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *uhap; /* When there is an alternate redo list free that branch completely, * because we can never go there. */ if (uhp->uh_alt_next.ptr != NULL) u_freebranch(buf, uhp->uh_alt_next.ptr, uhpp); if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; /* Update the links in the list to remove the header. */ if (uhp->uh_next.ptr == NULL) buf->b_u_oldhead = uhp->uh_prev.ptr; else uhp->uh_next.ptr->uh_prev.ptr = uhp->uh_prev.ptr; if (uhp->uh_prev.ptr == NULL) buf->b_u_newhead = uhp->uh_next.ptr; else for (uhap = uhp->uh_prev.ptr; uhap != NULL; uhap = uhap->uh_alt_next.ptr) uhap->uh_next.ptr = uhp->uh_next.ptr; u_freeentries(buf, uhp, uhpp); } /* * Free an alternate branch and any following alternate branches. */ static void u_freebranch( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *tofree, *next; /* If this is the top branch we may need to use u_freeheader() to update * all the pointers. */ if (uhp == buf->b_u_oldhead) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, uhpp); return; } if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; next = uhp; while (next != NULL) { tofree = next; if (tofree->uh_alt_next.ptr != NULL) u_freebranch(buf, tofree->uh_alt_next.ptr, uhpp); /* recursive */ next = tofree->uh_prev.ptr; u_freeentries(buf, tofree, uhpp); } } /* * Free all the undo entries for one header and the header itself. * This means that "uhp" is invalid when returning. */ static void u_freeentries( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_entry_T *uep, *nuep; /* Check for pointers to the header that become invalid now. */ if (buf->b_u_curhead == uhp) buf->b_u_curhead = NULL; if (buf->b_u_newhead == uhp) buf->b_u_newhead = NULL; /* freeing the newest entry */ if (uhpp != NULL && uhp == *uhpp) *uhpp = NULL; for (uep = uhp->uh_entry; uep != NULL; uep = nuep) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); } #ifdef U_DEBUG uhp->uh_magic = 0; #endif vim_free((char_u *)uhp); --buf->b_u_numhead; } /* * free entry 'uep' and 'n' lines in uep->ue_array[] */ static void u_freeentry(u_entry_T *uep, long n) { while (n > 0) vim_free(uep->ue_array[--n]); vim_free((char_u *)uep->ue_array); #ifdef U_DEBUG uep->ue_magic = 0; #endif vim_free((char_u *)uep); } /* * invalidate the undo buffer; called when storage has already been released */ void u_clearall(buf_T *buf) { buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL; buf->b_u_synced = TRUE; buf->b_u_numhead = 0; buf->b_u_line_ptr = NULL; buf->b_u_line_lnum = 0; } /* * save the line "lnum" for the "U" command */ void u_saveline(linenr_T lnum) { if (lnum == curbuf->b_u_line_lnum) /* line is already saved */ return; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */ return; u_clearline(); curbuf->b_u_line_lnum = lnum; if (curwin->w_cursor.lnum == lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; else curbuf->b_u_line_colnr = 0; if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); } /* * clear the line saved for the "U" command * (this is used externally for crossing a line while in insert mode) */ void u_clearline(void) { if (curbuf->b_u_line_ptr != NULL) { vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = NULL; curbuf->b_u_line_lnum = 0; } } /* * Implementation of the "U" command. * Differentiation from vi: "U" can be undone with the next "U". * We also allow the cursor to be in another line. * Careful: may trigger autocommands that reload the buffer. */ void u_undoline(void) { colnr_T t; char_u *oldp; if (undo_off) return; if (curbuf->b_u_line_ptr == NULL || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count) { beep_flush(); return; } /* first save the line for the 'u' command */ if (u_savecommon(curbuf->b_u_line_lnum - 1, curbuf->b_u_line_lnum + 1, (linenr_T)0, FALSE) == FAIL) return; oldp = u_save_line(curbuf->b_u_line_lnum); if (oldp == NULL) { do_outofmem_msg((long_u)0); return; } ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE); changed_bytes(curbuf->b_u_line_lnum, 0); vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = oldp; t = curbuf->b_u_line_colnr; if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; curwin->w_cursor.col = t; curwin->w_cursor.lnum = curbuf->b_u_line_lnum; check_cursor_col(); } /* * Free all allocated memory blocks for the buffer 'buf'. */ void u_blockfree(buf_T *buf) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, NULL); vim_free(buf->b_u_line_ptr); } /* * u_save_line(): allocate memory and copy line 'lnum' into it. * Returns NULL when out of memory. */ static char_u * u_save_line(linenr_T lnum) { return vim_strsave(ml_get(lnum)); } /* * Check if the 'modified' flag is set, or 'ff' has changed (only need to * check the first character, because it can only be "dos", "unix" or "mac"). * "nofile" and "scratch" type buffers are considered to always be unchanged. */ int bufIsChanged(buf_T *buf) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(buf) && #endif (buf->b_changed || file_ff_differs(buf, TRUE)); } int curbufIsChanged(void) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(curbuf) && #endif (curbuf->b_changed || file_ff_differs(curbuf, TRUE)); } #if defined(FEAT_EVAL) || defined(PROTO) /* * For undotree(): Append the list of undo blocks at "first_uhp" to "list". * Recursive. */ void u_eval_tree(u_header_T *first_uhp, list_T *list) { u_header_T *uhp = first_uhp; dict_T *dict; while (uhp != NULL) { dict = dict_alloc(); if (dict == NULL) return; dict_add_nr_str(dict, "seq", uhp->uh_seq, NULL); dict_add_nr_str(dict, "time", (long)uhp->uh_time, NULL); if (uhp == curbuf->b_u_newhead) dict_add_nr_str(dict, "newhead", 1, NULL); if (uhp == curbuf->b_u_curhead) dict_add_nr_str(dict, "curhead", 1, NULL); if (uhp->uh_save_nr > 0) dict_add_nr_str(dict, "save", uhp->uh_save_nr, NULL); if (uhp->uh_alt_next.ptr != NULL) { list_T *alt_list = list_alloc(); if (alt_list != NULL) { /* Recursive call to add alternate undo tree. */ u_eval_tree(uhp->uh_alt_next.ptr, alt_list); dict_add_list(dict, "alt", alt_list); } } list_append_dict(list, dict); uhp = uhp->uh_prev.ptr; } } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_3179_0
crossvul-cpp_data_good_664_0
/* * 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. */ #include "index.h" #include <stddef.h> #include "repository.h" #include "tree.h" #include "tree-cache.h" #include "hash.h" #include "iterator.h" #include "pathspec.h" #include "ignore.h" #include "blob.h" #include "idxmap.h" #include "diff.h" #include "varint.h" #include "git2/odb.h" #include "git2/oid.h" #include "git2/blob.h" #include "git2/config.h" #include "git2/sys/index.h" #define INSERT_IN_MAP_EX(idx, map, e, err) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_insert((khash_t(idxicase) *) (map), (e), (e), (err)); \ else \ git_idxmap_insert((map), (e), (e), (err)); \ } while (0) #define INSERT_IN_MAP(idx, e, err) INSERT_IN_MAP_EX(idx, (idx)->entries_map, e, err) #define LOOKUP_IN_MAP(p, idx, k) do { \ if ((idx)->ignore_case) \ (p) = git_idxmap_icase_lookup_index((khash_t(idxicase) *) index->entries_map, (k)); \ else \ (p) = git_idxmap_lookup_index(index->entries_map, (k)); \ } while (0) #define DELETE_IN_MAP(idx, e) do { \ if ((idx)->ignore_case) \ git_idxmap_icase_delete((khash_t(idxicase) *) (idx)->entries_map, (e)); \ else \ git_idxmap_delete((idx)->entries_map, (e)); \ } while (0) static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload); #define minimal_entry_size (offsetof(struct entry_short, path)) static const size_t INDEX_FOOTER_SIZE = GIT_OID_RAWSZ; static const size_t INDEX_HEADER_SIZE = 12; static const unsigned int INDEX_VERSION_NUMBER_DEFAULT = 2; static const unsigned int INDEX_VERSION_NUMBER_LB = 2; static const unsigned int INDEX_VERSION_NUMBER_EXT = 3; static const unsigned int INDEX_VERSION_NUMBER_COMP = 4; static const unsigned int INDEX_VERSION_NUMBER_UB = 4; static const unsigned int INDEX_HEADER_SIG = 0x44495243; static const char INDEX_EXT_TREECACHE_SIG[] = {'T', 'R', 'E', 'E'}; static const char INDEX_EXT_UNMERGED_SIG[] = {'R', 'E', 'U', 'C'}; static const char INDEX_EXT_CONFLICT_NAME_SIG[] = {'N', 'A', 'M', 'E'}; #define INDEX_OWNER(idx) ((git_repository *)(GIT_REFCOUNT_OWNER(idx))) struct index_header { uint32_t signature; uint32_t version; uint32_t entry_count; }; struct index_extension { char signature[4]; uint32_t extension_size; }; struct entry_time { uint32_t seconds; uint32_t nanoseconds; }; struct entry_short { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; char path[1]; /* arbitrary length */ }; struct entry_long { struct entry_time ctime; struct entry_time mtime; uint32_t dev; uint32_t ino; uint32_t mode; uint32_t uid; uint32_t gid; uint32_t file_size; git_oid oid; uint16_t flags; uint16_t flags_extended; char path[1]; /* arbitrary length */ }; struct entry_srch_key { const char *path; size_t pathlen; int stage; }; struct entry_internal { git_index_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; struct reuc_entry_internal { git_index_reuc_entry entry; size_t pathlen; char path[GIT_FLEX_ARRAY]; }; /* local declarations */ static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size); static int read_header(struct index_header *dest, const void *buffer); static int parse_index(git_index *index, const char *buffer, size_t buffer_size); static bool is_index_extended(git_index *index); static int write_index(git_oid *checksum, git_index *index, git_filebuf *file); static void index_entry_free(git_index_entry *entry); static void index_entry_reuc_free(git_index_reuc_entry *reuc); int git_index_entry_srch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = memcmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } int git_index_entry_isrch(const void *key, const void *array_member) { const struct entry_srch_key *srch_key = key; const struct entry_internal *entry = array_member; int cmp; size_t len1, len2, len; len1 = srch_key->pathlen; len2 = entry->pathlen; len = len1 < len2 ? len1 : len2; cmp = strncasecmp(srch_key->path, entry->path, len); if (cmp) return cmp; if (len1 < len2) return -1; if (len1 > len2) return 1; if (srch_key->stage != GIT_INDEX_STAGE_ANY) return srch_key->stage - GIT_IDXENTRY_STAGE(&entry->entry); return 0; } static int index_entry_srch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcmp((const char *)path, entry->path); } static int index_entry_isrch_path(const void *path, const void *array_member) { const git_index_entry *entry = array_member; return strcasecmp((const char *)path, entry->path); } int git_index_entry_cmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } int git_index_entry_icmp(const void *a, const void *b) { int diff; const git_index_entry *entry_a = a; const git_index_entry *entry_b = b; diff = strcasecmp(entry_a->path, entry_b->path); if (diff == 0) diff = (GIT_IDXENTRY_STAGE(entry_a) - GIT_IDXENTRY_STAGE(entry_b)); return diff; } static int conflict_name_cmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcmp(name_a->ours, name_b->ours); } /** * TODO: enable this when resolving case insensitive conflicts */ #if 0 static int conflict_name_icmp(const void *a, const void *b) { const git_index_name_entry *name_a = a; const git_index_name_entry *name_b = b; if (name_a->ancestor && !name_b->ancestor) return 1; if (!name_a->ancestor && name_b->ancestor) return -1; if (name_a->ancestor) return strcasecmp(name_a->ancestor, name_b->ancestor); if (!name_a->ours || !name_b->ours) return 0; return strcasecmp(name_a->ours, name_b->ours); } #endif static int reuc_srch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcmp(key, reuc->path); } static int reuc_isrch(const void *key, const void *array_member) { const git_index_reuc_entry *reuc = array_member; return strcasecmp(key, reuc->path); } static int reuc_cmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcmp(info_a->path, info_b->path); } static int reuc_icmp(const void *a, const void *b) { const git_index_reuc_entry *info_a = a; const git_index_reuc_entry *info_b = b; return strcasecmp(info_a->path, info_b->path); } static void index_entry_reuc_free(git_index_reuc_entry *reuc) { git__free(reuc); } static void index_entry_free(git_index_entry *entry) { if (!entry) return; memset(&entry->id, 0, sizeof(entry->id)); git__free(entry); } unsigned int git_index__create_mode(unsigned int mode) { if (S_ISLNK(mode)) return S_IFLNK; if (S_ISDIR(mode) || (mode & S_IFMT) == (S_IFLNK | S_IFDIR)) return (S_IFLNK | S_IFDIR); return S_IFREG | GIT_PERMS_CANONICAL(mode); } static unsigned int index_merge_mode( git_index *index, git_index_entry *existing, unsigned int mode) { if (index->no_symlinks && S_ISREG(mode) && existing && S_ISLNK(existing->mode)) return existing->mode; if (index->distrust_filemode && S_ISREG(mode)) return (existing && S_ISREG(existing->mode)) ? existing->mode : git_index__create_mode(0666); return git_index__create_mode(mode); } GIT_INLINE(int) index_find_in_entries( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { struct entry_srch_key srch_key; srch_key.path = path; srch_key.pathlen = !path_len ? strlen(path) : path_len; srch_key.stage = stage; return git_vector_bsearch2(out, entries, entry_srch, &srch_key); } GIT_INLINE(int) index_find( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { git_vector_sort(&index->entries); return index_find_in_entries( out, &index->entries, index->entries_search, path, path_len, stage); } void git_index__set_ignore_case(git_index *index, bool ignore_case) { index->ignore_case = ignore_case; if (ignore_case) { index->entries_cmp_path = git__strcasecmp_cb; index->entries_search = git_index_entry_isrch; index->entries_search_path = index_entry_isrch_path; index->reuc_search = reuc_isrch; } else { index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; } git_vector_set_cmp(&index->entries, ignore_case ? git_index_entry_icmp : git_index_entry_cmp); git_vector_sort(&index->entries); git_vector_set_cmp(&index->reuc, ignore_case ? reuc_icmp : reuc_cmp); git_vector_sort(&index->reuc); } int git_index_open(git_index **index_out, const char *index_path) { git_index *index; int error = -1; assert(index_out); index = git__calloc(1, sizeof(git_index)); GITERR_CHECK_ALLOC(index); git_pool_init(&index->tree_pool, 1); if (index_path != NULL) { index->index_file_path = git__strdup(index_path); if (!index->index_file_path) goto fail; /* Check if index file is stored on disk already */ if (git_path_exists(index->index_file_path) == true) index->on_disk = 1; } if (git_vector_init(&index->entries, 32, git_index_entry_cmp) < 0 || git_idxmap_alloc(&index->entries_map) < 0 || git_vector_init(&index->names, 8, conflict_name_cmp) < 0 || git_vector_init(&index->reuc, 8, reuc_cmp) < 0 || git_vector_init(&index->deleted, 8, git_index_entry_cmp) < 0) goto fail; index->entries_cmp_path = git__strcmp_cb; index->entries_search = git_index_entry_srch; index->entries_search_path = index_entry_srch_path; index->reuc_search = reuc_srch; index->version = INDEX_VERSION_NUMBER_DEFAULT; if (index_path != NULL && (error = git_index_read(index, true)) < 0) goto fail; *index_out = index; GIT_REFCOUNT_INC(index); return 0; fail: git_pool_clear(&index->tree_pool); git_index_free(index); return error; } int git_index_new(git_index **out) { return git_index_open(out, NULL); } static void index_free(git_index *index) { /* index iterators increment the refcount of the index, so if we * get here then there should be no outstanding iterators. */ assert(!git_atomic_get(&index->readers)); git_index_clear(index); git_idxmap_free(index->entries_map); git_vector_free(&index->entries); git_vector_free(&index->names); git_vector_free(&index->reuc); git_vector_free(&index->deleted); git__free(index->index_file_path); git__memzero(index, sizeof(*index)); git__free(index); } void git_index_free(git_index *index) { if (index == NULL) return; GIT_REFCOUNT_DEC(index, index_free); } /* call with locked index */ static void index_free_deleted(git_index *index) { int readers = (int)git_atomic_get(&index->readers); size_t i; if (readers > 0 || !index->deleted.length) return; for (i = 0; i < index->deleted.length; ++i) { git_index_entry *ie = git__swap(index->deleted.contents[i], NULL); index_entry_free(ie); } git_vector_clear(&index->deleted); } /* call with locked index */ static int index_remove_entry(git_index *index, size_t pos) { int error = 0; git_index_entry *entry = git_vector_get(&index->entries, pos); if (entry != NULL) { git_tree_cache_invalidate_path(index->tree, entry->path); DELETE_IN_MAP(index, entry); } error = git_vector_remove(&index->entries, pos); if (!error) { if (git_atomic_get(&index->readers) > 0) { error = git_vector_insert(&index->deleted, entry); } else { index_entry_free(entry); } } return error; } int git_index_clear(git_index *index) { int error = 0; assert(index); index->tree = NULL; git_pool_clear(&index->tree_pool); git_idxmap_clear(index->entries_map); while (!error && index->entries.length > 0) error = index_remove_entry(index, index->entries.length - 1); index_free_deleted(index); git_index_reuc_clear(index); git_index_name_clear(index); git_futils_filestamp_set(&index->stamp, NULL); return error; } static int create_index_error(int error, const char *msg) { giterr_set_str(GITERR_INDEX, msg); return error; } int git_index_set_caps(git_index *index, int caps) { unsigned int old_ignore_case; assert(index); old_ignore_case = index->ignore_case; if (caps == GIT_INDEXCAP_FROM_OWNER) { git_repository *repo = INDEX_OWNER(index); int val; if (!repo) return create_index_error( -1, "cannot access repository to set index caps"); if (!git_repository__cvar(&val, repo, GIT_CVAR_IGNORECASE)) index->ignore_case = (val != 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_FILEMODE)) index->distrust_filemode = (val == 0); if (!git_repository__cvar(&val, repo, GIT_CVAR_SYMLINKS)) index->no_symlinks = (val == 0); } else { index->ignore_case = ((caps & GIT_INDEXCAP_IGNORE_CASE) != 0); index->distrust_filemode = ((caps & GIT_INDEXCAP_NO_FILEMODE) != 0); index->no_symlinks = ((caps & GIT_INDEXCAP_NO_SYMLINKS) != 0); } if (old_ignore_case != index->ignore_case) { git_index__set_ignore_case(index, (bool)index->ignore_case); } return 0; } int git_index_caps(const git_index *index) { return ((index->ignore_case ? GIT_INDEXCAP_IGNORE_CASE : 0) | (index->distrust_filemode ? GIT_INDEXCAP_NO_FILEMODE : 0) | (index->no_symlinks ? GIT_INDEXCAP_NO_SYMLINKS : 0)); } const git_oid *git_index_checksum(git_index *index) { return &index->checksum; } /** * Returns 1 for changed, 0 for not changed and <0 for errors */ static int compare_checksum(git_index *index) { int fd; ssize_t bytes_read; git_oid checksum = {{ 0 }}; if ((fd = p_open(index->index_file_path, O_RDONLY)) < 0) return fd; if (p_lseek(fd, -20, SEEK_END) < 0) { p_close(fd); giterr_set(GITERR_OS, "failed to seek to end of file"); return -1; } bytes_read = p_read(fd, &checksum, GIT_OID_RAWSZ); p_close(fd); if (bytes_read < 0) return -1; return !!git_oid_cmp(&checksum, &index->checksum); } int git_index_read(git_index *index, int force) { int error = 0, updated; git_buf buffer = GIT_BUF_INIT; git_futils_filestamp stamp = index->stamp; if (!index->index_file_path) return create_index_error(-1, "failed to read index: The index is in-memory only"); index->on_disk = git_path_exists(index->index_file_path); if (!index->on_disk) { if (force) return git_index_clear(index); return 0; } if ((updated = git_futils_filestamp_check(&stamp, index->index_file_path) < 0) || ((updated = compare_checksum(index)) < 0)) { giterr_set( GITERR_INDEX, "failed to read index: '%s' no longer exists", index->index_file_path); return updated; } if (!updated && !force) return 0; error = git_futils_readbuffer(&buffer, index->index_file_path); if (error < 0) return error; index->tree = NULL; git_pool_clear(&index->tree_pool); error = git_index_clear(index); if (!error) error = parse_index(index, buffer.ptr, buffer.size); if (!error) git_futils_filestamp_set(&index->stamp, &stamp); git_buf_free(&buffer); return error; } int git_index__changed_relative_to( git_index *index, const git_oid *checksum) { /* attempt to update index (ignoring errors) */ if (git_index_read(index, false) < 0) giterr_clear(); return !!git_oid_cmp(&index->checksum, checksum); } static bool is_racy_entry(git_index *index, const git_index_entry *entry) { /* Git special-cases submodules in the check */ if (S_ISGITLINK(entry->mode)) return false; return git_index_entry_newer_than_index(entry, index); } /* * Force the next diff to take a look at those entries which have the * same timestamp as the current index. */ static int truncate_racily_clean(git_index *index) { size_t i; int error; git_index_entry *entry; git_diff_options diff_opts = GIT_DIFF_OPTIONS_INIT; git_diff *diff = NULL; git_vector paths = GIT_VECTOR_INIT; git_diff_delta *delta; /* Nothing to do if there's no repo to talk about */ if (!INDEX_OWNER(index)) return 0; /* If there's no workdir, we can't know where to even check */ if (!git_repository_workdir(INDEX_OWNER(index))) return 0; diff_opts.flags |= GIT_DIFF_INCLUDE_TYPECHANGE | GIT_DIFF_IGNORE_SUBMODULES | GIT_DIFF_DISABLE_PATHSPEC_MATCH; git_vector_foreach(&index->entries, i, entry) { if ((entry->flags_extended & GIT_IDXENTRY_UPTODATE) == 0 && is_racy_entry(index, entry)) git_vector_insert(&paths, (char *)entry->path); } if (paths.length == 0) goto done; diff_opts.pathspec.count = paths.length; diff_opts.pathspec.strings = (char **)paths.contents; if ((error = git_diff_index_to_workdir(&diff, INDEX_OWNER(index), index, &diff_opts)) < 0) return error; git_vector_foreach(&diff->deltas, i, delta) { entry = (git_index_entry *)git_index_get_bypath(index, delta->old_file.path, 0); /* Ensure that we have a stage 0 for this file (ie, it's not a * conflict), otherwise smudging it is quite pointless. */ if (entry) entry->file_size = 0; } done: git_diff_free(diff); git_vector_free(&paths); return 0; } unsigned git_index_version(git_index *index) { assert(index); return index->version; } int git_index_set_version(git_index *index, unsigned int version) { assert(index); if (version < INDEX_VERSION_NUMBER_LB || version > INDEX_VERSION_NUMBER_UB) { giterr_set(GITERR_INDEX, "invalid version number"); return -1; } index->version = version; return 0; } int git_index_write(git_index *index) { git_indexwriter writer = GIT_INDEXWRITER_INIT; int error; truncate_racily_clean(index); if ((error = git_indexwriter_init(&writer, index)) == 0) error = git_indexwriter_commit(&writer); git_indexwriter_cleanup(&writer); return error; } const char * git_index_path(const git_index *index) { assert(index); return index->index_file_path; } int git_index_write_tree(git_oid *oid, git_index *index) { git_repository *repo; assert(oid && index); repo = INDEX_OWNER(index); if (repo == NULL) return create_index_error(-1, "Failed to write tree. " "the index file is not backed up by an existing repository"); return git_tree__write_index(oid, index, repo); } int git_index_write_tree_to( git_oid *oid, git_index *index, git_repository *repo) { assert(oid && index && repo); return git_tree__write_index(oid, index, repo); } size_t git_index_entrycount(const git_index *index) { assert(index); return index->entries.length; } const git_index_entry *git_index_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->entries); return git_vector_get(&index->entries, n); } const git_index_entry *git_index_get_bypath( git_index *index, const char *path, int stage) { khiter_t pos; git_index_entry key = {{ 0 }}; assert(index); key.path = path; GIT_IDXENTRY_STAGE_SET(&key, stage); LOOKUP_IN_MAP(pos, index, &key); if (git_idxmap_valid_index(index->entries_map, pos)) return git_idxmap_value_at(index->entries_map, pos); giterr_set(GITERR_INDEX, "index does not contain '%s'", path); return NULL; } void git_index_entry__init_from_stat( git_index_entry *entry, struct stat *st, bool trust_mode) { entry->ctime.seconds = (int32_t)st->st_ctime; entry->mtime.seconds = (int32_t)st->st_mtime; #if defined(GIT_USE_NSEC) entry->mtime.nanoseconds = st->st_mtime_nsec; entry->ctime.nanoseconds = st->st_ctime_nsec; #endif entry->dev = st->st_rdev; entry->ino = st->st_ino; entry->mode = (!trust_mode && S_ISREG(st->st_mode)) ? git_index__create_mode(0666) : git_index__create_mode(st->st_mode); entry->uid = st->st_uid; entry->gid = st->st_gid; entry->file_size = (uint32_t)st->st_size; } static void index_entry_adjust_namemask( git_index_entry *entry, size_t path_length) { entry->flags &= ~GIT_IDXENTRY_NAMEMASK; if (path_length < GIT_IDXENTRY_NAMEMASK) entry->flags |= path_length & GIT_IDXENTRY_NAMEMASK; else entry->flags |= GIT_IDXENTRY_NAMEMASK; } /* When `from_workdir` is true, we will validate the paths to avoid placing * paths that are invalid for the working directory on the current filesystem * (eg, on Windows, we will disallow `GIT~1`, `AUX`, `COM1`, etc). This * function will *always* prevent `.git` and directory traversal `../` from * being added to the index. */ static int index_entry_create( git_index_entry **out, git_repository *repo, const char *path, bool from_workdir) { size_t pathlen = strlen(path), alloclen; struct entry_internal *entry; unsigned int path_valid_flags = GIT_PATH_REJECT_INDEX_DEFAULTS; /* always reject placing `.git` in the index and directory traversal. * when requested, disallow platform-specific filenames and upgrade to * the platform-specific `.git` tests (eg, `git~1`, etc). */ if (from_workdir) path_valid_flags |= GIT_PATH_REJECT_WORKDIR_DEFAULTS; if (!git_path_isvalid(repo, path, path_valid_flags)) { giterr_set(GITERR_INDEX, "invalid path: '%s'", path); return -1; } GITERR_CHECK_ALLOC_ADD(&alloclen, sizeof(struct entry_internal), pathlen); GITERR_CHECK_ALLOC_ADD(&alloclen, alloclen, 1); entry = git__calloc(1, alloclen); GITERR_CHECK_ALLOC(entry); entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; *out = (git_index_entry *)entry; return 0; } static int index_entry_init( git_index_entry **entry_out, git_index *index, const char *rel_path) { int error = 0; git_index_entry *entry = NULL; struct stat st; git_oid oid; if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (index_entry_create(&entry, INDEX_OWNER(index), rel_path, true) < 0) return -1; /* write the blob to disk and get the oid and stat info */ error = git_blob__create_from_paths( &oid, &st, INDEX_OWNER(index), NULL, rel_path, 0, true); if (error < 0) { index_entry_free(entry); return error; } entry->id = oid; git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); *entry_out = (git_index_entry *)entry; return 0; } static git_index_reuc_entry *reuc_entry_alloc(const char *path) { size_t pathlen = strlen(path), structlen = sizeof(struct reuc_entry_internal), alloclen; struct reuc_entry_internal *entry; if (GIT_ADD_SIZET_OVERFLOW(&alloclen, structlen, pathlen) || GIT_ADD_SIZET_OVERFLOW(&alloclen, alloclen, 1)) return NULL; entry = git__calloc(1, alloclen); if (!entry) return NULL; entry->pathlen = pathlen; memcpy(entry->path, path, pathlen); entry->entry.path = entry->path; return (git_index_reuc_entry *)entry; } static int index_entry_reuc_init(git_index_reuc_entry **reuc_out, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; assert(reuc_out && path); *reuc_out = reuc = reuc_entry_alloc(path); GITERR_CHECK_ALLOC(reuc); if ((reuc->mode[0] = ancestor_mode) > 0) { assert(ancestor_oid); git_oid_cpy(&reuc->oid[0], ancestor_oid); } if ((reuc->mode[1] = our_mode) > 0) { assert(our_oid); git_oid_cpy(&reuc->oid[1], our_oid); } if ((reuc->mode[2] = their_mode) > 0) { assert(their_oid); git_oid_cpy(&reuc->oid[2], their_oid); } return 0; } static void index_entry_cpy( git_index_entry *tgt, const git_index_entry *src) { const char *tgt_path = tgt->path; memcpy(tgt, src, sizeof(*tgt)); tgt->path = tgt_path; } static int index_entry_dup( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy(*out, src); return 0; } static void index_entry_cpy_nocache( git_index_entry *tgt, const git_index_entry *src) { git_oid_cpy(&tgt->id, &src->id); tgt->mode = src->mode; tgt->flags = src->flags; tgt->flags_extended = (src->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); } static int index_entry_dup_nocache( git_index_entry **out, git_index *index, const git_index_entry *src) { if (index_entry_create(out, INDEX_OWNER(index), src->path, false) < 0) return -1; index_entry_cpy_nocache(*out, src); return 0; } static int has_file_name(git_index *index, const git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = 0; size_t len = strlen(entry->path); int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; while (pos < index->entries.length) { struct entry_internal *p = index->entries.contents[pos++]; if (len >= p->pathlen) break; if (memcmp(name, p->path, len)) break; if (GIT_IDXENTRY_STAGE(&p->entry) != stage) continue; if (p->path[len] != '/') continue; retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, --pos) < 0) break; } return retval; } /* * Do we have another file with a pathname that is a proper * subset of the name we're trying to add? */ static int has_dir_name(git_index *index, const git_index_entry *entry, int ok_to_replace) { int retval = 0; int stage = GIT_IDXENTRY_STAGE(entry); const char *name = entry->path; const char *slash = name + strlen(name); for (;;) { size_t len, pos; for (;;) { if (*--slash == '/') break; if (slash <= entry->path) return retval; } len = slash - name; if (!index_find(&pos, index, name, len, stage)) { retval = -1; if (!ok_to_replace) break; if (index_remove_entry(index, pos) < 0) break; continue; } /* * Trivial optimization: if we find an entry that * already matches the sub-directory, then we know * we're ok, and we can exit. */ for (; pos < index->entries.length; ++pos) { struct entry_internal *p = index->entries.contents[pos]; if (p->pathlen <= len || p->path[len] != '/' || memcmp(p->path, name, len)) break; /* not our subdirectory */ if (GIT_IDXENTRY_STAGE(&p->entry) == stage) return retval; } } return retval; } static int check_file_directory_collision(git_index *index, git_index_entry *entry, size_t pos, int ok_to_replace) { int retval = has_file_name(index, entry, pos, ok_to_replace); retval = retval + has_dir_name(index, entry, ok_to_replace); if (retval) { giterr_set(GITERR_INDEX, "'%s' appears as both a file and a directory", entry->path); return -1; } return 0; } static int canonicalize_directory_path( git_index *index, git_index_entry *entry, git_index_entry *existing) { const git_index_entry *match, *best = NULL; char *search, *sep; size_t pos, search_len, best_len; if (!index->ignore_case) return 0; /* item already exists in the index, simply re-use the existing case */ if (existing) { memcpy((char *)entry->path, existing->path, strlen(existing->path)); return 0; } /* nothing to do */ if (strchr(entry->path, '/') == NULL) return 0; if ((search = git__strdup(entry->path)) == NULL) return -1; /* starting at the parent directory and descending to the root, find the * common parent directory. */ while (!best && (sep = strrchr(search, '/'))) { sep[1] = '\0'; search_len = strlen(search); git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, search); while ((match = git_vector_get(&index->entries, pos))) { if (GIT_IDXENTRY_STAGE(match) != 0) { /* conflicts do not contribute to canonical paths */ } else if (strncmp(search, match->path, search_len) == 0) { /* prefer an exact match to the input filename */ best = match; best_len = search_len; break; } else if (strncasecmp(search, match->path, search_len) == 0) { /* continue walking, there may be a path with an exact * (case sensitive) match later in the index, but use this * as the best match until that happens. */ if (!best) { best = match; best_len = search_len; } } else { break; } pos++; } sep[0] = '\0'; } if (best) memcpy((char *)entry->path, best->path, best_len); git__free(search); return 0; } static int index_no_dups(void **old, void *new) { const git_index_entry *entry = new; GIT_UNUSED(old); giterr_set(GITERR_INDEX, "'%s' appears multiple times at stage %d", entry->path, GIT_IDXENTRY_STAGE(entry)); return GIT_EEXISTS; } static void index_existing_and_best( git_index_entry **existing, size_t *existing_position, git_index_entry **best, git_index *index, const git_index_entry *entry) { git_index_entry *e; size_t pos; int error; error = index_find(&pos, index, entry->path, 0, GIT_IDXENTRY_STAGE(entry)); if (error == 0) { *existing = index->entries.contents[pos]; *existing_position = pos; *best = index->entries.contents[pos]; return; } *existing = NULL; *existing_position = 0; *best = NULL; if (GIT_IDXENTRY_STAGE(entry) == 0) { for (; pos < index->entries.length; pos++) { int (*strcomp)(const char *a, const char *b) = index->ignore_case ? git__strcasecmp : git__strcmp; e = index->entries.contents[pos]; if (strcomp(entry->path, e->path) != 0) break; if (GIT_IDXENTRY_STAGE(e) == GIT_INDEX_STAGE_ANCESTOR) { *best = e; continue; } else { *best = e; break; } } } } /* index_insert takes ownership of the new entry - if it can't insert * it, then it will return an error **and also free the entry**. When * it replaces an existing entry, it will update the entry_ptr with the * actual entry in the index (and free the passed in one). * * trust_path is whether we use the given path, or whether (on case * insensitive systems only) we try to canonicalize the given path to * be within an existing directory. * * trust_mode is whether we trust the mode in entry_ptr. * * trust_id is whether we trust the id or it should be validated. */ static int index_insert( git_index *index, git_index_entry **entry_ptr, int replace, bool trust_path, bool trust_mode, bool trust_id) { int error = 0; size_t path_length, position; git_index_entry *existing, *best, *entry; assert(index && entry_ptr); entry = *entry_ptr; /* make sure that the path length flag is correct */ path_length = ((struct entry_internal *)entry)->pathlen; index_entry_adjust_namemask(entry, path_length); /* this entry is now up-to-date and should not be checked for raciness */ entry->flags_extended |= GIT_IDXENTRY_UPTODATE; git_vector_sort(&index->entries); /* look if an entry with this path already exists, either staged, or (if * this entry is a regular staged item) as the "ours" side of a conflict. */ index_existing_and_best(&existing, &position, &best, index, entry); /* update the file mode */ entry->mode = trust_mode ? git_index__create_mode(entry->mode) : index_merge_mode(index, best, entry->mode); /* canonicalize the directory name */ if (!trust_path) error = canonicalize_directory_path(index, entry, best); /* ensure that the given id exists (unless it's a submodule) */ if (!error && !trust_id && INDEX_OWNER(index) && (entry->mode & GIT_FILEMODE_COMMIT) != GIT_FILEMODE_COMMIT) { if (!git_object__is_valid(INDEX_OWNER(index), &entry->id, git_object__type_from_filemode(entry->mode))) error = -1; } /* look for tree / blob name collisions, removing conflicts if requested */ if (!error) error = check_file_directory_collision(index, entry, position, replace); if (error < 0) /* skip changes */; /* if we are replacing an existing item, overwrite the existing entry * and return it in place of the passed in one. */ else if (existing) { if (replace) { index_entry_cpy(existing, entry); if (trust_path) memcpy((char *)existing->path, entry->path, strlen(entry->path)); } index_entry_free(entry); *entry_ptr = entry = existing; } else { /* if replace is not requested or no existing entry exists, insert * at the sorted position. (Since we re-sort after each insert to * check for dups, this is actually cheaper in the long run.) */ error = git_vector_insert_sorted(&index->entries, entry, index_no_dups); if (error == 0) { INSERT_IN_MAP(index, entry, &error); } } if (error < 0) { index_entry_free(*entry_ptr); *entry_ptr = NULL; } return error; } static int index_conflict_to_reuc(git_index *index, const char *path) { const git_index_entry *conflict_entries[3]; int ancestor_mode, our_mode, their_mode; git_oid const *ancestor_oid, *our_oid, *their_oid; int ret; if ((ret = git_index_conflict_get(&conflict_entries[0], &conflict_entries[1], &conflict_entries[2], index, path)) < 0) return ret; ancestor_mode = conflict_entries[0] == NULL ? 0 : conflict_entries[0]->mode; our_mode = conflict_entries[1] == NULL ? 0 : conflict_entries[1]->mode; their_mode = conflict_entries[2] == NULL ? 0 : conflict_entries[2]->mode; ancestor_oid = conflict_entries[0] == NULL ? NULL : &conflict_entries[0]->id; our_oid = conflict_entries[1] == NULL ? NULL : &conflict_entries[1]->id; their_oid = conflict_entries[2] == NULL ? NULL : &conflict_entries[2]->id; if ((ret = git_index_reuc_add(index, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) >= 0) ret = git_index_conflict_remove(index, path); return ret; } GIT_INLINE(bool) is_file_or_link(const int filemode) { return (filemode == GIT_FILEMODE_BLOB || filemode == GIT_FILEMODE_BLOB_EXECUTABLE || filemode == GIT_FILEMODE_LINK); } GIT_INLINE(bool) valid_filemode(const int filemode) { return (is_file_or_link(filemode) || filemode == GIT_FILEMODE_COMMIT); } int git_index_add_frombuffer( git_index *index, const git_index_entry *source_entry, const void *buffer, size_t len) { git_index_entry *entry = NULL; int error = 0; git_oid id; assert(index && source_entry->path); if (INDEX_OWNER(index) == NULL) return create_index_error(-1, "could not initialize index entry. " "Index is not backed up by an existing repository."); if (!is_file_or_link(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid filemode"); return -1; } if (index_entry_dup(&entry, index, source_entry) < 0) return -1; error = git_blob_create_frombuffer(&id, INDEX_OWNER(index), buffer, len); if (error < 0) { index_entry_free(entry); return error; } git_oid_cpy(&entry->id, &id); entry->file_size = len; if ((error = index_insert(index, &entry, 1, true, true, true)) < 0) return error; /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((error = index_conflict_to_reuc(index, entry->path)) < 0 && error != GIT_ENOTFOUND) return error; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } static int add_repo_as_submodule(git_index_entry **out, git_index *index, const char *path) { git_repository *sub; git_buf abspath = GIT_BUF_INIT; git_repository *repo = INDEX_OWNER(index); git_reference *head; git_index_entry *entry; struct stat st; int error; if (index_entry_create(&entry, INDEX_OWNER(index), path, true) < 0) return -1; if ((error = git_buf_joinpath(&abspath, git_repository_workdir(repo), path)) < 0) return error; if ((error = p_stat(abspath.ptr, &st)) < 0) { giterr_set(GITERR_OS, "failed to stat repository dir"); return -1; } git_index_entry__init_from_stat(entry, &st, !index->distrust_filemode); if ((error = git_repository_open(&sub, abspath.ptr)) < 0) return error; if ((error = git_repository_head(&head, sub)) < 0) return error; git_oid_cpy(&entry->id, git_reference_target(head)); entry->mode = GIT_FILEMODE_COMMIT; git_reference_free(head); git_repository_free(sub); git_buf_free(&abspath); *out = entry; return 0; } int git_index_add_bypath(git_index *index, const char *path) { git_index_entry *entry = NULL; int ret; assert(index && path); if ((ret = index_entry_init(&entry, index, path)) == 0) ret = index_insert(index, &entry, 1, false, false, true); /* If we were given a directory, let's see if it's a submodule */ if (ret < 0 && ret != GIT_EDIRECTORY) return ret; if (ret == GIT_EDIRECTORY) { git_submodule *sm; git_error_state err; giterr_state_capture(&err, ret); ret = git_submodule_lookup(&sm, INDEX_OWNER(index), path); if (ret == GIT_ENOTFOUND) return giterr_state_restore(&err); giterr_state_free(&err); /* * EEXISTS means that there is a repository at that path, but it's not known * as a submodule. We add its HEAD as an entry and don't register it. */ if (ret == GIT_EEXISTS) { if ((ret = add_repo_as_submodule(&entry, index, path)) < 0) return ret; if ((ret = index_insert(index, &entry, 1, false, false, true)) < 0) return ret; } else if (ret < 0) { return ret; } else { ret = git_submodule_add_to_index(sm, false); git_submodule_free(sm); return ret; } } /* Adding implies conflict was resolved, move conflict entries to REUC */ if ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove_bypath(git_index *index, const char *path) { int ret; assert(index && path); if (((ret = git_index_remove(index, path, 0)) < 0 && ret != GIT_ENOTFOUND) || ((ret = index_conflict_to_reuc(index, path)) < 0 && ret != GIT_ENOTFOUND)) return ret; if (ret == GIT_ENOTFOUND) giterr_clear(); return 0; } int git_index__fill(git_index *index, const git_vector *source_entries) { const git_index_entry *source_entry = NULL; size_t i; int ret = 0; assert(index); if (!source_entries->length) return 0; git_vector_size_hint(&index->entries, source_entries->length); git_idxmap_resize(index->entries_map, (khint_t)(source_entries->length * 1.3)); git_vector_foreach(source_entries, i, source_entry) { git_index_entry *entry = NULL; if ((ret = index_entry_dup(&entry, index, source_entry)) < 0) break; index_entry_adjust_namemask(entry, ((struct entry_internal *)entry)->pathlen); entry->flags_extended |= GIT_IDXENTRY_UPTODATE; entry->mode = git_index__create_mode(entry->mode); if ((ret = git_vector_insert(&index->entries, entry)) < 0) break; INSERT_IN_MAP(index, entry, &ret); if (ret < 0) break; } if (!ret) git_vector_sort(&index->entries); return ret; } int git_index_add(git_index *index, const git_index_entry *source_entry) { git_index_entry *entry = NULL; int ret; assert(index && source_entry && source_entry->path); if (!valid_filemode(source_entry->mode)) { giterr_set(GITERR_INDEX, "invalid entry mode"); return -1; } if ((ret = index_entry_dup(&entry, index, source_entry)) < 0 || (ret = index_insert(index, &entry, 1, true, true, false)) < 0) return ret; git_tree_cache_invalidate_path(index->tree, entry->path); return 0; } int git_index_remove(git_index *index, const char *path, int stage) { int error; size_t position; git_index_entry remove_key = {{ 0 }}; remove_key.path = path; GIT_IDXENTRY_STAGE_SET(&remove_key, stage); DELETE_IN_MAP(index, &remove_key); if (index_find(&position, index, path, 0, stage) < 0) { giterr_set( GITERR_INDEX, "index does not contain %s at stage %d", path, stage); error = GIT_ENOTFOUND; } else { error = index_remove_entry(index, position); } return error; } int git_index_remove_directory(git_index *index, const char *dir, int stage) { git_buf pfx = GIT_BUF_INIT; int error = 0; size_t pos; git_index_entry *entry; if (!(error = git_buf_sets(&pfx, dir)) && !(error = git_path_to_dir(&pfx))) index_find(&pos, index, pfx.ptr, pfx.size, GIT_INDEX_STAGE_ANY); while (!error) { entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, pfx.ptr) != 0) break; if (GIT_IDXENTRY_STAGE(entry) != stage) { ++pos; continue; } error = index_remove_entry(index, pos); /* removed entry at 'pos' so we don't need to increment */ } git_buf_free(&pfx); return error; } int git_index_find_prefix(size_t *at_pos, git_index *index, const char *prefix) { int error = 0; size_t pos; const git_index_entry *entry; index_find(&pos, index, prefix, strlen(prefix), GIT_INDEX_STAGE_ANY); entry = git_vector_get(&index->entries, pos); if (!entry || git__prefixcmp(entry->path, prefix) != 0) error = GIT_ENOTFOUND; if (!error && at_pos) *at_pos = pos; return error; } int git_index__find_pos( size_t *out, git_index *index, const char *path, size_t path_len, int stage) { assert(index && path); return index_find(out, index, path, path_len, stage); } int git_index_find(size_t *at_pos, git_index *index, const char *path) { size_t pos; assert(index && path); if (git_vector_bsearch2( &pos, &index->entries, index->entries_search_path, path) < 0) { giterr_set(GITERR_INDEX, "index does not contain %s", path); return GIT_ENOTFOUND; } /* Since our binary search only looked at path, we may be in the * middle of a list of stages. */ for (; pos > 0; --pos) { const git_index_entry *prev = git_vector_get(&index->entries, pos - 1); if (index->entries_cmp_path(prev->path, path) != 0) break; } if (at_pos) *at_pos = pos; return 0; } int git_index_conflict_add(git_index *index, const git_index_entry *ancestor_entry, const git_index_entry *our_entry, const git_index_entry *their_entry) { git_index_entry *entries[3] = { 0 }; unsigned short i; int ret = 0; assert (index); if ((ancestor_entry && (ret = index_entry_dup(&entries[0], index, ancestor_entry)) < 0) || (our_entry && (ret = index_entry_dup(&entries[1], index, our_entry)) < 0) || (their_entry && (ret = index_entry_dup(&entries[2], index, their_entry)) < 0)) goto on_error; /* Validate entries */ for (i = 0; i < 3; i++) { if (entries[i] && !valid_filemode(entries[i]->mode)) { giterr_set(GITERR_INDEX, "invalid filemode for stage %d entry", i + 1); return -1; } } /* Remove existing index entries for each path */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; if ((ret = git_index_remove(index, entries[i]->path, 0)) != 0) { if (ret != GIT_ENOTFOUND) goto on_error; giterr_clear(); ret = 0; } } /* Add the conflict entries */ for (i = 0; i < 3; i++) { if (entries[i] == NULL) continue; /* Make sure stage is correct */ GIT_IDXENTRY_STAGE_SET(entries[i], i + 1); if ((ret = index_insert(index, &entries[i], 1, true, true, false)) < 0) goto on_error; entries[i] = NULL; /* don't free if later entry fails */ } return 0; on_error: for (i = 0; i < 3; i++) { if (entries[i] != NULL) index_entry_free(entries[i]); } return ret; } static int index_conflict__get_byindex( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, size_t n) { const git_index_entry *conflict_entry; const char *path = NULL; size_t count; int stage, len = 0; assert(ancestor_out && our_out && their_out && index); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; for (count = git_index_entrycount(index); n < count; ++n) { conflict_entry = git_vector_get(&index->entries, n); if (path && index->entries_cmp_path(conflict_entry->path, path) != 0) break; stage = GIT_IDXENTRY_STAGE(conflict_entry); path = conflict_entry->path; switch (stage) { case 3: *their_out = conflict_entry; len++; break; case 2: *our_out = conflict_entry; len++; break; case 1: *ancestor_out = conflict_entry; len++; break; default: break; }; } return len; } int git_index_conflict_get( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index *index, const char *path) { size_t pos; int len = 0; assert(ancestor_out && our_out && their_out && index && path); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; if (git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, index, pos)) < 0) return len; else if (len == 0) return GIT_ENOTFOUND; return 0; } static int index_conflict_remove(git_index *index, const char *path) { size_t pos = 0; git_index_entry *conflict_entry; int error = 0; if (path != NULL && git_index_find(&pos, index, path) < 0) return GIT_ENOTFOUND; while ((conflict_entry = git_vector_get(&index->entries, pos)) != NULL) { if (path != NULL && index->entries_cmp_path(conflict_entry->path, path) != 0) break; if (GIT_IDXENTRY_STAGE(conflict_entry) == 0) { pos++; continue; } if ((error = index_remove_entry(index, pos)) < 0) break; } return error; } int git_index_conflict_remove(git_index *index, const char *path) { assert(index && path); return index_conflict_remove(index, path); } int git_index_conflict_cleanup(git_index *index) { assert(index); return index_conflict_remove(index, NULL); } int git_index_has_conflicts(const git_index *index) { size_t i; git_index_entry *entry; assert(index); git_vector_foreach(&index->entries, i, entry) { if (GIT_IDXENTRY_STAGE(entry) > 0) return 1; } return 0; } int git_index_conflict_iterator_new( git_index_conflict_iterator **iterator_out, git_index *index) { git_index_conflict_iterator *it = NULL; assert(iterator_out && index); it = git__calloc(1, sizeof(git_index_conflict_iterator)); GITERR_CHECK_ALLOC(it); it->index = index; *iterator_out = it; return 0; } int git_index_conflict_next( const git_index_entry **ancestor_out, const git_index_entry **our_out, const git_index_entry **their_out, git_index_conflict_iterator *iterator) { const git_index_entry *entry; int len; assert(ancestor_out && our_out && their_out && iterator); *ancestor_out = NULL; *our_out = NULL; *their_out = NULL; while (iterator->cur < iterator->index->entries.length) { entry = git_index_get_byindex(iterator->index, iterator->cur); if (git_index_entry_is_conflict(entry)) { if ((len = index_conflict__get_byindex( ancestor_out, our_out, their_out, iterator->index, iterator->cur)) < 0) return len; iterator->cur += len; return 0; } iterator->cur++; } return GIT_ITEROVER; } void git_index_conflict_iterator_free(git_index_conflict_iterator *iterator) { if (iterator == NULL) return; git__free(iterator); } size_t git_index_name_entrycount(git_index *index) { assert(index); return index->names.length; } const git_index_name_entry *git_index_name_get_byindex( git_index *index, size_t n) { assert(index); git_vector_sort(&index->names); return git_vector_get(&index->names, n); } static void index_name_entry_free(git_index_name_entry *ne) { if (!ne) return; git__free(ne->ancestor); git__free(ne->ours); git__free(ne->theirs); git__free(ne); } int git_index_name_add(git_index *index, const char *ancestor, const char *ours, const char *theirs) { git_index_name_entry *conflict_name; assert((ancestor && ours) || (ancestor && theirs) || (ours && theirs)); conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); if ((ancestor && !(conflict_name->ancestor = git__strdup(ancestor))) || (ours && !(conflict_name->ours = git__strdup(ours))) || (theirs && !(conflict_name->theirs = git__strdup(theirs))) || git_vector_insert(&index->names, conflict_name) < 0) { index_name_entry_free(conflict_name); return -1; } return 0; } void git_index_name_clear(git_index *index) { size_t i; git_index_name_entry *conflict_name; assert(index); git_vector_foreach(&index->names, i, conflict_name) index_name_entry_free(conflict_name); git_vector_clear(&index->names); } size_t git_index_reuc_entrycount(git_index *index) { assert(index); return index->reuc.length; } static int index_reuc_on_dup(void **old, void *new) { index_entry_reuc_free(*old); *old = new; return GIT_EEXISTS; } static int index_reuc_insert( git_index *index, git_index_reuc_entry *reuc) { int res; assert(index && reuc && reuc->path != NULL); assert(git_vector_is_sorted(&index->reuc)); res = git_vector_insert_sorted(&index->reuc, reuc, &index_reuc_on_dup); return res == GIT_EEXISTS ? 0 : res; } int git_index_reuc_add(git_index *index, const char *path, int ancestor_mode, const git_oid *ancestor_oid, int our_mode, const git_oid *our_oid, int their_mode, const git_oid *their_oid) { git_index_reuc_entry *reuc = NULL; int error = 0; assert(index && path); if ((error = index_entry_reuc_init(&reuc, path, ancestor_mode, ancestor_oid, our_mode, our_oid, their_mode, their_oid)) < 0 || (error = index_reuc_insert(index, reuc)) < 0) index_entry_reuc_free(reuc); return error; } int git_index_reuc_find(size_t *at_pos, git_index *index, const char *path) { return git_vector_bsearch2(at_pos, &index->reuc, index->reuc_search, path); } const git_index_reuc_entry *git_index_reuc_get_bypath( git_index *index, const char *path) { size_t pos; assert(index && path); if (!index->reuc.length) return NULL; assert(git_vector_is_sorted(&index->reuc)); if (git_index_reuc_find(&pos, index, path) < 0) return NULL; return git_vector_get(&index->reuc, pos); } const git_index_reuc_entry *git_index_reuc_get_byindex( git_index *index, size_t n) { assert(index); assert(git_vector_is_sorted(&index->reuc)); return git_vector_get(&index->reuc, n); } int git_index_reuc_remove(git_index *index, size_t position) { int error; git_index_reuc_entry *reuc; assert(git_vector_is_sorted(&index->reuc)); reuc = git_vector_get(&index->reuc, position); error = git_vector_remove(&index->reuc, position); if (!error) index_entry_reuc_free(reuc); return error; } void git_index_reuc_clear(git_index *index) { size_t i; assert(index); for (i = 0; i < index->reuc.length; ++i) index_entry_reuc_free(git__swap(index->reuc.contents[i], NULL)); git_vector_clear(&index->reuc); } static int index_error_invalid(const char *message) { giterr_set(GITERR_INDEX, "invalid data in index - %s", message); return -1; } static int read_reuc(git_index *index, const char *buffer, size_t size) { const char *endptr; size_t len; int i; /* If called multiple times, the vector might already be initialized */ if (index->reuc._alloc_size == 0 && git_vector_init(&index->reuc, 16, reuc_cmp) < 0) return -1; while (size) { git_index_reuc_entry *lost; len = p_strnlen(buffer, size) + 1; if (size <= len) return index_error_invalid("reading reuc entries"); lost = reuc_entry_alloc(buffer); GITERR_CHECK_ALLOC(lost); size -= len; buffer += len; /* read 3 ASCII octal numbers for stage entries */ for (i = 0; i < 3; i++) { int64_t tmp; if (git__strtol64(&tmp, buffer, &endptr, 8) < 0 || !endptr || endptr == buffer || *endptr || tmp < 0 || tmp > UINT32_MAX) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } lost->mode[i] = (uint32_t)tmp; len = (endptr + 1) - buffer; if (size <= len) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry stage"); } size -= len; buffer += len; } /* read up to 3 OIDs for stage entries */ for (i = 0; i < 3; i++) { if (!lost->mode[i]) continue; if (size < 20) { index_entry_reuc_free(lost); return index_error_invalid("reading reuc entry oid"); } git_oid_fromraw(&lost->oid[i], (const unsigned char *) buffer); size -= 20; buffer += 20; } /* entry was read successfully - insert into reuc vector */ if (git_vector_insert(&index->reuc, lost) < 0) return -1; } /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->reuc, true); return 0; } static int read_conflict_names(git_index *index, const char *buffer, size_t size) { size_t len; /* This gets called multiple times, the vector might already be initialized */ if (index->names._alloc_size == 0 && git_vector_init(&index->names, 16, conflict_name_cmp) < 0) return -1; #define read_conflict_name(ptr) \ len = p_strnlen(buffer, size) + 1; \ if (size < len) { \ index_error_invalid("reading conflict name entries"); \ goto out_err; \ } \ if (len == 1) \ ptr = NULL; \ else { \ ptr = git__malloc(len); \ GITERR_CHECK_ALLOC(ptr); \ memcpy(ptr, buffer, len); \ } \ \ buffer += len; \ size -= len; while (size) { git_index_name_entry *conflict_name = git__calloc(1, sizeof(git_index_name_entry)); GITERR_CHECK_ALLOC(conflict_name); read_conflict_name(conflict_name->ancestor); read_conflict_name(conflict_name->ours); read_conflict_name(conflict_name->theirs); if (git_vector_insert(&index->names, conflict_name) < 0) goto out_err; continue; out_err: git__free(conflict_name->ancestor); git__free(conflict_name->ours); git__free(conflict_name->theirs); git__free(conflict_name); return -1; } #undef read_conflict_name /* entries are guaranteed to be sorted on-disk */ git_vector_set_sorted(&index->names, true); return 0; } static size_t index_entry_size(size_t path_len, size_t varint_len, uint32_t flags) { if (varint_len) { if (flags & GIT_IDXENTRY_EXTENDED) return offsetof(struct entry_long, path) + path_len + 1 + varint_len; else return offsetof(struct entry_short, path) + path_len + 1 + varint_len; } else { #define entry_size(type,len) ((offsetof(type, path) + (len) + 8) & ~7) if (flags & GIT_IDXENTRY_EXTENDED) return entry_size(struct entry_long, path_len); else return entry_size(struct entry_short, path_len); #undef entry_size } } static int read_entry( git_index_entry **out, size_t *out_size, git_index *index, const void *buffer, size_t buffer_size, const char *last) { size_t path_length, entry_size; const char *path_ptr; struct entry_short source; git_index_entry entry = {{0}}; bool compressed = index->version >= INDEX_VERSION_NUMBER_COMP; char *tmp_path = NULL; if (INDEX_FOOTER_SIZE + minimal_entry_size > buffer_size) return -1; /* buffer is not guaranteed to be aligned */ memcpy(&source, buffer, sizeof(struct entry_short)); entry.ctime.seconds = (git_time_t)ntohl(source.ctime.seconds); entry.ctime.nanoseconds = ntohl(source.ctime.nanoseconds); entry.mtime.seconds = (git_time_t)ntohl(source.mtime.seconds); entry.mtime.nanoseconds = ntohl(source.mtime.nanoseconds); entry.dev = ntohl(source.dev); entry.ino = ntohl(source.ino); entry.mode = ntohl(source.mode); entry.uid = ntohl(source.uid); entry.gid = ntohl(source.gid); entry.file_size = ntohl(source.file_size); git_oid_cpy(&entry.id, &source.oid); entry.flags = ntohs(source.flags); if (entry.flags & GIT_IDXENTRY_EXTENDED) { uint16_t flags_raw; size_t flags_offset; flags_offset = offsetof(struct entry_long, flags_extended); memcpy(&flags_raw, (const char *) buffer + flags_offset, sizeof(flags_raw)); flags_raw = ntohs(flags_raw); memcpy(&entry.flags_extended, &flags_raw, sizeof(flags_raw)); path_ptr = (const char *) buffer + offsetof(struct entry_long, path); } else path_ptr = (const char *) buffer + offsetof(struct entry_short, path); if (!compressed) { path_length = entry.flags & GIT_IDXENTRY_NAMEMASK; /* if this is a very long string, we must find its * real length without overflowing */ if (path_length == 0xFFF) { const char *path_end; path_end = memchr(path_ptr, '\0', buffer_size); if (path_end == NULL) return -1; path_length = path_end - path_ptr; } entry_size = index_entry_size(path_length, 0, entry.flags); entry.path = (char *)path_ptr; } else { size_t varint_len, last_len, prefix_len, suffix_len, path_len; uintmax_t strip_len; strip_len = git_decode_varint((const unsigned char *)path_ptr, &varint_len); last_len = strlen(last); if (varint_len == 0 || last_len < strip_len) return index_error_invalid("incorrect prefix length"); prefix_len = last_len - strip_len; suffix_len = strlen(path_ptr + varint_len); GITERR_CHECK_ALLOC_ADD(&path_len, prefix_len, suffix_len); GITERR_CHECK_ALLOC_ADD(&path_len, path_len, 1); tmp_path = git__malloc(path_len); GITERR_CHECK_ALLOC(tmp_path); memcpy(tmp_path, last, prefix_len); memcpy(tmp_path + prefix_len, path_ptr + varint_len, suffix_len + 1); entry_size = index_entry_size(suffix_len, varint_len, entry.flags); entry.path = tmp_path; } if (entry_size == 0) return -1; if (INDEX_FOOTER_SIZE + entry_size > buffer_size) return -1; if (index_entry_dup(out, index, &entry) < 0) { git__free(tmp_path); return -1; } git__free(tmp_path); *out_size = entry_size; return 0; } static int read_header(struct index_header *dest, const void *buffer) { const struct index_header *source = buffer; dest->signature = ntohl(source->signature); if (dest->signature != INDEX_HEADER_SIG) return index_error_invalid("incorrect header signature"); dest->version = ntohl(source->version); if (dest->version < INDEX_VERSION_NUMBER_LB || dest->version > INDEX_VERSION_NUMBER_UB) return index_error_invalid("incorrect header version"); dest->entry_count = ntohl(source->entry_count); return 0; } static size_t read_extension(git_index *index, const char *buffer, size_t buffer_size) { struct index_extension dest; size_t total_size; /* buffer is not guaranteed to be aligned */ memcpy(&dest, buffer, sizeof(struct index_extension)); dest.extension_size = ntohl(dest.extension_size); total_size = dest.extension_size + sizeof(struct index_extension); if (dest.extension_size > total_size || buffer_size < total_size || buffer_size - total_size < INDEX_FOOTER_SIZE) return 0; /* optional extension */ if (dest.signature[0] >= 'A' && dest.signature[0] <= 'Z') { /* tree cache */ if (memcmp(dest.signature, INDEX_EXT_TREECACHE_SIG, 4) == 0) { if (git_tree_cache_read(&index->tree, buffer + 8, dest.extension_size, &index->tree_pool) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_UNMERGED_SIG, 4) == 0) { if (read_reuc(index, buffer + 8, dest.extension_size) < 0) return 0; } else if (memcmp(dest.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4) == 0) { if (read_conflict_names(index, buffer + 8, dest.extension_size) < 0) return 0; } /* else, unsupported extension. We cannot parse this, but we can skip * it by returning `total_size */ } else { /* we cannot handle non-ignorable extensions; * in fact they aren't even defined in the standard */ return 0; } return total_size; } static int parse_index(git_index *index, const char *buffer, size_t buffer_size) { int error = 0; unsigned int i; struct index_header header = { 0 }; git_oid checksum_calculated, checksum_expected; const char *last = NULL; const char *empty = ""; #define seek_forward(_increase) { \ if (_increase >= buffer_size) { \ error = index_error_invalid("ran out of data while parsing"); \ goto done; } \ buffer += _increase; \ buffer_size -= _increase;\ } if (buffer_size < INDEX_HEADER_SIZE + INDEX_FOOTER_SIZE) return index_error_invalid("insufficient buffer space"); /* Precalculate the SHA1 of the files's contents -- we'll match it to * the provided SHA1 in the footer */ git_hash_buf(&checksum_calculated, buffer, buffer_size - INDEX_FOOTER_SIZE); /* Parse header */ if ((error = read_header(&header, buffer)) < 0) return error; index->version = header.version; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = empty; seek_forward(INDEX_HEADER_SIZE); assert(!index->entries.length); if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) index->entries_map, header.entry_count); else git_idxmap_resize(index->entries_map, header.entry_count); /* Parse all the entries */ for (i = 0; i < header.entry_count && buffer_size > INDEX_FOOTER_SIZE; ++i) { git_index_entry *entry = NULL; size_t entry_size; if ((error = read_entry(&entry, &entry_size, index, buffer, buffer_size, last)) < 0) { error = index_error_invalid("invalid entry"); goto done; } if ((error = git_vector_insert(&index->entries, entry)) < 0) { index_entry_free(entry); goto done; } INSERT_IN_MAP(index, entry, &error); if (error < 0) { index_entry_free(entry); goto done; } error = 0; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; seek_forward(entry_size); } if (i != header.entry_count) { error = index_error_invalid("header entries changed while parsing"); goto done; } /* There's still space for some extensions! */ while (buffer_size > INDEX_FOOTER_SIZE) { size_t extension_size; extension_size = read_extension(index, buffer, buffer_size); /* see if we have read any bytes from the extension */ if (extension_size == 0) { error = index_error_invalid("extension is truncated"); goto done; } seek_forward(extension_size); } if (buffer_size != INDEX_FOOTER_SIZE) { error = index_error_invalid( "buffer size does not match index footer size"); goto done; } /* 160-bit SHA-1 over the content of the index file before this checksum. */ git_oid_fromraw(&checksum_expected, (const unsigned char *)buffer); if (git_oid__cmp(&checksum_calculated, &checksum_expected) != 0) { error = index_error_invalid( "calculated checksum does not match expected"); goto done; } git_oid_cpy(&index->checksum, &checksum_calculated); #undef seek_forward /* Entries are stored case-sensitively on disk, so re-sort now if * in-memory index is supposed to be case-insensitive */ git_vector_set_sorted(&index->entries, !index->ignore_case); git_vector_sort(&index->entries); done: return error; } static bool is_index_extended(git_index *index) { size_t i, extended; git_index_entry *entry; extended = 0; git_vector_foreach(&index->entries, i, entry) { entry->flags &= ~GIT_IDXENTRY_EXTENDED; if (entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS) { extended++; entry->flags |= GIT_IDXENTRY_EXTENDED; } } return (extended > 0); } static int write_disk_entry(git_filebuf *file, git_index_entry *entry, const char *last) { void *mem = NULL; struct entry_short *ondisk; size_t path_len, disk_size; int varint_len = 0; char *path; const char *path_start = entry->path; size_t same_len = 0; path_len = ((struct entry_internal *)entry)->pathlen; if (last) { const char *last_c = last; while (*path_start == *last_c) { if (!*path_start || !*last_c) break; ++path_start; ++last_c; ++same_len; } path_len -= same_len; varint_len = git_encode_varint(NULL, 0, same_len); } disk_size = index_entry_size(path_len, varint_len, entry->flags); if (git_filebuf_reserve(file, &mem, disk_size) < 0) return -1; ondisk = (struct entry_short *)mem; memset(ondisk, 0x0, disk_size); /** * Yes, we have to truncate. * * The on-disk format for Index entries clearly defines * the time and size fields to be 4 bytes each -- so even if * we store these values with 8 bytes on-memory, they must * be truncated to 4 bytes before writing to disk. * * In 2038 I will be either too dead or too rich to care about this */ ondisk->ctime.seconds = htonl((uint32_t)entry->ctime.seconds); ondisk->mtime.seconds = htonl((uint32_t)entry->mtime.seconds); ondisk->ctime.nanoseconds = htonl(entry->ctime.nanoseconds); ondisk->mtime.nanoseconds = htonl(entry->mtime.nanoseconds); ondisk->dev = htonl(entry->dev); ondisk->ino = htonl(entry->ino); ondisk->mode = htonl(entry->mode); ondisk->uid = htonl(entry->uid); ondisk->gid = htonl(entry->gid); ondisk->file_size = htonl((uint32_t)entry->file_size); git_oid_cpy(&ondisk->oid, &entry->id); ondisk->flags = htons(entry->flags); if (entry->flags & GIT_IDXENTRY_EXTENDED) { struct entry_long *ondisk_ext; ondisk_ext = (struct entry_long *)ondisk; ondisk_ext->flags_extended = htons(entry->flags_extended & GIT_IDXENTRY_EXTENDED_FLAGS); path = ondisk_ext->path; disk_size -= offsetof(struct entry_long, path); } else { path = ondisk->path; disk_size -= offsetof(struct entry_short, path); } if (last) { varint_len = git_encode_varint((unsigned char *) path, disk_size, same_len); assert(varint_len > 0); path += varint_len; disk_size -= varint_len; /* * If using path compression, we are not allowed * to have additional trailing NULs. */ assert(disk_size == path_len + 1); } else { /* * If no path compression is used, we do have * NULs as padding. As such, simply assert that * we have enough space left to write the path. */ assert(disk_size > path_len); } memcpy(path, path_start, path_len + 1); return 0; } static int write_entries(git_index *index, git_filebuf *file) { int error = 0; size_t i; git_vector case_sorted, *entries; git_index_entry *entry; const char *last = NULL; /* If index->entries is sorted case-insensitively, then we need * to re-sort it case-sensitively before writing */ if (index->ignore_case) { git_vector_dup(&case_sorted, &index->entries, git_index_entry_cmp); git_vector_sort(&case_sorted); entries = &case_sorted; } else { entries = &index->entries; } if (index->version >= INDEX_VERSION_NUMBER_COMP) last = ""; git_vector_foreach(entries, i, entry) { if ((error = write_disk_entry(file, entry, last)) < 0) break; if (index->version >= INDEX_VERSION_NUMBER_COMP) last = entry->path; } if (index->ignore_case) git_vector_free(&case_sorted); return error; } static int write_extension(git_filebuf *file, struct index_extension *header, git_buf *data) { struct index_extension ondisk; memset(&ondisk, 0x0, sizeof(struct index_extension)); memcpy(&ondisk, header, 4); ondisk.extension_size = htonl(header->extension_size); git_filebuf_write(file, &ondisk, sizeof(struct index_extension)); return git_filebuf_write(file, data->ptr, data->size); } static int create_name_extension_data(git_buf *name_buf, git_index_name_entry *conflict_name) { int error = 0; if (conflict_name->ancestor == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ancestor, strlen(conflict_name->ancestor) + 1); if (error != 0) goto on_error; if (conflict_name->ours == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->ours, strlen(conflict_name->ours) + 1); if (error != 0) goto on_error; if (conflict_name->theirs == NULL) error = git_buf_put(name_buf, "\0", 1); else error = git_buf_put(name_buf, conflict_name->theirs, strlen(conflict_name->theirs) + 1); on_error: return error; } static int write_name_extension(git_index *index, git_filebuf *file) { git_buf name_buf = GIT_BUF_INIT; git_vector *out = &index->names; git_index_name_entry *conflict_name; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, conflict_name) { if ((error = create_name_extension_data(&name_buf, conflict_name)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_CONFLICT_NAME_SIG, 4); extension.extension_size = (uint32_t)name_buf.size; error = write_extension(file, &extension, &name_buf); git_buf_free(&name_buf); done: return error; } static int create_reuc_extension_data(git_buf *reuc_buf, git_index_reuc_entry *reuc) { int i; int error = 0; if ((error = git_buf_put(reuc_buf, reuc->path, strlen(reuc->path) + 1)) < 0) return error; for (i = 0; i < 3; i++) { if ((error = git_buf_printf(reuc_buf, "%o", reuc->mode[i])) < 0 || (error = git_buf_put(reuc_buf, "\0", 1)) < 0) return error; } for (i = 0; i < 3; i++) { if (reuc->mode[i] && (error = git_buf_put(reuc_buf, (char *)&reuc->oid[i].id, GIT_OID_RAWSZ)) < 0) return error; } return 0; } static int write_reuc_extension(git_index *index, git_filebuf *file) { git_buf reuc_buf = GIT_BUF_INIT; git_vector *out = &index->reuc; git_index_reuc_entry *reuc; struct index_extension extension; size_t i; int error = 0; git_vector_foreach(out, i, reuc) { if ((error = create_reuc_extension_data(&reuc_buf, reuc)) < 0) goto done; } memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_UNMERGED_SIG, 4); extension.extension_size = (uint32_t)reuc_buf.size; error = write_extension(file, &extension, &reuc_buf); git_buf_free(&reuc_buf); done: return error; } static int write_tree_extension(git_index *index, git_filebuf *file) { struct index_extension extension; git_buf buf = GIT_BUF_INIT; int error; if (index->tree == NULL) return 0; if ((error = git_tree_cache_write(&buf, index->tree)) < 0) return error; memset(&extension, 0x0, sizeof(struct index_extension)); memcpy(&extension.signature, INDEX_EXT_TREECACHE_SIG, 4); extension.extension_size = (uint32_t)buf.size; error = write_extension(file, &extension, &buf); git_buf_free(&buf); return error; } static void clear_uptodate(git_index *index) { git_index_entry *entry; size_t i; git_vector_foreach(&index->entries, i, entry) entry->flags_extended &= ~GIT_IDXENTRY_UPTODATE; } static int write_index(git_oid *checksum, git_index *index, git_filebuf *file) { git_oid hash_final; struct index_header header; bool is_extended; uint32_t index_version_number; assert(index && file); if (index->version <= INDEX_VERSION_NUMBER_EXT) { is_extended = is_index_extended(index); index_version_number = is_extended ? INDEX_VERSION_NUMBER_EXT : INDEX_VERSION_NUMBER_LB; } else { index_version_number = index->version; } header.signature = htonl(INDEX_HEADER_SIG); header.version = htonl(index_version_number); header.entry_count = htonl((uint32_t)index->entries.length); if (git_filebuf_write(file, &header, sizeof(struct index_header)) < 0) return -1; if (write_entries(index, file) < 0) return -1; /* write the tree cache extension */ if (index->tree != NULL && write_tree_extension(index, file) < 0) return -1; /* write the rename conflict extension */ if (index->names.length > 0 && write_name_extension(index, file) < 0) return -1; /* write the reuc extension */ if (index->reuc.length > 0 && write_reuc_extension(index, file) < 0) return -1; /* get out the hash for all the contents we've appended to the file */ git_filebuf_hash(&hash_final, file); git_oid_cpy(checksum, &hash_final); /* write it at the end of the file */ if (git_filebuf_write(file, hash_final.id, GIT_OID_RAWSZ) < 0) return -1; /* file entries are no longer up to date */ clear_uptodate(index); return 0; } int git_index_entry_stage(const git_index_entry *entry) { return GIT_IDXENTRY_STAGE(entry); } int git_index_entry_is_conflict(const git_index_entry *entry) { return (GIT_IDXENTRY_STAGE(entry) > 0); } typedef struct read_tree_data { git_index *index; git_vector *old_entries; git_vector *new_entries; git_vector_cmp entry_cmp; git_tree_cache *tree; } read_tree_data; static int read_tree_cb( const char *root, const git_tree_entry *tentry, void *payload) { read_tree_data *data = payload; git_index_entry *entry = NULL, *old_entry; git_buf path = GIT_BUF_INIT; size_t pos; if (git_tree_entry__is_tree(tentry)) return 0; if (git_buf_joinpath(&path, root, tentry->filename) < 0) return -1; if (index_entry_create(&entry, INDEX_OWNER(data->index), path.ptr, false) < 0) return -1; entry->mode = tentry->attr; git_oid_cpy(&entry->id, git_tree_entry_id(tentry)); /* look for corresponding old entry and copy data to new entry */ if (data->old_entries != NULL && !index_find_in_entries( &pos, data->old_entries, data->entry_cmp, path.ptr, 0, 0) && (old_entry = git_vector_get(data->old_entries, pos)) != NULL && entry->mode == old_entry->mode && git_oid_equal(&entry->id, &old_entry->id)) { index_entry_cpy(entry, old_entry); entry->flags_extended = 0; } index_entry_adjust_namemask(entry, path.size); git_buf_free(&path); if (git_vector_insert(data->new_entries, entry) < 0) { index_entry_free(entry); return -1; } return 0; } int git_index_read_tree(git_index *index, const git_tree *tree) { int error = 0; git_vector entries = GIT_VECTOR_INIT; git_idxmap *entries_map; read_tree_data data; size_t i; git_index_entry *e; if (git_idxmap_alloc(&entries_map) < 0) return -1; git_vector_set_cmp(&entries, index->entries._cmp); /* match sort */ data.index = index; data.old_entries = &index->entries; data.new_entries = &entries; data.entry_cmp = index->entries_search; index->tree = NULL; git_pool_clear(&index->tree_pool); git_vector_sort(&index->entries); if ((error = git_tree_walk(tree, GIT_TREEWALK_POST, read_tree_cb, &data)) < 0) goto cleanup; if (index->ignore_case) git_idxmap_icase_resize((khash_t(idxicase) *) entries_map, entries.length); else git_idxmap_resize(entries_map, entries.length); git_vector_foreach(&entries, i, e) { INSERT_IN_MAP_EX(index, entries_map, e, &error); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry into map"); return error; } } error = 0; git_vector_sort(&entries); if ((error = git_index_clear(index)) < 0) { /* well, this isn't good */; } else { git_vector_swap(&entries, &index->entries); entries_map = git__swap(index->entries_map, entries_map); } cleanup: git_vector_free(&entries); git_idxmap_free(entries_map); if (error < 0) return error; error = git_tree_cache_read_tree(&index->tree, tree, &index->tree_pool); return error; } static int git_index_read_iterator( git_index *index, git_iterator *new_iterator, size_t new_length_hint) { git_vector new_entries = GIT_VECTOR_INIT, remove_entries = GIT_VECTOR_INIT; git_idxmap *new_entries_map = NULL; git_iterator *index_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; const git_index_entry *old_entry, *new_entry; git_index_entry *entry; size_t i; int error; assert((new_iterator->flags & GIT_ITERATOR_DONT_IGNORE_CASE)); if ((error = git_vector_init(&new_entries, new_length_hint, index->entries._cmp)) < 0 || (error = git_vector_init(&remove_entries, index->entries.length, NULL)) < 0 || (error = git_idxmap_alloc(&new_entries_map)) < 0) goto done; if (index->ignore_case && new_length_hint) git_idxmap_icase_resize((khash_t(idxicase) *) new_entries_map, new_length_hint); else if (new_length_hint) git_idxmap_resize(new_entries_map, new_length_hint); opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&index_iterator, git_index_owner(index), index, &opts)) < 0 || ((error = git_iterator_current(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) || ((error = git_iterator_current(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER)) goto done; while (true) { git_index_entry *dup_entry = NULL, *add_entry = NULL, *remove_entry = NULL; int diff; error = 0; if (old_entry && new_entry) diff = git_index_entry_cmp(old_entry, new_entry); else if (!old_entry && new_entry) diff = 1; else if (old_entry && !new_entry) diff = -1; else break; if (diff < 0) { remove_entry = (git_index_entry *)old_entry; } else if (diff > 0) { dup_entry = (git_index_entry *)new_entry; } else { /* Path and stage are equal, if the OID is equal, keep it to * keep the stat cache data. */ if (git_oid_equal(&old_entry->id, &new_entry->id) && old_entry->mode == new_entry->mode) { add_entry = (git_index_entry *)old_entry; } else { dup_entry = (git_index_entry *)new_entry; remove_entry = (git_index_entry *)old_entry; } } if (dup_entry) { if ((error = index_entry_dup_nocache(&add_entry, index, dup_entry)) < 0) goto done; index_entry_adjust_namemask(add_entry, ((struct entry_internal *)add_entry)->pathlen); } /* invalidate this path in the tree cache if this is new (to * invalidate the parent trees) */ if (dup_entry && !remove_entry && index->tree) git_tree_cache_invalidate_path(index->tree, dup_entry->path); if (add_entry) { if ((error = git_vector_insert(&new_entries, add_entry)) == 0) INSERT_IN_MAP_EX(index, new_entries_map, add_entry, &error); } if (remove_entry && error >= 0) error = git_vector_insert(&remove_entries, remove_entry); if (error < 0) { giterr_set(GITERR_INDEX, "failed to insert entry"); goto done; } if (diff <= 0) { if ((error = git_iterator_advance(&old_entry, index_iterator)) < 0 && error != GIT_ITEROVER) goto done; } if (diff >= 0) { if ((error = git_iterator_advance(&new_entry, new_iterator)) < 0 && error != GIT_ITEROVER) goto done; } } git_index_name_clear(index); git_index_reuc_clear(index); git_vector_swap(&new_entries, &index->entries); new_entries_map = git__swap(index->entries_map, new_entries_map); git_vector_foreach(&remove_entries, i, entry) { if (index->tree) git_tree_cache_invalidate_path(index->tree, entry->path); index_entry_free(entry); } clear_uptodate(index); error = 0; done: git_idxmap_free(new_entries_map); git_vector_free(&new_entries); git_vector_free(&remove_entries); git_iterator_free(index_iterator); return error; } int git_index_read_index( git_index *index, const git_index *new_index) { git_iterator *new_iterator = NULL; git_iterator_options opts = GIT_ITERATOR_OPTIONS_INIT; int error; opts.flags = GIT_ITERATOR_DONT_IGNORE_CASE | GIT_ITERATOR_INCLUDE_CONFLICTS; if ((error = git_iterator_for_index(&new_iterator, git_index_owner(new_index), (git_index *)new_index, &opts)) < 0 || (error = git_index_read_iterator(index, new_iterator, new_index->entries.length)) < 0) goto done; done: git_iterator_free(new_iterator); return error; } git_repository *git_index_owner(const git_index *index) { return INDEX_OWNER(index); } enum { INDEX_ACTION_NONE = 0, INDEX_ACTION_UPDATE = 1, INDEX_ACTION_REMOVE = 2, INDEX_ACTION_ADDALL = 3, }; int git_index_add_all( git_index *index, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_repository *repo; git_iterator *wditer = NULL; git_pathspec ps; bool no_fnmatch = (flags & GIT_INDEX_ADD_DISABLE_PATHSPEC_MATCH) != 0; assert(index); repo = INDEX_OWNER(index); if ((error = git_repository__ensure_not_bare(repo, "index add all")) < 0) return error; if ((error = git_pathspec__init(&ps, paths)) < 0) return error; /* optionally check that pathspec doesn't mention any ignored files */ if ((flags & GIT_INDEX_ADD_CHECK_PATHSPEC) != 0 && (flags & GIT_INDEX_ADD_FORCE) == 0 && (error = git_ignore__check_pathspec_for_exact_ignores( repo, &ps.pathspec, no_fnmatch)) < 0) goto cleanup; error = index_apply_to_wd_diff(index, INDEX_ACTION_ADDALL, paths, flags, cb, payload); if (error) giterr_set_after_callback(error); cleanup: git_iterator_free(wditer); git_pathspec__clear(&ps); return error; } struct foreach_diff_data { git_index *index; const git_pathspec *pathspec; unsigned int flags; git_index_matched_path_cb cb; void *payload; }; static int apply_each_file(const git_diff_delta *delta, float progress, void *payload) { struct foreach_diff_data *data = payload; const char *match, *path; int error = 0; GIT_UNUSED(progress); path = delta->old_file.path; /* We only want those which match the pathspecs */ if (!git_pathspec__match( &data->pathspec->pathspec, path, false, (bool)data->index->ignore_case, &match, NULL)) return 0; if (data->cb) error = data->cb(path, match, data->payload); if (error > 0) /* skip this entry */ return 0; if (error < 0) /* actual error */ return error; /* If the workdir item does not exist, remove it from the index. */ if ((delta->new_file.flags & GIT_DIFF_FLAG_EXISTS) == 0) error = git_index_remove_bypath(data->index, path); else error = git_index_add_bypath(data->index, delta->new_file.path); return error; } static int index_apply_to_wd_diff(git_index *index, int action, const git_strarray *paths, unsigned int flags, git_index_matched_path_cb cb, void *payload) { int error; git_diff *diff; git_pathspec ps; git_repository *repo; git_diff_options opts = GIT_DIFF_OPTIONS_INIT; struct foreach_diff_data data = { index, NULL, flags, cb, payload, }; assert(index); assert(action == INDEX_ACTION_UPDATE || action == INDEX_ACTION_ADDALL); repo = INDEX_OWNER(index); if (!repo) { return create_index_error(-1, "cannot run update; the index is not backed up by a repository."); } /* * We do the matching ourselves intead of passing the list to * diff because we want to tell the callback which one * matched, which we do not know if we ask diff to filter for us. */ if ((error = git_pathspec__init(&ps, paths)) < 0) return error; opts.flags = GIT_DIFF_INCLUDE_TYPECHANGE; if (action == INDEX_ACTION_ADDALL) { opts.flags |= GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_RECURSE_UNTRACKED_DIRS; if (flags == GIT_INDEX_ADD_FORCE) opts.flags |= GIT_DIFF_INCLUDE_IGNORED; } if ((error = git_diff_index_to_workdir(&diff, repo, index, &opts)) < 0) goto cleanup; data.pathspec = &ps; error = git_diff_foreach(diff, apply_each_file, NULL, NULL, NULL, &data); git_diff_free(diff); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); cleanup: git_pathspec__clear(&ps); return error; } static int index_apply_to_all( git_index *index, int action, const git_strarray *paths, git_index_matched_path_cb cb, void *payload) { int error = 0; size_t i; git_pathspec ps; const char *match; git_buf path = GIT_BUF_INIT; assert(index); if ((error = git_pathspec__init(&ps, paths)) < 0) return error; git_vector_sort(&index->entries); for (i = 0; !error && i < index->entries.length; ++i) { git_index_entry *entry = git_vector_get(&index->entries, i); /* check if path actually matches */ if (!git_pathspec__match( &ps.pathspec, entry->path, false, (bool)index->ignore_case, &match, NULL)) continue; /* issue notification callback if requested */ if (cb && (error = cb(entry->path, match, payload)) != 0) { if (error > 0) { /* return > 0 means skip this one */ error = 0; continue; } if (error < 0) /* return < 0 means abort */ break; } /* index manipulation may alter entry, so don't depend on it */ if ((error = git_buf_sets(&path, entry->path)) < 0) break; switch (action) { case INDEX_ACTION_NONE: break; case INDEX_ACTION_UPDATE: error = git_index_add_bypath(index, path.ptr); if (error == GIT_ENOTFOUND) { giterr_clear(); error = git_index_remove_bypath(index, path.ptr); if (!error) /* back up foreach if we removed this */ i--; } break; case INDEX_ACTION_REMOVE: if (!(error = git_index_remove_bypath(index, path.ptr))) i--; /* back up foreach if we removed this */ break; default: giterr_set(GITERR_INVALID, "unknown index action %d", action); error = -1; break; } } git_buf_free(&path); git_pathspec__clear(&ps); return error; } int git_index_remove_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_all( index, INDEX_ACTION_REMOVE, pathspec, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_update_all( git_index *index, const git_strarray *pathspec, git_index_matched_path_cb cb, void *payload) { int error = index_apply_to_wd_diff(index, INDEX_ACTION_UPDATE, pathspec, 0, cb, payload); if (error) /* make sure error is set if callback stopped iteration */ giterr_set_after_callback(error); return error; } int git_index_snapshot_new(git_vector *snap, git_index *index) { int error; GIT_REFCOUNT_INC(index); git_atomic_inc(&index->readers); git_vector_sort(&index->entries); error = git_vector_dup(snap, &index->entries, index->entries._cmp); if (error < 0) git_index_free(index); return error; } void git_index_snapshot_release(git_vector *snap, git_index *index) { git_vector_free(snap); git_atomic_dec(&index->readers); git_index_free(index); } int git_index_snapshot_find( size_t *out, git_vector *entries, git_vector_cmp entry_srch, const char *path, size_t path_len, int stage) { return index_find_in_entries(out, entries, entry_srch, path, path_len, stage); } int git_indexwriter_init( git_indexwriter *writer, git_index *index) { int error; GIT_REFCOUNT_INC(index); writer->index = index; if (!index->index_file_path) return create_index_error(-1, "failed to write index: The index is in-memory only"); if ((error = git_filebuf_open( &writer->file, index->index_file_path, GIT_FILEBUF_HASH_CONTENTS, GIT_INDEX_FILE_MODE)) < 0) { if (error == GIT_ELOCKED) giterr_set(GITERR_INDEX, "the index is locked; this might be due to a concurrent or crashed process"); return error; } writer->should_write = 1; return 0; } int git_indexwriter_init_for_operation( git_indexwriter *writer, git_repository *repo, unsigned int *checkout_strategy) { git_index *index; int error; if ((error = git_repository_index__weakptr(&index, repo)) < 0 || (error = git_indexwriter_init(writer, index)) < 0) return error; writer->should_write = (*checkout_strategy & GIT_CHECKOUT_DONT_WRITE_INDEX) == 0; *checkout_strategy |= GIT_CHECKOUT_DONT_WRITE_INDEX; return 0; } int git_indexwriter_commit(git_indexwriter *writer) { int error; git_oid checksum = {{ 0 }}; if (!writer->should_write) return 0; git_vector_sort(&writer->index->entries); git_vector_sort(&writer->index->reuc); if ((error = write_index(&checksum, writer->index, &writer->file)) < 0) { git_indexwriter_cleanup(writer); return error; } if ((error = git_filebuf_commit(&writer->file)) < 0) return error; if ((error = git_futils_filestamp_check( &writer->index->stamp, writer->index->index_file_path)) < 0) { giterr_set(GITERR_OS, "could not read index timestamp"); return -1; } writer->index->on_disk = 1; git_oid_cpy(&writer->index->checksum, &checksum); git_index_free(writer->index); writer->index = NULL; return 0; } void git_indexwriter_cleanup(git_indexwriter *writer) { git_filebuf_cleanup(&writer->file); git_index_free(writer->index); writer->index = NULL; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_664_0
crossvul-cpp_data_bad_3121_0
/* * Copyright © 2014 Broadcom * * 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 (including the next * paragraph) 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 <linux/module.h> #include <linux/platform_device.h> #include <linux/pm_runtime.h> #include <linux/device.h> #include <linux/io.h> #include "uapi/drm/vc4_drm.h" #include "vc4_drv.h" #include "vc4_regs.h" #include "vc4_trace.h" static void vc4_queue_hangcheck(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); mod_timer(&vc4->hangcheck.timer, round_jiffies_up(jiffies + msecs_to_jiffies(100))); } struct vc4_hang_state { struct drm_vc4_get_hang_state user_state; u32 bo_count; struct drm_gem_object **bo; }; static void vc4_free_hang_state(struct drm_device *dev, struct vc4_hang_state *state) { unsigned int i; for (i = 0; i < state->user_state.bo_count; i++) drm_gem_object_unreference_unlocked(state->bo[i]); kfree(state); } int vc4_get_hang_state_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_vc4_get_hang_state *get_state = data; struct drm_vc4_get_hang_state_bo *bo_state; struct vc4_hang_state *kernel_state; struct drm_vc4_get_hang_state *state; struct vc4_dev *vc4 = to_vc4_dev(dev); unsigned long irqflags; u32 i; int ret = 0; spin_lock_irqsave(&vc4->job_lock, irqflags); kernel_state = vc4->hang_state; if (!kernel_state) { spin_unlock_irqrestore(&vc4->job_lock, irqflags); return -ENOENT; } state = &kernel_state->user_state; /* If the user's array isn't big enough, just return the * required array size. */ if (get_state->bo_count < state->bo_count) { get_state->bo_count = state->bo_count; spin_unlock_irqrestore(&vc4->job_lock, irqflags); return 0; } vc4->hang_state = NULL; spin_unlock_irqrestore(&vc4->job_lock, irqflags); /* Save the user's BO pointer, so we don't stomp it with the memcpy. */ state->bo = get_state->bo; memcpy(get_state, state, sizeof(*state)); bo_state = kcalloc(state->bo_count, sizeof(*bo_state), GFP_KERNEL); if (!bo_state) { ret = -ENOMEM; goto err_free; } for (i = 0; i < state->bo_count; i++) { struct vc4_bo *vc4_bo = to_vc4_bo(kernel_state->bo[i]); u32 handle; ret = drm_gem_handle_create(file_priv, kernel_state->bo[i], &handle); if (ret) { state->bo_count = i - 1; goto err; } bo_state[i].handle = handle; bo_state[i].paddr = vc4_bo->base.paddr; bo_state[i].size = vc4_bo->base.base.size; } if (copy_to_user((void __user *)(uintptr_t)get_state->bo, bo_state, state->bo_count * sizeof(*bo_state))) ret = -EFAULT; kfree(bo_state); err_free: vc4_free_hang_state(dev, kernel_state); err: return ret; } static void vc4_save_hang_state(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); struct drm_vc4_get_hang_state *state; struct vc4_hang_state *kernel_state; struct vc4_exec_info *exec[2]; struct vc4_bo *bo; unsigned long irqflags; unsigned int i, j, unref_list_count, prev_idx; kernel_state = kcalloc(1, sizeof(*kernel_state), GFP_KERNEL); if (!kernel_state) return; state = &kernel_state->user_state; spin_lock_irqsave(&vc4->job_lock, irqflags); exec[0] = vc4_first_bin_job(vc4); exec[1] = vc4_first_render_job(vc4); if (!exec[0] && !exec[1]) { spin_unlock_irqrestore(&vc4->job_lock, irqflags); return; } /* Get the bos from both binner and renderer into hang state. */ state->bo_count = 0; for (i = 0; i < 2; i++) { if (!exec[i]) continue; unref_list_count = 0; list_for_each_entry(bo, &exec[i]->unref_list, unref_head) unref_list_count++; state->bo_count += exec[i]->bo_count + unref_list_count; } kernel_state->bo = kcalloc(state->bo_count, sizeof(*kernel_state->bo), GFP_ATOMIC); if (!kernel_state->bo) { spin_unlock_irqrestore(&vc4->job_lock, irqflags); return; } prev_idx = 0; for (i = 0; i < 2; i++) { if (!exec[i]) continue; for (j = 0; j < exec[i]->bo_count; j++) { drm_gem_object_reference(&exec[i]->bo[j]->base); kernel_state->bo[j + prev_idx] = &exec[i]->bo[j]->base; } list_for_each_entry(bo, &exec[i]->unref_list, unref_head) { drm_gem_object_reference(&bo->base.base); kernel_state->bo[j + prev_idx] = &bo->base.base; j++; } prev_idx = j + 1; } if (exec[0]) state->start_bin = exec[0]->ct0ca; if (exec[1]) state->start_render = exec[1]->ct1ca; spin_unlock_irqrestore(&vc4->job_lock, irqflags); state->ct0ca = V3D_READ(V3D_CTNCA(0)); state->ct0ea = V3D_READ(V3D_CTNEA(0)); state->ct1ca = V3D_READ(V3D_CTNCA(1)); state->ct1ea = V3D_READ(V3D_CTNEA(1)); state->ct0cs = V3D_READ(V3D_CTNCS(0)); state->ct1cs = V3D_READ(V3D_CTNCS(1)); state->ct0ra0 = V3D_READ(V3D_CT00RA0); state->ct1ra0 = V3D_READ(V3D_CT01RA0); state->bpca = V3D_READ(V3D_BPCA); state->bpcs = V3D_READ(V3D_BPCS); state->bpoa = V3D_READ(V3D_BPOA); state->bpos = V3D_READ(V3D_BPOS); state->vpmbase = V3D_READ(V3D_VPMBASE); state->dbge = V3D_READ(V3D_DBGE); state->fdbgo = V3D_READ(V3D_FDBGO); state->fdbgb = V3D_READ(V3D_FDBGB); state->fdbgr = V3D_READ(V3D_FDBGR); state->fdbgs = V3D_READ(V3D_FDBGS); state->errstat = V3D_READ(V3D_ERRSTAT); spin_lock_irqsave(&vc4->job_lock, irqflags); if (vc4->hang_state) { spin_unlock_irqrestore(&vc4->job_lock, irqflags); vc4_free_hang_state(dev, kernel_state); } else { vc4->hang_state = kernel_state; spin_unlock_irqrestore(&vc4->job_lock, irqflags); } } static void vc4_reset(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); DRM_INFO("Resetting GPU.\n"); mutex_lock(&vc4->power_lock); if (vc4->power_refcount) { /* Power the device off and back on the by dropping the * reference on runtime PM. */ pm_runtime_put_sync_suspend(&vc4->v3d->pdev->dev); pm_runtime_get_sync(&vc4->v3d->pdev->dev); } mutex_unlock(&vc4->power_lock); vc4_irq_reset(dev); /* Rearm the hangcheck -- another job might have been waiting * for our hung one to get kicked off, and vc4_irq_reset() * would have started it. */ vc4_queue_hangcheck(dev); } static void vc4_reset_work(struct work_struct *work) { struct vc4_dev *vc4 = container_of(work, struct vc4_dev, hangcheck.reset_work); vc4_save_hang_state(vc4->dev); vc4_reset(vc4->dev); } static void vc4_hangcheck_elapsed(unsigned long data) { struct drm_device *dev = (struct drm_device *)data; struct vc4_dev *vc4 = to_vc4_dev(dev); uint32_t ct0ca, ct1ca; unsigned long irqflags; struct vc4_exec_info *bin_exec, *render_exec; spin_lock_irqsave(&vc4->job_lock, irqflags); bin_exec = vc4_first_bin_job(vc4); render_exec = vc4_first_render_job(vc4); /* If idle, we can stop watching for hangs. */ if (!bin_exec && !render_exec) { spin_unlock_irqrestore(&vc4->job_lock, irqflags); return; } ct0ca = V3D_READ(V3D_CTNCA(0)); ct1ca = V3D_READ(V3D_CTNCA(1)); /* If we've made any progress in execution, rearm the timer * and wait. */ if ((bin_exec && ct0ca != bin_exec->last_ct0ca) || (render_exec && ct1ca != render_exec->last_ct1ca)) { if (bin_exec) bin_exec->last_ct0ca = ct0ca; if (render_exec) render_exec->last_ct1ca = ct1ca; spin_unlock_irqrestore(&vc4->job_lock, irqflags); vc4_queue_hangcheck(dev); return; } spin_unlock_irqrestore(&vc4->job_lock, irqflags); /* We've gone too long with no progress, reset. This has to * be done from a work struct, since resetting can sleep and * this timer hook isn't allowed to. */ schedule_work(&vc4->hangcheck.reset_work); } static void submit_cl(struct drm_device *dev, uint32_t thread, uint32_t start, uint32_t end) { struct vc4_dev *vc4 = to_vc4_dev(dev); /* Set the current and end address of the control list. * Writing the end register is what starts the job. */ V3D_WRITE(V3D_CTNCA(thread), start); V3D_WRITE(V3D_CTNEA(thread), end); } int vc4_wait_for_seqno(struct drm_device *dev, uint64_t seqno, uint64_t timeout_ns, bool interruptible) { struct vc4_dev *vc4 = to_vc4_dev(dev); int ret = 0; unsigned long timeout_expire; DEFINE_WAIT(wait); if (vc4->finished_seqno >= seqno) return 0; if (timeout_ns == 0) return -ETIME; timeout_expire = jiffies + nsecs_to_jiffies(timeout_ns); trace_vc4_wait_for_seqno_begin(dev, seqno, timeout_ns); for (;;) { prepare_to_wait(&vc4->job_wait_queue, &wait, interruptible ? TASK_INTERRUPTIBLE : TASK_UNINTERRUPTIBLE); if (interruptible && signal_pending(current)) { ret = -ERESTARTSYS; break; } if (vc4->finished_seqno >= seqno) break; if (timeout_ns != ~0ull) { if (time_after_eq(jiffies, timeout_expire)) { ret = -ETIME; break; } schedule_timeout(timeout_expire - jiffies); } else { schedule(); } } finish_wait(&vc4->job_wait_queue, &wait); trace_vc4_wait_for_seqno_end(dev, seqno); return ret; } static void vc4_flush_caches(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); /* Flush the GPU L2 caches. These caches sit on top of system * L3 (the 128kb or so shared with the CPU), and are * non-allocating in the L3. */ V3D_WRITE(V3D_L2CACTL, V3D_L2CACTL_L2CCLR); V3D_WRITE(V3D_SLCACTL, VC4_SET_FIELD(0xf, V3D_SLCACTL_T1CC) | VC4_SET_FIELD(0xf, V3D_SLCACTL_T0CC) | VC4_SET_FIELD(0xf, V3D_SLCACTL_UCC) | VC4_SET_FIELD(0xf, V3D_SLCACTL_ICC)); } /* Sets the registers for the next job to be actually be executed in * the hardware. * * The job_lock should be held during this. */ void vc4_submit_next_bin_job(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); struct vc4_exec_info *exec; again: exec = vc4_first_bin_job(vc4); if (!exec) return; vc4_flush_caches(dev); /* Either put the job in the binner if it uses the binner, or * immediately move it to the to-be-rendered queue. */ if (exec->ct0ca != exec->ct0ea) { submit_cl(dev, 0, exec->ct0ca, exec->ct0ea); } else { vc4_move_job_to_render(dev, exec); goto again; } } void vc4_submit_next_render_job(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); struct vc4_exec_info *exec = vc4_first_render_job(vc4); if (!exec) return; submit_cl(dev, 1, exec->ct1ca, exec->ct1ea); } void vc4_move_job_to_render(struct drm_device *dev, struct vc4_exec_info *exec) { struct vc4_dev *vc4 = to_vc4_dev(dev); bool was_empty = list_empty(&vc4->render_job_list); list_move_tail(&exec->head, &vc4->render_job_list); if (was_empty) vc4_submit_next_render_job(dev); } static void vc4_update_bo_seqnos(struct vc4_exec_info *exec, uint64_t seqno) { struct vc4_bo *bo; unsigned i; for (i = 0; i < exec->bo_count; i++) { bo = to_vc4_bo(&exec->bo[i]->base); bo->seqno = seqno; } list_for_each_entry(bo, &exec->unref_list, unref_head) { bo->seqno = seqno; } for (i = 0; i < exec->rcl_write_bo_count; i++) { bo = to_vc4_bo(&exec->rcl_write_bo[i]->base); bo->write_seqno = seqno; } } /* Queues a struct vc4_exec_info for execution. If no job is * currently executing, then submits it. * * Unlike most GPUs, our hardware only handles one command list at a * time. To queue multiple jobs at once, we'd need to edit the * previous command list to have a jump to the new one at the end, and * then bump the end address. That's a change for a later date, * though. */ static void vc4_queue_submit(struct drm_device *dev, struct vc4_exec_info *exec) { struct vc4_dev *vc4 = to_vc4_dev(dev); uint64_t seqno; unsigned long irqflags; spin_lock_irqsave(&vc4->job_lock, irqflags); seqno = ++vc4->emit_seqno; exec->seqno = seqno; vc4_update_bo_seqnos(exec, seqno); list_add_tail(&exec->head, &vc4->bin_job_list); /* If no job was executing, kick ours off. Otherwise, it'll * get started when the previous job's flush done interrupt * occurs. */ if (vc4_first_bin_job(vc4) == exec) { vc4_submit_next_bin_job(dev); vc4_queue_hangcheck(dev); } spin_unlock_irqrestore(&vc4->job_lock, irqflags); } /** * Looks up a bunch of GEM handles for BOs and stores the array for * use in the command validator that actually writes relocated * addresses pointing to them. */ static int vc4_cl_lookup_bos(struct drm_device *dev, struct drm_file *file_priv, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; uint32_t *handles; int ret = 0; int i; exec->bo_count = args->bo_handle_count; if (!exec->bo_count) { /* See comment on bo_index for why we have to check * this. */ DRM_ERROR("Rendering requires BOs to validate\n"); return -EINVAL; } exec->bo = drm_calloc_large(exec->bo_count, sizeof(struct drm_gem_cma_object *)); if (!exec->bo) { DRM_ERROR("Failed to allocate validated BO pointers\n"); return -ENOMEM; } handles = drm_malloc_ab(exec->bo_count, sizeof(uint32_t)); if (!handles) { ret = -ENOMEM; DRM_ERROR("Failed to allocate incoming GEM handles\n"); goto fail; } if (copy_from_user(handles, (void __user *)(uintptr_t)args->bo_handles, exec->bo_count * sizeof(uint32_t))) { ret = -EFAULT; DRM_ERROR("Failed to copy in GEM handles\n"); goto fail; } spin_lock(&file_priv->table_lock); for (i = 0; i < exec->bo_count; i++) { struct drm_gem_object *bo = idr_find(&file_priv->object_idr, handles[i]); if (!bo) { DRM_ERROR("Failed to look up GEM BO %d: %d\n", i, handles[i]); ret = -EINVAL; spin_unlock(&file_priv->table_lock); goto fail; } drm_gem_object_reference(bo); exec->bo[i] = (struct drm_gem_cma_object *)bo; } spin_unlock(&file_priv->table_lock); fail: drm_free_large(handles); return ret; } static int vc4_get_bcl(struct drm_device *dev, struct vc4_exec_info *exec) { struct drm_vc4_submit_cl *args = exec->args; void *temp = NULL; void *bin; int ret = 0; uint32_t bin_offset = 0; uint32_t shader_rec_offset = roundup(bin_offset + args->bin_cl_size, 16); uint32_t uniforms_offset = shader_rec_offset + args->shader_rec_size; uint32_t exec_size = uniforms_offset + args->uniforms_size; uint32_t temp_size = exec_size + (sizeof(struct vc4_shader_state) * args->shader_rec_count); struct vc4_bo *bo; if (uniforms_offset < shader_rec_offset || exec_size < uniforms_offset || args->shader_rec_count >= (UINT_MAX / sizeof(struct vc4_shader_state)) || temp_size < exec_size) { DRM_ERROR("overflow in exec arguments\n"); goto fail; } /* Allocate space where we'll store the copied in user command lists * and shader records. * * We don't just copy directly into the BOs because we need to * read the contents back for validation, and I think the * bo->vaddr is uncached access. */ temp = drm_malloc_ab(temp_size, 1); if (!temp) { DRM_ERROR("Failed to allocate storage for copying " "in bin/render CLs.\n"); ret = -ENOMEM; goto fail; } bin = temp + bin_offset; exec->shader_rec_u = temp + shader_rec_offset; exec->uniforms_u = temp + uniforms_offset; exec->shader_state = temp + exec_size; exec->shader_state_size = args->shader_rec_count; if (copy_from_user(bin, (void __user *)(uintptr_t)args->bin_cl, args->bin_cl_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->shader_rec_u, (void __user *)(uintptr_t)args->shader_rec, args->shader_rec_size)) { ret = -EFAULT; goto fail; } if (copy_from_user(exec->uniforms_u, (void __user *)(uintptr_t)args->uniforms, args->uniforms_size)) { ret = -EFAULT; goto fail; } bo = vc4_bo_create(dev, exec_size, true); if (IS_ERR(bo)) { DRM_ERROR("Couldn't allocate BO for binning\n"); ret = PTR_ERR(bo); goto fail; } exec->exec_bo = &bo->base; list_add_tail(&to_vc4_bo(&exec->exec_bo->base)->unref_head, &exec->unref_list); exec->ct0ca = exec->exec_bo->paddr + bin_offset; exec->bin_u = bin; exec->shader_rec_v = exec->exec_bo->vaddr + shader_rec_offset; exec->shader_rec_p = exec->exec_bo->paddr + shader_rec_offset; exec->shader_rec_size = args->shader_rec_size; exec->uniforms_v = exec->exec_bo->vaddr + uniforms_offset; exec->uniforms_p = exec->exec_bo->paddr + uniforms_offset; exec->uniforms_size = args->uniforms_size; ret = vc4_validate_bin_cl(dev, exec->exec_bo->vaddr + bin_offset, bin, exec); if (ret) goto fail; ret = vc4_validate_shader_recs(dev, exec); if (ret) goto fail; /* Block waiting on any previous rendering into the CS's VBO, * IB, or textures, so that pixels are actually written by the * time we try to read them. */ ret = vc4_wait_for_seqno(dev, exec->bin_dep_seqno, ~0ull, true); fail: drm_free_large(temp); return ret; } static void vc4_complete_exec(struct drm_device *dev, struct vc4_exec_info *exec) { struct vc4_dev *vc4 = to_vc4_dev(dev); unsigned i; if (exec->bo) { for (i = 0; i < exec->bo_count; i++) drm_gem_object_unreference_unlocked(&exec->bo[i]->base); drm_free_large(exec->bo); } while (!list_empty(&exec->unref_list)) { struct vc4_bo *bo = list_first_entry(&exec->unref_list, struct vc4_bo, unref_head); list_del(&bo->unref_head); drm_gem_object_unreference_unlocked(&bo->base.base); } mutex_lock(&vc4->power_lock); if (--vc4->power_refcount == 0) { pm_runtime_mark_last_busy(&vc4->v3d->pdev->dev); pm_runtime_put_autosuspend(&vc4->v3d->pdev->dev); } mutex_unlock(&vc4->power_lock); kfree(exec); } void vc4_job_handle_completed(struct vc4_dev *vc4) { unsigned long irqflags; struct vc4_seqno_cb *cb, *cb_temp; spin_lock_irqsave(&vc4->job_lock, irqflags); while (!list_empty(&vc4->job_done_list)) { struct vc4_exec_info *exec = list_first_entry(&vc4->job_done_list, struct vc4_exec_info, head); list_del(&exec->head); spin_unlock_irqrestore(&vc4->job_lock, irqflags); vc4_complete_exec(vc4->dev, exec); spin_lock_irqsave(&vc4->job_lock, irqflags); } list_for_each_entry_safe(cb, cb_temp, &vc4->seqno_cb_list, work.entry) { if (cb->seqno <= vc4->finished_seqno) { list_del_init(&cb->work.entry); schedule_work(&cb->work); } } spin_unlock_irqrestore(&vc4->job_lock, irqflags); } static void vc4_seqno_cb_work(struct work_struct *work) { struct vc4_seqno_cb *cb = container_of(work, struct vc4_seqno_cb, work); cb->func(cb); } int vc4_queue_seqno_cb(struct drm_device *dev, struct vc4_seqno_cb *cb, uint64_t seqno, void (*func)(struct vc4_seqno_cb *cb)) { struct vc4_dev *vc4 = to_vc4_dev(dev); int ret = 0; unsigned long irqflags; cb->func = func; INIT_WORK(&cb->work, vc4_seqno_cb_work); spin_lock_irqsave(&vc4->job_lock, irqflags); if (seqno > vc4->finished_seqno) { cb->seqno = seqno; list_add_tail(&cb->work.entry, &vc4->seqno_cb_list); } else { schedule_work(&cb->work); } spin_unlock_irqrestore(&vc4->job_lock, irqflags); return ret; } /* Scheduled when any job has been completed, this walks the list of * jobs that had completed and unrefs their BOs and frees their exec * structs. */ static void vc4_job_done_work(struct work_struct *work) { struct vc4_dev *vc4 = container_of(work, struct vc4_dev, job_done_work); vc4_job_handle_completed(vc4); } static int vc4_wait_for_seqno_ioctl_helper(struct drm_device *dev, uint64_t seqno, uint64_t *timeout_ns) { unsigned long start = jiffies; int ret = vc4_wait_for_seqno(dev, seqno, *timeout_ns, true); if ((ret == -EINTR || ret == -ERESTARTSYS) && *timeout_ns != ~0ull) { uint64_t delta = jiffies_to_nsecs(jiffies - start); if (*timeout_ns >= delta) *timeout_ns -= delta; } return ret; } int vc4_wait_seqno_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_vc4_wait_seqno *args = data; return vc4_wait_for_seqno_ioctl_helper(dev, args->seqno, &args->timeout_ns); } int vc4_wait_bo_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { int ret; struct drm_vc4_wait_bo *args = data; struct drm_gem_object *gem_obj; struct vc4_bo *bo; if (args->pad != 0) return -EINVAL; gem_obj = drm_gem_object_lookup(file_priv, args->handle); if (!gem_obj) { DRM_ERROR("Failed to look up GEM BO %d\n", args->handle); return -EINVAL; } bo = to_vc4_bo(gem_obj); ret = vc4_wait_for_seqno_ioctl_helper(dev, bo->seqno, &args->timeout_ns); drm_gem_object_unreference_unlocked(gem_obj); return ret; } /** * Submits a command list to the VC4. * * This is what is called batchbuffer emitting on other hardware. */ int vc4_submit_cl_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vc4_dev *vc4 = to_vc4_dev(dev); struct drm_vc4_submit_cl *args = data; struct vc4_exec_info *exec; int ret = 0; if ((args->flags & ~VC4_SUBMIT_CL_USE_CLEAR_COLOR) != 0) { DRM_ERROR("Unknown flags: 0x%02x\n", args->flags); return -EINVAL; } exec = kcalloc(1, sizeof(*exec), GFP_KERNEL); if (!exec) { DRM_ERROR("malloc failure on exec struct\n"); return -ENOMEM; } mutex_lock(&vc4->power_lock); if (vc4->power_refcount++ == 0) ret = pm_runtime_get_sync(&vc4->v3d->pdev->dev); mutex_unlock(&vc4->power_lock); if (ret < 0) { kfree(exec); return ret; } exec->args = args; INIT_LIST_HEAD(&exec->unref_list); ret = vc4_cl_lookup_bos(dev, file_priv, exec); if (ret) goto fail; if (exec->args->bin_cl_size != 0) { ret = vc4_get_bcl(dev, exec); if (ret) goto fail; } else { exec->ct0ca = 0; exec->ct0ea = 0; } ret = vc4_get_rcl(dev, exec); if (ret) goto fail; /* Clear this out of the struct we'll be putting in the queue, * since it's part of our stack. */ exec->args = NULL; vc4_queue_submit(dev, exec); /* Return the seqno for our job. */ args->seqno = vc4->emit_seqno; return 0; fail: vc4_complete_exec(vc4->dev, exec); return ret; } void vc4_gem_init(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); INIT_LIST_HEAD(&vc4->bin_job_list); INIT_LIST_HEAD(&vc4->render_job_list); INIT_LIST_HEAD(&vc4->job_done_list); INIT_LIST_HEAD(&vc4->seqno_cb_list); spin_lock_init(&vc4->job_lock); INIT_WORK(&vc4->hangcheck.reset_work, vc4_reset_work); setup_timer(&vc4->hangcheck.timer, vc4_hangcheck_elapsed, (unsigned long)dev); INIT_WORK(&vc4->job_done_work, vc4_job_done_work); mutex_init(&vc4->power_lock); } void vc4_gem_destroy(struct drm_device *dev) { struct vc4_dev *vc4 = to_vc4_dev(dev); /* Waiting for exec to finish would need to be done before * unregistering V3D. */ WARN_ON(vc4->emit_seqno != vc4->finished_seqno); /* V3D should already have disabled its interrupt and cleared * the overflow allocation registers. Now free the object. */ if (vc4->overflow_mem) { drm_gem_object_unreference_unlocked(&vc4->overflow_mem->base.base); vc4->overflow_mem = NULL; } if (vc4->hang_state) vc4_free_hang_state(dev, vc4->hang_state); vc4_bo_cache_destroy(dev); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3121_0
crossvul-cpp_data_bad_1943_2
/* zmalloc - total amount of allocated memory aware version of malloc() * * Copyright (c) 2009-2010, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * 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 Redis 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. */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> /* This function provide us access to the original libc free(). This is useful * for instance to free results obtained by backtrace_symbols(). We need * to define this function before including zmalloc.h that may shadow the * free implementation if we use jemalloc or another non standard allocator. */ void zlibc_free(void *ptr) { free(ptr); } #include <string.h> #include <pthread.h> #include "config.h" #include "zmalloc.h" #include "atomicvar.h" #ifdef HAVE_MALLOC_SIZE #define PREFIX_SIZE (0) #else #if defined(__sun) || defined(__sparc) || defined(__sparc__) #define PREFIX_SIZE (sizeof(long long)) #else #define PREFIX_SIZE (sizeof(size_t)) #endif #endif /* Explicitly override malloc/free etc when using tcmalloc. */ #if defined(USE_TCMALLOC) #define malloc(size) tc_malloc(size) #define calloc(count,size) tc_calloc(count,size) #define realloc(ptr,size) tc_realloc(ptr,size) #define free(ptr) tc_free(ptr) #elif defined(USE_JEMALLOC) #define malloc(size) je_malloc(size) #define calloc(count,size) je_calloc(count,size) #define realloc(ptr,size) je_realloc(ptr,size) #define free(ptr) je_free(ptr) #define mallocx(size,flags) je_mallocx(size,flags) #define dallocx(ptr,flags) je_dallocx(ptr,flags) #endif #define update_zmalloc_stat_alloc(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ atomicIncr(used_memory,__n); \ } while(0) #define update_zmalloc_stat_free(__n) do { \ size_t _n = (__n); \ if (_n&(sizeof(long)-1)) _n += sizeof(long)-(_n&(sizeof(long)-1)); \ atomicDecr(used_memory,__n); \ } while(0) static size_t used_memory = 0; pthread_mutex_t used_memory_mutex = PTHREAD_MUTEX_INITIALIZER; static void zmalloc_default_oom(size_t size) { fprintf(stderr, "zmalloc: Out of memory trying to allocate %zu bytes\n", size); fflush(stderr); abort(); } static void (*zmalloc_oom_handler)(size_t) = zmalloc_default_oom; void *zmalloc(size_t size) { void *ptr = malloc(size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } /* Allocation and free functions that bypass the thread cache * and go straight to the allocator arena bins. * Currently implemented only for jemalloc. Used for online defragmentation. */ #ifdef HAVE_DEFRAG void *zmalloc_no_tcache(size_t size) { void *ptr = mallocx(size+PREFIX_SIZE, MALLOCX_TCACHE_NONE); if (!ptr) zmalloc_oom_handler(size); update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; } void zfree_no_tcache(void *ptr) { if (ptr == NULL) return; update_zmalloc_stat_free(zmalloc_size(ptr)); dallocx(ptr, MALLOCX_TCACHE_NONE); } #endif void *zcalloc(size_t size) { void *ptr = calloc(1, size+PREFIX_SIZE); if (!ptr) zmalloc_oom_handler(size); #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_alloc(zmalloc_size(ptr)); return ptr; #else *((size_t*)ptr) = size; update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)ptr+PREFIX_SIZE; #endif } void *zrealloc(void *ptr, size_t size) { #ifndef HAVE_MALLOC_SIZE void *realptr; #endif size_t oldsize; void *newptr; if (size == 0 && ptr != NULL) { zfree(ptr); return NULL; } if (ptr == NULL) return zmalloc(size); #ifdef HAVE_MALLOC_SIZE oldsize = zmalloc_size(ptr); newptr = realloc(ptr,size); if (!newptr) zmalloc_oom_handler(size); update_zmalloc_stat_free(oldsize); update_zmalloc_stat_alloc(zmalloc_size(newptr)); return newptr; #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); newptr = realloc(realptr,size+PREFIX_SIZE); if (!newptr) zmalloc_oom_handler(size); *((size_t*)newptr) = size; update_zmalloc_stat_free(oldsize+PREFIX_SIZE); update_zmalloc_stat_alloc(size+PREFIX_SIZE); return (char*)newptr+PREFIX_SIZE; #endif } /* Provide zmalloc_size() for systems where this function is not provided by * malloc itself, given that in that case we store a header with this * information as the first bytes of every allocation. */ #ifndef HAVE_MALLOC_SIZE size_t zmalloc_size(void *ptr) { void *realptr = (char*)ptr-PREFIX_SIZE; size_t size = *((size_t*)realptr); return size+PREFIX_SIZE; } size_t zmalloc_usable(void *ptr) { return zmalloc_size(ptr)-PREFIX_SIZE; } #endif void zfree(void *ptr) { #ifndef HAVE_MALLOC_SIZE void *realptr; size_t oldsize; #endif if (ptr == NULL) return; #ifdef HAVE_MALLOC_SIZE update_zmalloc_stat_free(zmalloc_size(ptr)); free(ptr); #else realptr = (char*)ptr-PREFIX_SIZE; oldsize = *((size_t*)realptr); update_zmalloc_stat_free(oldsize+PREFIX_SIZE); free(realptr); #endif } char *zstrdup(const char *s) { size_t l = strlen(s)+1; char *p = zmalloc(l); memcpy(p,s,l); return p; } size_t zmalloc_used_memory(void) { size_t um; atomicGet(used_memory,um); return um; } void zmalloc_set_oom_handler(void (*oom_handler)(size_t)) { zmalloc_oom_handler = oom_handler; } /* Get the RSS information in an OS-specific way. * * WARNING: the function zmalloc_get_rss() is not designed to be fast * and may not be called in the busy loops where Redis tries to release * memory expiring or swapping out objects. * * For this kind of "fast RSS reporting" usages use instead the * function RedisEstimateRSS() that is a much faster (and less precise) * version of the function. */ #if defined(HAVE_PROC_STAT) #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> size_t zmalloc_get_rss(void) { int page = sysconf(_SC_PAGESIZE); size_t rss; char buf[4096]; char filename[256]; int fd, count; char *p, *x; snprintf(filename,256,"/proc/%d/stat",getpid()); if ((fd = open(filename,O_RDONLY)) == -1) return 0; if (read(fd,buf,4096) <= 0) { close(fd); return 0; } close(fd); p = buf; count = 23; /* RSS is the 24th field in /proc/<pid>/stat */ while(p && count--) { p = strchr(p,' '); if (p) p++; } if (!p) return 0; x = strchr(p,' '); if (!x) return 0; *x = '\0'; rss = strtoll(p,NULL,10); rss *= page; return rss; } #elif defined(HAVE_TASKINFO) #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/sysctl.h> #include <mach/task.h> #include <mach/mach_init.h> size_t zmalloc_get_rss(void) { task_t task = MACH_PORT_NULL; struct task_basic_info t_info; mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT; if (task_for_pid(current_task(), getpid(), &task) != KERN_SUCCESS) return 0; task_info(task, TASK_BASIC_INFO, (task_info_t)&t_info, &t_info_count); return t_info.resident_size; } #elif defined(__FreeBSD__) #include <sys/types.h> #include <sys/sysctl.h> #include <sys/user.h> #include <unistd.h> size_t zmalloc_get_rss(void) { struct kinfo_proc info; size_t infolen = sizeof(info); int mib[4]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); if (sysctl(mib, 4, &info, &infolen, NULL, 0) == 0) return (size_t)info.ki_rssize; return 0L; } #elif defined(__NetBSD__) #include <sys/types.h> #include <sys/sysctl.h> #include <unistd.h> size_t zmalloc_get_rss(void) { struct kinfo_proc2 info; size_t infolen = sizeof(info); int mib[6]; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); mib[4] = sizeof(info); mib[5] = 1; if (sysctl(mib, 4, &info, &infolen, NULL, 0) == 0) return (size_t)info.p_vm_rssize; return 0L; } #else size_t zmalloc_get_rss(void) { /* If we can't get the RSS in an OS-specific way for this system just * return the memory usage we estimated in zmalloc().. * * Fragmentation will appear to be always 1 (no fragmentation) * of course... */ return zmalloc_used_memory(); } #endif #if defined(USE_JEMALLOC) int zmalloc_get_allocator_info(size_t *allocated, size_t *active, size_t *resident) { uint64_t epoch = 1; size_t sz; *allocated = *resident = *active = 0; /* Update the statistics cached by mallctl. */ sz = sizeof(epoch); je_mallctl("epoch", &epoch, &sz, &epoch, sz); sz = sizeof(size_t); /* Unlike RSS, this does not include RSS from shared libraries and other non * heap mappings. */ je_mallctl("stats.resident", resident, &sz, NULL, 0); /* Unlike resident, this doesn't not include the pages jemalloc reserves * for re-use (purge will clean that). */ je_mallctl("stats.active", active, &sz, NULL, 0); /* Unlike zmalloc_used_memory, this matches the stats.resident by taking * into account all allocations done by this process (not only zmalloc). */ je_mallctl("stats.allocated", allocated, &sz, NULL, 0); return 1; } void set_jemalloc_bg_thread(int enable) { /* let jemalloc do purging asynchronously, required when there's no traffic * after flushdb */ char val = !!enable; je_mallctl("background_thread", NULL, 0, &val, 1); } int jemalloc_purge() { /* return all unused (reserved) pages to the OS */ char tmp[32]; unsigned narenas = 0; size_t sz = sizeof(unsigned); if (!je_mallctl("arenas.narenas", &narenas, &sz, NULL, 0)) { sprintf(tmp, "arena.%d.purge", narenas); if (!je_mallctl(tmp, NULL, 0, NULL, 0)) return 0; } return -1; } #else int zmalloc_get_allocator_info(size_t *allocated, size_t *active, size_t *resident) { *allocated = *resident = *active = 0; return 1; } void set_jemalloc_bg_thread(int enable) { ((void)(enable)); } int jemalloc_purge() { return 0; } #endif #if defined(__APPLE__) /* For proc_pidinfo() used later in zmalloc_get_smap_bytes_by_field(). * Note that this file cannot be included in zmalloc.h because it includes * a Darwin queue.h file where there is a "LIST_HEAD" macro (!) defined * conficting with Redis user code. */ #include <libproc.h> #endif /* Get the sum of the specified field (converted form kb to bytes) in * /proc/self/smaps. The field must be specified with trailing ":" as it * apperas in the smaps output. * * If a pid is specified, the information is extracted for such a pid, * otherwise if pid is -1 the information is reported is about the * current process. * * Example: zmalloc_get_smap_bytes_by_field("Rss:",-1); */ #if defined(HAVE_PROC_SMAPS) size_t zmalloc_get_smap_bytes_by_field(char *field, long pid) { char line[1024]; size_t bytes = 0; int flen = strlen(field); FILE *fp; if (pid == -1) { fp = fopen("/proc/self/smaps","r"); } else { char filename[128]; snprintf(filename,sizeof(filename),"/proc/%ld/smaps",pid); fp = fopen(filename,"r"); } if (!fp) return 0; while(fgets(line,sizeof(line),fp) != NULL) { if (strncmp(line,field,flen) == 0) { char *p = strchr(line,'k'); if (p) { *p = '\0'; bytes += strtol(line+flen,NULL,10) * 1024; } } } fclose(fp); return bytes; } #else /* Get sum of the specified field from libproc api call. * As there are per page value basis we need to convert * them accordingly. * * Note that AnonHugePages is a no-op as THP feature * is not supported in this platform */ size_t zmalloc_get_smap_bytes_by_field(char *field, long pid) { #if defined(__APPLE__) struct proc_regioninfo pri; if (proc_pidinfo(pid, PROC_PIDREGIONINFO, 0, &pri, PROC_PIDREGIONINFO_SIZE) == PROC_PIDREGIONINFO_SIZE) { if (!strcmp(field, "Private_Dirty:")) { return (size_t)pri.pri_pages_dirtied * 4096; } else if (!strcmp(field, "Rss:")) { return (size_t)pri.pri_pages_resident * 4096; } else if (!strcmp(field, "AnonHugePages:")) { return 0; } } return 0; #endif ((void) field); ((void) pid); return 0; } #endif size_t zmalloc_get_private_dirty(long pid) { return zmalloc_get_smap_bytes_by_field("Private_Dirty:",pid); } /* Returns the size of physical memory (RAM) in bytes. * It looks ugly, but this is the cleanest way to achieve cross platform results. * Cleaned up from: * * http://nadeausoftware.com/articles/2012/09/c_c_tip_how_get_physical_memory_size_system * * Note that this function: * 1) Was released under the following CC attribution license: * http://creativecommons.org/licenses/by/3.0/deed.en_US. * 2) Was originally implemented by David Robert Nadeau. * 3) Was modified for Redis by Matt Stancliff. * 4) This note exists in order to comply with the original license. */ size_t zmalloc_get_memory_size(void) { #if defined(__unix__) || defined(__unix) || defined(unix) || \ (defined(__APPLE__) && defined(__MACH__)) #if defined(CTL_HW) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM64)) int mib[2]; mib[0] = CTL_HW; #if defined(HW_MEMSIZE) mib[1] = HW_MEMSIZE; /* OSX. --------------------- */ #elif defined(HW_PHYSMEM64) mib[1] = HW_PHYSMEM64; /* NetBSD, OpenBSD. --------- */ #endif int64_t size = 0; /* 64-bit */ size_t len = sizeof(size); if (sysctl( mib, 2, &size, &len, NULL, 0) == 0) return (size_t)size; return 0L; /* Failed? */ #elif defined(_SC_PHYS_PAGES) && defined(_SC_PAGESIZE) /* FreeBSD, Linux, OpenBSD, and Solaris. -------------------- */ return (size_t)sysconf(_SC_PHYS_PAGES) * (size_t)sysconf(_SC_PAGESIZE); #elif defined(CTL_HW) && (defined(HW_PHYSMEM) || defined(HW_REALMEM)) /* DragonFly BSD, FreeBSD, NetBSD, OpenBSD, and OSX. -------- */ int mib[2]; mib[0] = CTL_HW; #if defined(HW_REALMEM) mib[1] = HW_REALMEM; /* FreeBSD. ----------------- */ #elif defined(HW_PHYSMEM) mib[1] = HW_PHYSMEM; /* Others. ------------------ */ #endif unsigned int size = 0; /* 32-bit */ size_t len = sizeof(size); if (sysctl(mib, 2, &size, &len, NULL, 0) == 0) return (size_t)size; return 0L; /* Failed? */ #else return 0L; /* Unknown method to get the data. */ #endif #else return 0L; /* Unknown OS. */ #endif } #ifdef REDIS_TEST #define UNUSED(x) ((void)(x)) int zmalloc_test(int argc, char **argv) { void *ptr; UNUSED(argc); UNUSED(argv); printf("Initial used memory: %zu\n", zmalloc_used_memory()); ptr = zmalloc(123); printf("Allocated 123 bytes; used: %zu\n", zmalloc_used_memory()); ptr = zrealloc(ptr, 456); printf("Reallocated to 456 bytes; used: %zu\n", zmalloc_used_memory()); zfree(ptr); printf("Freed pointer; used: %zu\n", zmalloc_used_memory()); return 0; } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1943_2
crossvul-cpp_data_good_1185_0
/* * Copyright (c) 1991-1997 Sam Leffler * Copyright (c) 1991-1997 Silicon Graphics, Inc. * * Permission to use, copy, modify, distribute, and sell this software and * its documentation for any purpose is hereby granted without fee, provided * that (i) the above copyright notices and this permission notice appear in * all copies of the software and related documentation, and (ii) the names of * Sam Leffler and Silicon Graphics may not be used in any advertising or * publicity relating to the software without the specific, prior written * permission of Sam Leffler and Silicon Graphics. * * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. * * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THIS SOFTWARE. */ /* * TIFF Library * * Read and return a packed RGBA image. */ #include "tiffiop.h" #include <stdio.h> static int gtTileContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtTileSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripContig(TIFFRGBAImage*, uint32*, uint32, uint32); static int gtStripSeparate(TIFFRGBAImage*, uint32*, uint32, uint32); static int PickContigCase(TIFFRGBAImage*); static int PickSeparateCase(TIFFRGBAImage*); static int BuildMapUaToAa(TIFFRGBAImage* img); static int BuildMapBitdepth16To8(TIFFRGBAImage* img); static const char photoTag[] = "PhotometricInterpretation"; /* * Helper constants used in Orientation tag handling */ #define FLIP_VERTICALLY 0x01 #define FLIP_HORIZONTALLY 0x02 /* * Color conversion constants. We will define display types here. */ static const TIFFDisplay display_sRGB = { { /* XYZ -> luminance matrix */ { 3.2410F, -1.5374F, -0.4986F }, { -0.9692F, 1.8760F, 0.0416F }, { 0.0556F, -0.2040F, 1.0570F } }, 100.0F, 100.0F, 100.0F, /* Light o/p for reference white */ 255, 255, 255, /* Pixel values for ref. white */ 1.0F, 1.0F, 1.0F, /* Residual light o/p for black pixel */ 2.4F, 2.4F, 2.4F, /* Gamma values for the three guns */ }; /* * Check the image to see if TIFFReadRGBAImage can deal with it. * 1/0 is returned according to whether or not the image can * be handled. If 0 is returned, emsg contains the reason * why it is being rejected. */ int TIFFRGBAImageOK(TIFF* tif, char emsg[1024]) { TIFFDirectory* td = &tif->tif_dir; uint16 photometric; int colorchannels; if (!tif->tif_decodestatus) { sprintf(emsg, "Sorry, requested compression method is not configured"); return (0); } switch (td->td_bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", td->td_bitspersample); return (0); } if (td->td_sampleformat == SAMPLEFORMAT_IEEEFP) { sprintf(emsg, "Sorry, can not handle images with IEEE floating-point samples"); return (0); } colorchannels = td->td_samplesperpixel - td->td_extrasamples; if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric)) { switch (colorchannels) { case 1: photometric = PHOTOMETRIC_MINISBLACK; break; case 3: photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); return (0); } } switch (photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: if (td->td_planarconfig == PLANARCONFIG_CONTIG && td->td_samplesperpixel != 1 && td->td_bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, photometric, "Samples/pixel", td->td_samplesperpixel, td->td_bitspersample); return (0); } /* * We should likely validate that any extra samples are either * to be ignored, or are alpha, and if alpha we should try to use * them. But for now we won't bother with this. */ break; case PHOTOMETRIC_YCBCR: /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); return (0); } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); return 0; } if (td->td_samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", td->td_samplesperpixel); return 0; } break; } case PHOTOMETRIC_LOGL: if (td->td_compression != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); return (0); } break; case PHOTOMETRIC_LOGLUV: if (td->td_compression != COMPRESSION_SGILOG && td->td_compression != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); return (0); } if (td->td_planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", td->td_planarconfig); return (0); } if ( td->td_samplesperpixel != 3 || colorchannels != 3 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels); return 0; } break; case PHOTOMETRIC_CIELAB: if ( td->td_samplesperpixel != 3 || colorchannels != 3 || td->td_bitspersample != 8 ) { sprintf(emsg, "Sorry, can not handle image with %s=%d, %s=%d and %s=%d", "Samples/pixel", td->td_samplesperpixel, "colorchannels", colorchannels, "Bits/sample", td->td_bitspersample); return 0; } break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, photometric); return (0); } return (1); } void TIFFRGBAImageEnd(TIFFRGBAImage* img) { if (img->Map) { _TIFFfree(img->Map); img->Map = NULL; } if (img->BWmap) { _TIFFfree(img->BWmap); img->BWmap = NULL; } if (img->PALmap) { _TIFFfree(img->PALmap); img->PALmap = NULL; } if (img->ycbcr) { _TIFFfree(img->ycbcr); img->ycbcr = NULL; } if (img->cielab) { _TIFFfree(img->cielab); img->cielab = NULL; } if (img->UaToAa) { _TIFFfree(img->UaToAa); img->UaToAa = NULL; } if (img->Bitdepth16To8) { _TIFFfree(img->Bitdepth16To8); img->Bitdepth16To8 = NULL; } if( img->redcmap ) { _TIFFfree( img->redcmap ); _TIFFfree( img->greencmap ); _TIFFfree( img->bluecmap ); img->redcmap = img->greencmap = img->bluecmap = NULL; } } static int isCCITTCompression(TIFF* tif) { uint16 compress; TIFFGetField(tif, TIFFTAG_COMPRESSION, &compress); return (compress == COMPRESSION_CCITTFAX3 || compress == COMPRESSION_CCITTFAX4 || compress == COMPRESSION_CCITTRLE || compress == COMPRESSION_CCITTRLEW); } int TIFFRGBAImageBegin(TIFFRGBAImage* img, TIFF* tif, int stop, char emsg[1024]) { uint16* sampleinfo; uint16 extrasamples; uint16 planarconfig; uint16 compress; int colorchannels; uint16 *red_orig, *green_orig, *blue_orig; int n_color; if( !TIFFRGBAImageOK(tif, emsg) ) return 0; /* Initialize to normal values */ img->row_offset = 0; img->col_offset = 0; img->redcmap = NULL; img->greencmap = NULL; img->bluecmap = NULL; img->Map = NULL; img->BWmap = NULL; img->PALmap = NULL; img->ycbcr = NULL; img->cielab = NULL; img->UaToAa = NULL; img->Bitdepth16To8 = NULL; img->req_orientation = ORIENTATION_BOTLEFT; /* It is the default */ img->tif = tif; img->stoponerr = stop; TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &img->bitspersample); switch (img->bitspersample) { case 1: case 2: case 4: case 8: case 16: break; default: sprintf(emsg, "Sorry, can not handle images with %d-bit samples", img->bitspersample); goto fail_return; } img->alpha = 0; TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &img->samplesperpixel); TIFFGetFieldDefaulted(tif, TIFFTAG_EXTRASAMPLES, &extrasamples, &sampleinfo); if (extrasamples >= 1) { switch (sampleinfo[0]) { case EXTRASAMPLE_UNSPECIFIED: /* Workaround for some images without */ if (img->samplesperpixel > 3) /* correct info about alpha channel */ img->alpha = EXTRASAMPLE_ASSOCALPHA; break; case EXTRASAMPLE_ASSOCALPHA: /* data is pre-multiplied */ case EXTRASAMPLE_UNASSALPHA: /* data is not pre-multiplied */ img->alpha = sampleinfo[0]; break; } } #ifdef DEFAULT_EXTRASAMPLE_AS_ALPHA if( !TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) img->photometric = PHOTOMETRIC_MINISWHITE; if( extrasamples == 0 && img->samplesperpixel == 4 && img->photometric == PHOTOMETRIC_RGB ) { img->alpha = EXTRASAMPLE_ASSOCALPHA; extrasamples = 1; } #endif colorchannels = img->samplesperpixel - extrasamples; TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &compress); TIFFGetFieldDefaulted(tif, TIFFTAG_PLANARCONFIG, &planarconfig); if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &img->photometric)) { switch (colorchannels) { case 1: if (isCCITTCompression(tif)) img->photometric = PHOTOMETRIC_MINISWHITE; else img->photometric = PHOTOMETRIC_MINISBLACK; break; case 3: img->photometric = PHOTOMETRIC_RGB; break; default: sprintf(emsg, "Missing needed %s tag", photoTag); goto fail_return; } } switch (img->photometric) { case PHOTOMETRIC_PALETTE: if (!TIFFGetField(tif, TIFFTAG_COLORMAP, &red_orig, &green_orig, &blue_orig)) { sprintf(emsg, "Missing required \"Colormap\" tag"); goto fail_return; } /* copy the colormaps so we can modify them */ n_color = (1U << img->bitspersample); img->redcmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->greencmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); img->bluecmap = (uint16 *) _TIFFmalloc(sizeof(uint16)*n_color); if( !img->redcmap || !img->greencmap || !img->bluecmap ) { sprintf(emsg, "Out of memory for colormap copy"); goto fail_return; } _TIFFmemcpy( img->redcmap, red_orig, n_color * 2 ); _TIFFmemcpy( img->greencmap, green_orig, n_color * 2 ); _TIFFmemcpy( img->bluecmap, blue_orig, n_color * 2 ); /* fall through... */ case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (planarconfig == PLANARCONFIG_CONTIG && img->samplesperpixel != 1 && img->bitspersample < 8 ) { sprintf(emsg, "Sorry, can not handle contiguous data with %s=%d, " "and %s=%d and Bits/Sample=%d", photoTag, img->photometric, "Samples/pixel", img->samplesperpixel, img->bitspersample); goto fail_return; } break; case PHOTOMETRIC_YCBCR: /* It would probably be nice to have a reality check here. */ if (planarconfig == PLANARCONFIG_CONTIG) /* can rely on libjpeg to convert to RGB */ /* XXX should restore current state on exit */ switch (compress) { case COMPRESSION_JPEG: /* * TODO: when complete tests verify complete desubsampling * and YCbCr handling, remove use of TIFFTAG_JPEGCOLORMODE in * favor of tif_getimage.c native handling */ TIFFSetField(tif, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB); img->photometric = PHOTOMETRIC_RGB; break; default: /* do nothing */; break; } /* * TODO: if at all meaningful and useful, make more complete * support check here, or better still, refactor to let supporting * code decide whether there is support and what meaningful * error to return */ break; case PHOTOMETRIC_RGB: if (colorchannels < 3) { sprintf(emsg, "Sorry, can not handle RGB image with %s=%d", "Color channels", colorchannels); goto fail_return; } break; case PHOTOMETRIC_SEPARATED: { uint16 inkset; TIFFGetFieldDefaulted(tif, TIFFTAG_INKSET, &inkset); if (inkset != INKSET_CMYK) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "InkSet", inkset); goto fail_return; } if (img->samplesperpixel < 4) { sprintf(emsg, "Sorry, can not handle separated image with %s=%d", "Samples/pixel", img->samplesperpixel); goto fail_return; } } break; case PHOTOMETRIC_LOGL: if (compress != COMPRESSION_SGILOG) { sprintf(emsg, "Sorry, LogL data must have %s=%d", "Compression", COMPRESSION_SGILOG); goto fail_return; } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_MINISBLACK; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_LOGLUV: if (compress != COMPRESSION_SGILOG && compress != COMPRESSION_SGILOG24) { sprintf(emsg, "Sorry, LogLuv data must have %s=%d or %d", "Compression", COMPRESSION_SGILOG, COMPRESSION_SGILOG24); goto fail_return; } if (planarconfig != PLANARCONFIG_CONTIG) { sprintf(emsg, "Sorry, can not handle LogLuv images with %s=%d", "Planarconfiguration", planarconfig); return (0); } TIFFSetField(tif, TIFFTAG_SGILOGDATAFMT, SGILOGDATAFMT_8BIT); img->photometric = PHOTOMETRIC_RGB; /* little white lie */ img->bitspersample = 8; break; case PHOTOMETRIC_CIELAB: break; default: sprintf(emsg, "Sorry, can not handle image with %s=%d", photoTag, img->photometric); goto fail_return; } TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &img->width); TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &img->height); TIFFGetFieldDefaulted(tif, TIFFTAG_ORIENTATION, &img->orientation); img->isContig = !(planarconfig == PLANARCONFIG_SEPARATE && img->samplesperpixel > 1); if (img->isContig) { if (!PickContigCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } else { if (!PickSeparateCase(img)) { sprintf(emsg, "Sorry, can not handle image"); goto fail_return; } } return 1; fail_return: TIFFRGBAImageEnd( img ); return 0; } int TIFFRGBAImageGet(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { if (img->get == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"get\" routine setup"); return (0); } if (img->put.any == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No \"put\" routine setupl; probably can not handle image format"); return (0); } return (*img->get)(img, raster, w, h); } /* * Read the specified image into an ABGR-format rastertaking in account * specified orientation. */ int TIFFReadRGBAImageOriented(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int orientation, int stop) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop, emsg)) { img.req_orientation = (uint16)orientation; /* XXX verify rwidth and rheight against width and height */ ok = TIFFRGBAImageGet(&img, raster+(rheight-img.height)*rwidth, rwidth, img.height); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read the specified image into an ABGR-format raster. Use bottom left * origin for raster by default. */ int TIFFReadRGBAImage(TIFF* tif, uint32 rwidth, uint32 rheight, uint32* raster, int stop) { return TIFFReadRGBAImageOriented(tif, rwidth, rheight, raster, ORIENTATION_BOTLEFT, stop); } static int setorientation(TIFFRGBAImage* img) { switch (img->orientation) { case ORIENTATION_TOPLEFT: case ORIENTATION_LEFTTOP: if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_VERTICALLY; else return 0; case ORIENTATION_TOPRIGHT: case ORIENTATION_RIGHTTOP: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else return 0; case ORIENTATION_BOTRIGHT: case ORIENTATION_RIGHTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTLEFT || img->req_orientation == ORIENTATION_LEFTBOT) return FLIP_HORIZONTALLY; else return 0; case ORIENTATION_BOTLEFT: case ORIENTATION_LEFTBOT: if (img->req_orientation == ORIENTATION_TOPLEFT || img->req_orientation == ORIENTATION_LEFTTOP) return FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_TOPRIGHT || img->req_orientation == ORIENTATION_RIGHTTOP) return FLIP_HORIZONTALLY | FLIP_VERTICALLY; else if (img->req_orientation == ORIENTATION_BOTRIGHT || img->req_orientation == ORIENTATION_RIGHTBOT) return FLIP_HORIZONTALLY; else return 0; default: /* NOTREACHED */ return 0; } } /* * Get an tile-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtTileContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; int32 fromskew, toskew; uint32 nrow; int ret = 1, flip; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tmsize_t bufsize; bufsize = TIFFTileSize(tif); if (bufsize == 0) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", "No space for tile buffer"); return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if (_TIFFReadTileAndAllocBuffer(tif, (void**) &buf, bufsize, col, row+img->row_offset, 0, 0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } _TIFFfree(buf); if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } return (ret); } /* * Get an tile-organized image that has * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtTileSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; uint32 col, row, y, rowstoread; tmsize_t pos; uint32 tw, th; unsigned char* buf = NULL; unsigned char* p0 = NULL; unsigned char* p1 = NULL; unsigned char* p2 = NULL; unsigned char* pa = NULL; tmsize_t tilesize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; uint32 nrow; int ret = 1, flip; uint16 colorchannels; uint32 this_tw, tocol; int32 this_toskew, leftmost_toskew; int32 leftmost_fromskew; uint32 leftmost_tw; tilesize = TIFFTileSize(tif); bufsize = _TIFFMultiplySSize(tif, alpha?4:3,tilesize, "gtTileSeparate"); if (bufsize == 0) { return (0); } TIFFGetField(tif, TIFFTAG_TILEWIDTH, &tw); TIFFGetField(tif, TIFFTAG_TILELENGTH, &th); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(tw + w); } else { y = 0; toskew = -(int32)(tw - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } /* * Leftmost tile is clipped on left side if col_offset > 0. */ leftmost_fromskew = img->col_offset % tw; leftmost_tw = tw - leftmost_fromskew; leftmost_toskew = toskew + leftmost_fromskew; for (row = 0; ret != 0 && row < h; row += nrow) { rowstoread = th - (row + img->row_offset) % th; nrow = (row + rowstoread > h ? h - row : rowstoread); fromskew = leftmost_fromskew; this_tw = leftmost_tw; this_toskew = leftmost_toskew; tocol = 0; col = img->col_offset; while (tocol < w) { if( buf == NULL ) { if (_TIFFReadTileAndAllocBuffer( tif, (void**) &buf, bufsize, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*tilesize):NULL); } else { p1 = p0 + tilesize; p2 = p1 + tilesize; pa = (alpha?(p2+tilesize):NULL); } } else if (TIFFReadTile(tif, p0, col, row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p1, col, row+img->row_offset,0,1) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadTile(tif, p2, col, row+img->row_offset,0,2) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha && TIFFReadTile(tif,pa,col, row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \ ((tmsize_t) fromskew * img->samplesperpixel); if (tocol + this_tw > w) { /* * Rightmost tile is clipped on right side. */ fromskew = tw - (w - tocol); this_tw = tw - fromskew; this_toskew = toskew + fromskew; } (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \ p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); tocol += this_tw; col += this_tw; /* * After the leftmost tile, tiles are no longer clipped on left side. */ fromskew = 0; this_tw = tw; this_toskew = toskew; } y += ((flip & FLIP_VERTICALLY) ?-(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image that has * PlanarConfiguration contiguous if SamplesPerPixel > 1 * or * SamplesPerPixel == 1 */ static int gtStripContig(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileContigRoutine put = img->put.contig; uint32 row, y, nrow, nrowsub, rowstoread; tmsize_t pos; unsigned char* buf = NULL; uint32 rowsperstrip; uint16 subsamplinghor,subsamplingver; uint32 imagewidth = img->width; tmsize_t scanline; int32 fromskew, toskew; int ret = 1, flip; tmsize_t maxstripsize; TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver); if( subsamplingver == 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling"); return (0); } maxstripsize = TIFFStripSize(tif); flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { uint32 temp; rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); nrowsub = nrow; if ((nrowsub%subsamplingver)!=0) nrowsub+=subsamplingver-nrowsub%subsamplingver; temp = (row + img->row_offset)%rowsperstrip + nrowsub; if( scanline > 0 && temp > (size_t)(TIFF_TMSIZE_T_MAX / scanline) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in gtStripContig"); return 0; } if (_TIFFReadEncodedStripAndAllocBuffer(tif, TIFFComputeStrip(tif,row+img->row_offset, 0), (void**)(&buf), maxstripsize, temp * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * Get a strip-organized image with * SamplesPerPixel > 1 * PlanarConfiguration separated * We assume that all such images are RGB. */ static int gtStripSeparate(TIFFRGBAImage* img, uint32* raster, uint32 w, uint32 h) { TIFF* tif = img->tif; tileSeparateRoutine put = img->put.separate; unsigned char *buf = NULL; unsigned char *p0 = NULL, *p1 = NULL, *p2 = NULL, *pa = NULL; uint32 row, y, nrow, rowstoread; tmsize_t pos; tmsize_t scanline; uint32 rowsperstrip, offset_row; uint32 imagewidth = img->width; tmsize_t stripsize; tmsize_t bufsize; int32 fromskew, toskew; int alpha = img->alpha; int ret = 1, flip; uint16 colorchannels; stripsize = TIFFStripSize(tif); bufsize = _TIFFMultiplySSize(tif,alpha?4:3,stripsize, "gtStripSeparate"); if (bufsize == 0) { return (0); } flip = setorientation(img); if (flip & FLIP_VERTICALLY) { y = h - 1; toskew = -(int32)(w + w); } else { y = 0; toskew = -(int32)(w - w); } switch( img->photometric ) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_PALETTE: colorchannels = 1; break; default: colorchannels = 3; break; } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); scanline = TIFFScanlineSize(tif); fromskew = (w < imagewidth ? imagewidth - w : 0); for (row = 0; row < h; row += nrow) { uint32 temp; rowstoread = rowsperstrip - (row + img->row_offset) % rowsperstrip; nrow = (row + rowstoread > h ? h - row : rowstoread); offset_row = row + img->row_offset; temp = (row + img->row_offset)%rowsperstrip + nrow; if( scanline > 0 && temp > (size_t)(TIFF_TMSIZE_T_MAX / scanline) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Integer overflow in gtStripSeparate"); return 0; } if( buf == NULL ) { if (_TIFFReadEncodedStripAndAllocBuffer( tif, TIFFComputeStrip(tif, offset_row, 0), (void**) &buf, bufsize, temp * scanline)==(tmsize_t)(-1) && (buf == NULL || img->stoponerr)) { ret = 0; break; } p0 = buf; if( colorchannels == 1 ) { p2 = p1 = p0; pa = (alpha?(p0+3*stripsize):NULL); } else { p1 = p0 + stripsize; p2 = p1 + stripsize; pa = (alpha?(p2+stripsize):NULL); } } else if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 0), p0, temp * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 1), p1, temp * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (colorchannels > 1 && TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, 2), p2, temp * scanline) == (tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } if (alpha) { if (TIFFReadEncodedStrip(tif, TIFFComputeStrip(tif, offset_row, colorchannels), pa, temp * scanline)==(tmsize_t)(-1) && img->stoponerr) { ret = 0; break; } } pos = ((row + img->row_offset) % rowsperstrip) * scanline + \ ((tmsize_t) img->col_offset * img->samplesperpixel); (*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL)); y += ((flip & FLIP_VERTICALLY) ? -(int32) nrow : (int32) nrow); } if (flip & FLIP_HORIZONTALLY) { uint32 line; for (line = 0; line < h; line++) { uint32 *left = raster + (line * w); uint32 *right = left + w - 1; while ( left < right ) { uint32 temp = *left; *left = *right; *right = temp; left++; right--; } } } _TIFFfree(buf); return (ret); } /* * The following routines move decoded data returned * from the TIFF library into rasters filled with packed * ABGR pixels (i.e. suitable for passing to lrecwrite.) * * The routines have been created according to the most * important cases and optimized. PickContigCase and * PickSeparateCase analyze the parameters and select * the appropriate "get" and "put" routine to use. */ #define REPEAT8(op) REPEAT4(op); REPEAT4(op) #define REPEAT4(op) REPEAT2(op); REPEAT2(op) #define REPEAT2(op) op; op #define CASE8(x,op) \ switch (x) { \ case 7: op; /*-fallthrough*/ \ case 6: op; /*-fallthrough*/ \ case 5: op; /*-fallthrough*/ \ case 4: op; /*-fallthrough*/ \ case 3: op; /*-fallthrough*/ \ case 2: op; /*-fallthrough*/ \ case 1: op; \ } #define CASE4(x,op) switch (x) { case 3: op; /*-fallthrough*/ case 2: op; /*-fallthrough*/ case 1: op; } #define NOP #define UNROLL8(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 8; _x -= 8) { \ op1; \ REPEAT8(op2); \ } \ if (_x > 0) { \ op1; \ CASE8(_x,op2); \ } \ } #define UNROLL4(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 4; _x -= 4) { \ op1; \ REPEAT4(op2); \ } \ if (_x > 0) { \ op1; \ CASE4(_x,op2); \ } \ } #define UNROLL2(w, op1, op2) { \ uint32 _x; \ for (_x = w; _x >= 2; _x -= 2) { \ op1; \ REPEAT2(op2); \ } \ if (_x) { \ op1; \ op2; \ } \ } #define SKEW(r,g,b,skew) { r += skew; g += skew; b += skew; } #define SKEW4(r,g,b,a,skew) { r += skew; g += skew; b += skew; a+= skew; } #define A1 (((uint32)0xffL)<<24) #define PACK(r,g,b) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|A1) #define PACK4(r,g,b,a) \ ((uint32)(r)|((uint32)(g)<<8)|((uint32)(b)<<16)|((uint32)(a)<<24)) #define W2B(v) (((v)>>8)&0xff) /* TODO: PACKW should have be made redundant in favor of Bitdepth16To8 LUT */ #define PACKW(r,g,b) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|A1) #define PACKW4(r,g,b,a) \ ((uint32)W2B(r)|((uint32)W2B(g)<<8)|((uint32)W2B(b)<<16)|((uint32)W2B(a)<<24)) #define DECLAREContigPutFunc(name) \ static void name(\ TIFFRGBAImage* img, \ uint32* cp, \ uint32 x, uint32 y, \ uint32 w, uint32 h, \ int32 fromskew, int32 toskew, \ unsigned char* pp \ ) /* * 8-bit palette => colormap/RGB */ DECLAREContigPutFunc(put8bitcmaptile) { uint32** PALmap = img->PALmap; int samplesperpixel = img->samplesperpixel; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PALmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 4-bit palette => colormap/RGB */ DECLAREContigPutFunc(put4bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit palette => colormap/RGB */ DECLAREContigPutFunc(put2bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 1-bit palette => colormap/RGB */ DECLAREContigPutFunc(put1bitcmaptile) { uint32** PALmap = img->PALmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = PALmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(putgreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0]; pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 8-bit greyscale with associated alpha => colormap/RGBA */ DECLAREContigPutFunc(putagreytile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = BWmap[*pp][0] & ((uint32)*(pp+1) << 24 | ~A1); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put16bitbwtile) { int samplesperpixel = img->samplesperpixel; uint32** BWmap = img->BWmap; (void) y; for( ; h > 0; --h) { uint16 *wp = (uint16 *) pp; for (x = w; x > 0; --x) { /* use high order byte of 16bit value */ *cp++ = BWmap[*wp >> 8][0]; pp += 2 * samplesperpixel; wp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 1-bit bilevel => colormap/RGB */ DECLAREContigPutFunc(put1bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 8; for( ; h > 0; --h) { uint32* bw; UNROLL8(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 2-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put2bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 4; for( ; h > 0; --h) { uint32* bw; UNROLL4(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 4-bit greyscale => colormap/RGB */ DECLAREContigPutFunc(put4bitbwtile) { uint32** BWmap = img->BWmap; (void) x; (void) y; fromskew /= 2; for( ; h > 0; --h) { uint32* bw; UNROLL2(w, bw = BWmap[*pp++], *cp++ = *bw++); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples, no Map => RGB */ DECLAREContigPutFunc(putRGBcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(pp[0], pp[1], pp[2]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(pp[0], pp[1], pp[2], pp[3]); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig8bittile) { int samplesperpixel = img->samplesperpixel; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r, g, b, a; uint8* m; for (x = w; x > 0; --x) { a = pp[3]; m = img->UaToAa+((size_t) a<<8); r = m[pp[0]]; g = m[pp[1]]; b = m[pp[2]]; *cp++ = PACK4(r,g,b,a); pp += samplesperpixel; } cp += toskew; pp += fromskew; } } /* * 16-bit packed samples => RGB */ DECLAREContigPutFunc(putRGBcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ associated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBAAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { *cp++ = PACK4(img->Bitdepth16To8[wp[0]], img->Bitdepth16To8[wp[1]], img->Bitdepth16To8[wp[2]], img->Bitdepth16To8[wp[3]]); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 16-bit packed samples => RGBA w/ unassociated alpha * (known to have Map == NULL) */ DECLAREContigPutFunc(putRGBUAcontig16bittile) { int samplesperpixel = img->samplesperpixel; uint16 *wp = (uint16 *)pp; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { uint32 r,g,b,a; uint8* m; for (x = w; x > 0; --x) { a = img->Bitdepth16To8[wp[3]]; m = img->UaToAa+((size_t) a<<8); r = m[img->Bitdepth16To8[wp[0]]]; g = m[img->Bitdepth16To8[wp[1]]]; b = m[img->Bitdepth16To8[wp[2]]]; *cp++ = PACK4(r,g,b,a); wp += samplesperpixel; } cp += toskew; wp += fromskew; } } /* * 8-bit packed CMYK samples w/o Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKtile) { int samplesperpixel = img->samplesperpixel; uint16 r, g, b, k; (void) x; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { UNROLL8(w, NOP, k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(r, g, b); pp += samplesperpixel); cp += toskew; pp += fromskew; } } /* * 8-bit packed CMYK samples w/Map => RGB * * NB: The conversion of CMYK->RGB is *very* crude. */ DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile) { int samplesperpixel = img->samplesperpixel; TIFFRGBValue* Map = img->Map; uint16 r, g, b, k; (void) y; fromskew *= samplesperpixel; for( ; h > 0; --h) { for (x = w; x > 0; --x) { k = 255 - pp[3]; r = (k*(255-pp[0]))/255; g = (k*(255-pp[1]))/255; b = (k*(255-pp[2]))/255; *cp++ = PACK(Map[r], Map[g], Map[b]); pp += samplesperpixel; } pp += fromskew; cp += toskew; } } #define DECLARESepPutFunc(name) \ static void name(\ TIFFRGBAImage* img,\ uint32* cp,\ uint32 x, uint32 y, \ uint32 w, uint32 h,\ int32 fromskew, int32 toskew,\ unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a\ ) /* * 8-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate8bittile) { (void) img; (void) x; (void) y; (void) a; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK(*r++, *g++, *b++)); SKEW(r, g, b, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate8bittile) { (void) img; (void) x; (void) y; for( ; h > 0; --h) { UNROLL8(w, NOP, *cp++ = PACK4(*r++, *g++, *b++, *a++)); SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked CMYK samples => RGBA */ DECLARESepPutFunc(putCMYKseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, kv; for (x = w; x > 0; --x) { kv = 255 - *a++; rv = (kv*(255-*r++))/255; gv = (kv*(255-*g++))/255; bv = (kv*(255-*b++))/255; *cp++ = PACK4(rv,gv,bv,255); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 8-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate8bittile) { (void) img; (void) y; for( ; h > 0; --h) { uint32 rv, gv, bv, av; uint8* m; for (x = w; x > 0; --x) { av = *a++; m = img->UaToAa+((size_t) av<<8); rv = m[*r++]; gv = m[*g++]; bv = m[*b++]; *cp++ = PACK4(rv,gv,bv,av); } SKEW4(r, g, b, a, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGB */ DECLARESepPutFunc(putRGBseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; (void) img; (void) y; (void) a; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++]); SKEW(wr, wg, wb, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ associated alpha */ DECLARESepPutFunc(putRGBAAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { for (x = 0; x < w; x++) *cp++ = PACK4(img->Bitdepth16To8[*wr++], img->Bitdepth16To8[*wg++], img->Bitdepth16To8[*wb++], img->Bitdepth16To8[*wa++]); SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 16-bit unpacked samples => RGBA w/ unassociated alpha */ DECLARESepPutFunc(putRGBUAseparate16bittile) { uint16 *wr = (uint16*) r; uint16 *wg = (uint16*) g; uint16 *wb = (uint16*) b; uint16 *wa = (uint16*) a; (void) img; (void) y; for( ; h > 0; --h) { uint32 r2,g2,b2,a2; uint8* m; for (x = w; x > 0; --x) { a2 = img->Bitdepth16To8[*wa++]; m = img->UaToAa+((size_t) a2<<8); r2 = m[img->Bitdepth16To8[*wr++]]; g2 = m[img->Bitdepth16To8[*wg++]]; b2 = m[img->Bitdepth16To8[*wb++]]; *cp++ = PACK4(r2,g2,b2,a2); } SKEW4(wr, wg, wb, wa, fromskew); cp += toskew; } } /* * 8-bit packed CIE L*a*b 1976 samples => RGB */ DECLAREContigPutFunc(putcontig8bitCIELab) { float X, Y, Z; uint32 r, g, b; (void) y; fromskew *= 3; for( ; h > 0; --h) { for (x = w; x > 0; --x) { TIFFCIELabToXYZ(img->cielab, (unsigned char)pp[0], (signed char)pp[1], (signed char)pp[2], &X, &Y, &Z); TIFFXYZToRGB(img->cielab, X, Y, Z, &r, &g, &b); *cp++ = PACK(r, g, b); pp += 3; } cp += toskew; pp += fromskew; } } /* * YCbCr -> RGB conversion and packing routines. */ #define YCbCrtoRGB(dst, Y) { \ uint32 r, g, b; \ TIFFYCbCrtoRGB(img->ycbcr, (Y), Cb, Cr, &r, &g, &b); \ dst = PACK(r, g, b); \ } /* * 8-bit packed YCbCr samples => RGB * This function is generic for different sampling sizes, * and can handle blocks sizes that aren't multiples of the * sampling size. However, it is substantially less optimized * than the specific sampling cases. It is used as a fallback * for difficult blocks. */ #ifdef notdef static void putcontig8bitYCbCrGenericTile( TIFFRGBAImage* img, uint32* cp, uint32 x, uint32 y, uint32 w, uint32 h, int32 fromskew, int32 toskew, unsigned char* pp, int h_group, int v_group ) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; int32 Cb, Cr; int group_size = v_group * h_group + 2; (void) y; fromskew = (fromskew * group_size) / h_group; for( yy = 0; yy < h; yy++ ) { unsigned char *pp_line; int y_line_group = yy / v_group; int y_remainder = yy - y_line_group * v_group; pp_line = pp + v_line_group * for( xx = 0; xx < w; xx++ ) { Cb = pp } } for (; h >= 4; h -= 4) { x = w>>2; do { Cb = pp[16]; Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4, cp1 += 4, cp2 += 4, cp3 += 4; pp += 18; } while (--x); cp += incr, cp1 += incr, cp2 += incr, cp3 += incr; pp += fromskew; } } #endif /* * 8-bit packed YCbCr samples w/ 4,4 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr44tile) { uint32* cp1 = cp+w+toskew; uint32* cp2 = cp1+w+toskew; uint32* cp3 = cp2+w+toskew; int32 incr = 3*w+4*toskew; (void) y; /* adjust fromskew */ fromskew = (fromskew / 4) * (4*2+2); if ((h & 3) == 0 && (w & 3) == 0) { for (; h >= 4; h -= 4) { x = w>>2; do { int32 Cb = pp[16]; int32 Cr = pp[17]; YCbCrtoRGB(cp [0], pp[ 0]); YCbCrtoRGB(cp [1], pp[ 1]); YCbCrtoRGB(cp [2], pp[ 2]); YCbCrtoRGB(cp [3], pp[ 3]); YCbCrtoRGB(cp1[0], pp[ 4]); YCbCrtoRGB(cp1[1], pp[ 5]); YCbCrtoRGB(cp1[2], pp[ 6]); YCbCrtoRGB(cp1[3], pp[ 7]); YCbCrtoRGB(cp2[0], pp[ 8]); YCbCrtoRGB(cp2[1], pp[ 9]); YCbCrtoRGB(cp2[2], pp[10]); YCbCrtoRGB(cp2[3], pp[11]); YCbCrtoRGB(cp3[0], pp[12]); YCbCrtoRGB(cp3[1], pp[13]); YCbCrtoRGB(cp3[2], pp[14]); YCbCrtoRGB(cp3[3], pp[15]); cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; pp += 18; } while (--x); cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[16]; int32 Cr = pp[17]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp3[3], pp[15]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[3], pp[11]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp3[2], pp[14]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[2], pp[10]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp3[1], pp[13]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[1], pp[ 9]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp3[0], pp[12]); /* FALLTHROUGH */ case 3: YCbCrtoRGB(cp2[0], pp[ 8]); /* FALLTHROUGH */ case 2: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; cp2 += x; cp3 += x; x = 0; } else { cp += 4; cp1 += 4; cp2 += 4; cp3 += 4; x -= 4; } pp += 18; } if (h <= 4) break; h -= 4; cp += incr; cp1 += incr; cp2 += incr; cp3 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr42tile) { uint32* cp1 = cp+w+toskew; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 4) * (4*2+2); if ((w & 3) == 0 && (h & 1) == 0) { for (; h >= 2; h -= 2) { x = w>>2; do { int32 Cb = pp[8]; int32 Cr = pp[9]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); YCbCrtoRGB(cp1[0], pp[4]); YCbCrtoRGB(cp1[1], pp[5]); YCbCrtoRGB(cp1[2], pp[6]); YCbCrtoRGB(cp1[3], pp[7]); cp += 4; cp1 += 4; pp += 10; } while (--x); cp += incr; cp1 += incr; pp += fromskew; } } else { while (h > 0) { for (x = w; x > 0;) { int32 Cb = pp[8]; int32 Cr = pp[9]; switch (x) { default: switch (h) { default: YCbCrtoRGB(cp1[3], pp[ 7]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [3], pp[ 3]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 3: switch (h) { default: YCbCrtoRGB(cp1[2], pp[ 6]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [2], pp[ 2]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 2: switch (h) { default: YCbCrtoRGB(cp1[1], pp[ 5]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [1], pp[ 1]); /* FALLTHROUGH */ } /* FALLTHROUGH */ case 1: switch (h) { default: YCbCrtoRGB(cp1[0], pp[ 4]); /* FALLTHROUGH */ case 1: YCbCrtoRGB(cp [0], pp[ 0]); /* FALLTHROUGH */ } /* FALLTHROUGH */ } if (x < 4) { cp += x; cp1 += x; x = 0; } else { cp += 4; cp1 += 4; x -= 4; } pp += 10; } if (h <= 2) break; h -= 2; cp += incr; cp1 += incr; pp += fromskew; } } } /* * 8-bit packed YCbCr samples w/ 4,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr41tile) { (void) y; fromskew = (fromskew / 4) * (4*1+2); do { x = w>>2; while(x>0) { int32 Cb = pp[4]; int32 Cr = pp[5]; YCbCrtoRGB(cp [0], pp[0]); YCbCrtoRGB(cp [1], pp[1]); YCbCrtoRGB(cp [2], pp[2]); YCbCrtoRGB(cp [3], pp[3]); cp += 4; pp += 6; x--; } if( (w&3) != 0 ) { int32 Cb = pp[4]; int32 Cr = pp[5]; switch( (w&3) ) { case 3: YCbCrtoRGB(cp [2], pp[2]); /*-fallthrough*/ case 2: YCbCrtoRGB(cp [1], pp[1]); /*-fallthrough*/ case 1: YCbCrtoRGB(cp [0], pp[0]); /*-fallthrough*/ case 0: break; } cp += (w&3); pp += 6; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 2,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr22tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 2) * (2*2+2); cp2 = cp+w+toskew; while (h>=2) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); YCbCrtoRGB(cp2[0], pp[2]); YCbCrtoRGB(cp2[1], pp[3]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[2]); cp ++ ; cp2 ++ ; pp += 6; } cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; while (x>=2) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; cp2 += 2; pp += 6; x -= 2; } if (x==1) { uint32 Cb = pp[4]; uint32 Cr = pp[5]; YCbCrtoRGB(cp[0], pp[0]); } } } /* * 8-bit packed YCbCr samples w/ 2,1 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr21tile) { (void) y; fromskew = (fromskew / 2) * (2*1+2); do { x = w>>1; while(x>0) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp[1], pp[1]); cp += 2; pp += 4; x --; } if( (w&1) != 0 ) { int32 Cb = pp[2]; int32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp += 1; pp += 4; } cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ 1,2 subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr12tile) { uint32* cp2; int32 incr = 2*toskew+w; (void) y; fromskew = (fromskew / 1) * (1 * 2 + 2); cp2 = cp+w+toskew; while (h>=2) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); YCbCrtoRGB(cp2[0], pp[1]); cp ++; cp2 ++; pp += 4; } while (--x); cp += incr; cp2 += incr; pp += fromskew; h-=2; } if (h==1) { x = w; do { uint32 Cb = pp[2]; uint32 Cr = pp[3]; YCbCrtoRGB(cp[0], pp[0]); cp ++; pp += 4; } while (--x); } } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLAREContigPutFunc(putcontig8bitYCbCr11tile) { (void) y; fromskew = (fromskew / 1) * (1 * 1 + 2); do { x = w; /* was x = w>>1; patched 2000/09/25 warmerda@home.com */ do { int32 Cb = pp[1]; int32 Cr = pp[2]; YCbCrtoRGB(*cp++, pp[0]); pp += 3; } while (--x); cp += toskew; pp += fromskew; } while (--h); } /* * 8-bit packed YCbCr samples w/ no subsampling => RGB */ DECLARESepPutFunc(putseparate8bitYCbCr11tile) { (void) y; (void) a; /* TODO: naming of input vars is still off, change obfuscating declaration inside define, or resolve obfuscation */ for( ; h > 0; --h) { x = w; do { uint32 dr, dg, db; TIFFYCbCrtoRGB(img->ycbcr,*r++,*g++,*b++,&dr,&dg,&db); *cp++ = PACK(dr,dg,db); } while (--x); SKEW(r, g, b, fromskew); cp += toskew; } } #undef YCbCrtoRGB static int isInRefBlackWhiteRange(float f) { return f > (float)(-0x7FFFFFFF + 128) && f < (float)0x7FFFFFFF; } static int initYCbCrConversion(TIFFRGBAImage* img) { static const char module[] = "initYCbCrConversion"; float *luma, *refBlackWhite; if (img->ycbcr == NULL) { img->ycbcr = (TIFFYCbCrToRGB*) _TIFFmalloc( TIFFroundup_32(sizeof (TIFFYCbCrToRGB), sizeof (long)) + 4*256*sizeof (TIFFRGBValue) + 2*256*sizeof (int) + 3*256*sizeof (int32) ); if (img->ycbcr == NULL) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for YCbCr->RGB conversion state"); return (0); } } TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRCOEFFICIENTS, &luma); TIFFGetFieldDefaulted(img->tif, TIFFTAG_REFERENCEBLACKWHITE, &refBlackWhite); /* Do some validation to avoid later issues. Detect NaN for now */ /* and also if lumaGreen is zero since we divide by it later */ if( luma[0] != luma[0] || luma[1] != luma[1] || luma[1] == 0.0 || luma[2] != luma[2] ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for YCbCrCoefficients tag"); return (0); } if( !isInRefBlackWhiteRange(refBlackWhite[0]) || !isInRefBlackWhiteRange(refBlackWhite[1]) || !isInRefBlackWhiteRange(refBlackWhite[2]) || !isInRefBlackWhiteRange(refBlackWhite[3]) || !isInRefBlackWhiteRange(refBlackWhite[4]) || !isInRefBlackWhiteRange(refBlackWhite[5]) ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid values for ReferenceBlackWhite tag"); return (0); } if (TIFFYCbCrToRGBInit(img->ycbcr, luma, refBlackWhite) < 0) return(0); return (1); } static tileContigRoutine initCIELabConversion(TIFFRGBAImage* img) { static const char module[] = "initCIELabConversion"; float *whitePoint; float refWhite[3]; TIFFGetFieldDefaulted(img->tif, TIFFTAG_WHITEPOINT, &whitePoint); if (whitePoint[1] == 0.0f ) { TIFFErrorExt(img->tif->tif_clientdata, module, "Invalid value for WhitePoint tag."); return NULL; } if (!img->cielab) { img->cielab = (TIFFCIELabToRGB *) _TIFFmalloc(sizeof(TIFFCIELabToRGB)); if (!img->cielab) { TIFFErrorExt(img->tif->tif_clientdata, module, "No space for CIE L*a*b*->RGB conversion state."); return NULL; } } refWhite[1] = 100.0F; refWhite[0] = whitePoint[0] / whitePoint[1] * refWhite[1]; refWhite[2] = (1.0F - whitePoint[0] - whitePoint[1]) / whitePoint[1] * refWhite[1]; if (TIFFCIELabToRGBInit(img->cielab, &display_sRGB, refWhite) < 0) { TIFFErrorExt(img->tif->tif_clientdata, module, "Failed to initialize CIE L*a*b*->RGB conversion state."); _TIFFfree(img->cielab); return NULL; } return putcontig8bitCIELab; } /* * Greyscale images with less than 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*bwtile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makebwmap(TIFFRGBAImage* img) { TIFFRGBValue* Map = img->Map; int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; int i; uint32* p; if( nsamples == 0 ) nsamples = 1; img->BWmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->BWmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for B&W mapping table"); return (0); } p = (uint32*)(img->BWmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->BWmap[i] = p; switch (bitspersample) { #define GREY(x) c = Map[x]; *p++ = PACK(c,c,c); case 1: GREY(i>>7); GREY((i>>6)&1); GREY((i>>5)&1); GREY((i>>4)&1); GREY((i>>3)&1); GREY((i>>2)&1); GREY((i>>1)&1); GREY(i&1); break; case 2: GREY(i>>6); GREY((i>>4)&3); GREY((i>>2)&3); GREY(i&3); break; case 4: GREY(i>>4); GREY(i&0xf); break; case 8: case 16: GREY(i); break; } #undef GREY } return (1); } /* * Construct a mapping table to convert from the range * of the data samples to [0,255] --for display. This * process also handles inverting B&W images when needed. */ static int setupMap(TIFFRGBAImage* img) { int32 x, range; range = (int32)((1L<<img->bitspersample)-1); /* treat 16 bit the same as eight bit */ if( img->bitspersample == 16 ) range = (int32) 255; img->Map = (TIFFRGBValue*) _TIFFmalloc((range+1) * sizeof (TIFFRGBValue)); if (img->Map == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for photometric conversion table"); return (0); } if (img->photometric == PHOTOMETRIC_MINISWHITE) { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) (((range - x) * 255) / range); } else { for (x = 0; x <= range; x++) img->Map[x] = (TIFFRGBValue) ((x * 255) / range); } if (img->bitspersample <= 16 && (img->photometric == PHOTOMETRIC_MINISBLACK || img->photometric == PHOTOMETRIC_MINISWHITE)) { /* * Use photometric mapping table to construct * unpacking tables for samples <= 8 bits. */ if (!makebwmap(img)) return (0); /* no longer need Map, free it */ _TIFFfree(img->Map); img->Map = NULL; } return (1); } static int checkcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long n = 1L<<img->bitspersample; while (n-- > 0) if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) return (16); return (8); } static void cvtcmap(TIFFRGBAImage* img) { uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; long i; for (i = (1L<<img->bitspersample)-1; i >= 0; i--) { #define CVT(x) ((uint16)((x)>>8)) r[i] = CVT(r[i]); g[i] = CVT(g[i]); b[i] = CVT(b[i]); #undef CVT } } /* * Palette images with <= 8 bits/sample are handled * with a table to avoid lots of shifts and masks. The table * is setup so that put*cmaptile (below) can retrieve 8/bitspersample * pixel values simply by indexing into the table with one * number. */ static int makecmap(TIFFRGBAImage* img) { int bitspersample = img->bitspersample; int nsamples = 8 / bitspersample; uint16* r = img->redcmap; uint16* g = img->greencmap; uint16* b = img->bluecmap; uint32 *p; int i; img->PALmap = (uint32**) _TIFFmalloc( 256*sizeof (uint32 *)+(256*nsamples*sizeof(uint32))); if (img->PALmap == NULL) { TIFFErrorExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "No space for Palette mapping table"); return (0); } p = (uint32*)(img->PALmap + 256); for (i = 0; i < 256; i++) { TIFFRGBValue c; img->PALmap[i] = p; #define CMAP(x) c = (TIFFRGBValue) x; *p++ = PACK(r[c]&0xff, g[c]&0xff, b[c]&0xff); switch (bitspersample) { case 1: CMAP(i>>7); CMAP((i>>6)&1); CMAP((i>>5)&1); CMAP((i>>4)&1); CMAP((i>>3)&1); CMAP((i>>2)&1); CMAP((i>>1)&1); CMAP(i&1); break; case 2: CMAP(i>>6); CMAP((i>>4)&3); CMAP((i>>2)&3); CMAP(i&3); break; case 4: CMAP(i>>4); CMAP(i&0xf); break; case 8: CMAP(i); break; } #undef CMAP } return (1); } /* * Construct any mapping table used * by the associated put routine. */ static int buildMap(TIFFRGBAImage* img) { switch (img->photometric) { case PHOTOMETRIC_RGB: case PHOTOMETRIC_YCBCR: case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8) break; /* fall through... */ case PHOTOMETRIC_MINISBLACK: case PHOTOMETRIC_MINISWHITE: if (!setupMap(img)) return (0); break; case PHOTOMETRIC_PALETTE: /* * Convert 16-bit colormap to 8-bit (unless it looks * like an old-style 8-bit colormap). */ if (checkcmap(img) == 16) cvtcmap(img); else TIFFWarningExt(img->tif->tif_clientdata, TIFFFileName(img->tif), "Assuming 8-bit colormap"); /* * Use mapping table and colormap to construct * unpacking tables for samples < 8 bits. */ if (img->bitspersample <= 8 && !makecmap(img)) return (0); break; } return (1); } /* * Select the appropriate conversion routine for packed data. */ static int PickContigCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileContig : gtStripContig; img->put.contig = NULL; switch (img->photometric) { case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >= 4) img->put.contig = putRGBAAcontig8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >= 4) { if (BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig8bittile; } else if( img->samplesperpixel >= 3 ) img->put.contig = putRGBcontig8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBAAcontig16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA && img->samplesperpixel >=4 ) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.contig = putRGBUAcontig16bittile; } else if( img->samplesperpixel >=3 ) { if (BuildMapBitdepth16To8(img)) img->put.contig = putRGBcontig16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->samplesperpixel >=4 && buildMap(img)) { if (img->bitspersample == 8) { if (!img->Map) img->put.contig = putRGBcontig8bitCMYKtile; else img->put.contig = putRGBcontig8bitCMYKMaptile; } } break; case PHOTOMETRIC_PALETTE: if (buildMap(img)) { switch (img->bitspersample) { case 8: img->put.contig = put8bitcmaptile; break; case 4: img->put.contig = put4bitcmaptile; break; case 2: img->put.contig = put2bitcmaptile; break; case 1: img->put.contig = put1bitcmaptile; break; } } break; case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: if (buildMap(img)) { switch (img->bitspersample) { case 16: img->put.contig = put16bitbwtile; break; case 8: if (img->alpha && img->samplesperpixel == 2) img->put.contig = putagreytile; else img->put.contig = putgreytile; break; case 4: img->put.contig = put4bitbwtile; break; case 2: img->put.contig = put2bitbwtile; break; case 1: img->put.contig = put1bitbwtile; break; } } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { /* * The 6.0 spec says that subsampling must be * one of 1, 2, or 4, and that vertical subsampling * must always be <= horizontal subsampling; so * there are only a few possibilities and we just * enumerate the cases. * Joris: added support for the [1,2] case, nonetheless, to accommodate * some OJPEG files */ uint16 SubsamplingHor; uint16 SubsamplingVer; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &SubsamplingHor, &SubsamplingVer); switch ((SubsamplingHor<<4)|SubsamplingVer) { case 0x44: img->put.contig = putcontig8bitYCbCr44tile; break; case 0x42: img->put.contig = putcontig8bitYCbCr42tile; break; case 0x41: img->put.contig = putcontig8bitYCbCr41tile; break; case 0x22: img->put.contig = putcontig8bitYCbCr22tile; break; case 0x21: img->put.contig = putcontig8bitYCbCr21tile; break; case 0x12: img->put.contig = putcontig8bitYCbCr12tile; break; case 0x11: img->put.contig = putcontig8bitYCbCr11tile; break; } } } break; case PHOTOMETRIC_CIELAB: if (img->samplesperpixel == 3 && buildMap(img)) { if (img->bitspersample == 8) img->put.contig = initCIELabConversion(img); break; } } return ((img->get!=NULL) && (img->put.contig!=NULL)); } /* * Select the appropriate conversion routine for unpacked data. * * NB: we assume that unpacked single channel data is directed * to the "packed routines. */ static int PickSeparateCase(TIFFRGBAImage* img) { img->get = TIFFIsTiled(img->tif) ? gtTileSeparate : gtStripSeparate; img->put.separate = NULL; switch (img->photometric) { case PHOTOMETRIC_MINISWHITE: case PHOTOMETRIC_MINISBLACK: /* greyscale images processed pretty much as RGB by gtTileSeparate */ case PHOTOMETRIC_RGB: switch (img->bitspersample) { case 8: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) img->put.separate = putRGBAAseparate8bittile; else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate8bittile; } else img->put.separate = putRGBseparate8bittile; break; case 16: if (img->alpha == EXTRASAMPLE_ASSOCALPHA) { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBAAseparate16bittile; } else if (img->alpha == EXTRASAMPLE_UNASSALPHA) { if (BuildMapBitdepth16To8(img) && BuildMapUaToAa(img)) img->put.separate = putRGBUAseparate16bittile; } else { if (BuildMapBitdepth16To8(img)) img->put.separate = putRGBseparate16bittile; } break; } break; case PHOTOMETRIC_SEPARATED: if (img->bitspersample == 8 && img->samplesperpixel == 4) { img->alpha = 1; // Not alpha, but seems like the only way to get 4th band img->put.separate = putCMYKseparate8bittile; } break; case PHOTOMETRIC_YCBCR: if ((img->bitspersample==8) && (img->samplesperpixel==3)) { if (initYCbCrConversion(img)!=0) { uint16 hs, vs; TIFFGetFieldDefaulted(img->tif, TIFFTAG_YCBCRSUBSAMPLING, &hs, &vs); switch ((hs<<4)|vs) { case 0x11: img->put.separate = putseparate8bitYCbCr11tile; break; /* TODO: add other cases here */ } } } break; } return ((img->get!=NULL) && (img->put.separate!=NULL)); } static int BuildMapUaToAa(TIFFRGBAImage* img) { static const char module[]="BuildMapUaToAa"; uint8* m; uint16 na,nv; assert(img->UaToAa==NULL); img->UaToAa=_TIFFmalloc(65536); if (img->UaToAa==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->UaToAa; for (na=0; na<256; na++) { for (nv=0; nv<256; nv++) *m++=(uint8)((nv*na+127)/255); } return(1); } static int BuildMapBitdepth16To8(TIFFRGBAImage* img) { static const char module[]="BuildMapBitdepth16To8"; uint8* m; uint32 n; assert(img->Bitdepth16To8==NULL); img->Bitdepth16To8=_TIFFmalloc(65536); if (img->Bitdepth16To8==NULL) { TIFFErrorExt(img->tif->tif_clientdata,module,"Out of memory"); return(0); } m=img->Bitdepth16To8; for (n=0; n<65536; n++) *m++=(uint8)((n+128)/257); return(1); } /* * Read a whole strip off data from the file, and convert to RGBA form. * If this is the last strip, then it will only contain the portion of * the strip that is actually within the image space. The result is * organized in bottom to top form. */ int TIFFReadRGBAStrip(TIFF* tif, uint32 row, uint32 * raster ) { return TIFFReadRGBAStripExt(tif, row, raster, 0 ); } int TIFFReadRGBAStripExt(TIFF* tif, uint32 row, uint32 * raster, int stop_on_error) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 rowsperstrip, rows_to_read; if( TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBAStrip() with tiled file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip); if( (row % rowsperstrip) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row passed to TIFFReadRGBAStrip() must be first in a strip."); return (0); } if (TIFFRGBAImageOK(tif, emsg) && TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { img.row_offset = row; img.col_offset = 0; if( row + rowsperstrip > img.height ) rows_to_read = img.height - row; else rows_to_read = rowsperstrip; ok = TIFFRGBAImageGet(&img, raster, img.width, rows_to_read ); TIFFRGBAImageEnd(&img); } else { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); ok = 0; } return (ok); } /* * Read a whole tile off data from the file, and convert to RGBA form. * The returned RGBA data is organized from bottom to top of tile, * and may include zeroed areas if the tile extends off the image. */ int TIFFReadRGBATile(TIFF* tif, uint32 col, uint32 row, uint32 * raster) { return TIFFReadRGBATileExt(tif, col, row, raster, 0 ); } int TIFFReadRGBATileExt(TIFF* tif, uint32 col, uint32 row, uint32 * raster, int stop_on_error ) { char emsg[1024] = ""; TIFFRGBAImage img; int ok; uint32 tile_xsize, tile_ysize; uint32 read_xsize, read_ysize; uint32 i_row; /* * Verify that our request is legal - on a tile file, and on a * tile boundary. */ if( !TIFFIsTiled( tif ) ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Can't use TIFFReadRGBATile() with striped file."); return (0); } TIFFGetFieldDefaulted(tif, TIFFTAG_TILEWIDTH, &tile_xsize); TIFFGetFieldDefaulted(tif, TIFFTAG_TILELENGTH, &tile_ysize); if( (col % tile_xsize) != 0 || (row % tile_ysize) != 0 ) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Row/col passed to TIFFReadRGBATile() must be top" "left corner of a tile."); return (0); } /* * Setup the RGBA reader. */ if (!TIFFRGBAImageOK(tif, emsg) || !TIFFRGBAImageBegin(&img, tif, stop_on_error, emsg)) { TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "%s", emsg); return( 0 ); } /* * The TIFFRGBAImageGet() function doesn't allow us to get off the * edge of the image, even to fill an otherwise valid tile. So we * figure out how much we can read, and fix up the tile buffer to * a full tile configuration afterwards. */ if( row + tile_ysize > img.height ) read_ysize = img.height - row; else read_ysize = tile_ysize; if( col + tile_xsize > img.width ) read_xsize = img.width - col; else read_xsize = tile_xsize; /* * Read the chunk of imagery. */ img.row_offset = row; img.col_offset = col; ok = TIFFRGBAImageGet(&img, raster, read_xsize, read_ysize ); TIFFRGBAImageEnd(&img); /* * If our read was incomplete we will need to fix up the tile by * shifting the data around as if a full tile of data is being returned. * * This is all the more complicated because the image is organized in * bottom to top format. */ if( read_xsize == tile_xsize && read_ysize == tile_ysize ) return( ok ); for( i_row = 0; i_row < read_ysize; i_row++ ) { memmove( raster + (tile_ysize - i_row - 1) * tile_xsize, raster + (read_ysize - i_row - 1) * read_xsize, read_xsize * sizeof(uint32) ); _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize+read_xsize, 0, sizeof(uint32) * (tile_xsize - read_xsize) ); } for( i_row = read_ysize; i_row < tile_ysize; i_row++ ) { _TIFFmemset( raster + (tile_ysize - i_row - 1) * tile_xsize, 0, sizeof(uint32) * tile_xsize ); } return (ok); } /* vim: set ts=8 sts=8 sw=8 noet: */ /* * Local Variables: * mode: c * c-basic-offset: 8 * fill-column: 78 * End: */
./CrossVul/dataset_final_sorted/CWE-190/c/good_1185_0
crossvul-cpp_data_good_966_0
// SPDX-License-Identifier: GPL-2.0-only /* * linux/drivers/block/floppy.c * * Copyright (C) 1991, 1992 Linus Torvalds * Copyright (C) 1993, 1994 Alain Knaff * Copyright (C) 1998 Alan Cox */ /* * 02.12.91 - Changed to static variables to indicate need for reset * and recalibrate. This makes some things easier (output_byte reset * checking etc), and means less interrupt jumping in case of errors, * so the code is hopefully easier to understand. */ /* * This file is certainly a mess. I've tried my best to get it working, * but I don't like programming floppies, and I have only one anyway. * Urgel. I should check for more errors, and do more graceful error * recovery. Seems there are problems with several drives. I've tried to * correct them. No promises. */ /* * As with hd.c, all routines within this file can (and will) be called * by interrupts, so extreme caution is needed. A hardware interrupt * handler may not sleep, or a kernel panic will happen. Thus I cannot * call "floppy-on" directly, but have to set a special timer interrupt * etc. */ /* * 28.02.92 - made track-buffering routines, based on the routines written * by entropy@wintermute.wpi.edu (Lawrence Foard). Linus. */ /* * Automatic floppy-detection and formatting written by Werner Almesberger * (almesber@nessie.cs.id.ethz.ch), who also corrected some problems with * the floppy-change signal detection. */ /* * 1992/7/22 -- Hennus Bergman: Added better error reporting, fixed * FDC data overrun bug, added some preliminary stuff for vertical * recording support. * * 1992/9/17: Added DMA allocation & DMA functions. -- hhb. * * TODO: Errors are still not counted properly. */ /* 1992/9/20 * Modifications for ``Sector Shifting'' by Rob Hooft (hooft@chem.ruu.nl) * modeled after the freeware MS-DOS program fdformat/88 V1.8 by * Christoph H. Hochst\"atter. * I have fixed the shift values to the ones I always use. Maybe a new * ioctl() should be created to be able to modify them. * There is a bug in the driver that makes it impossible to format a * floppy as the first thing after bootup. */ /* * 1993/4/29 -- Linus -- cleaned up the timer handling in the kernel, and * this helped the floppy driver as well. Much cleaner, and still seems to * work. */ /* 1994/6/24 --bbroad-- added the floppy table entries and made * minor modifications to allow 2.88 floppies to be run. */ /* 1994/7/13 -- Paul Vojta -- modified the probing code to allow three or more * disk types. */ /* * 1994/8/8 -- Alain Knaff -- Switched to fdpatch driver: Support for bigger * format bug fixes, but unfortunately some new bugs too... */ /* 1994/9/17 -- Koen Holtman -- added logging of physical floppy write * errors to allow safe writing by specialized programs. */ /* 1995/4/24 -- Dan Fandrich -- added support for Commodore 1581 3.5" disks * by defining bit 1 of the "stretch" parameter to mean put sectors on the * opposite side of the disk, leaving the sector IDs alone (i.e. Commodore's * drives are "upside-down"). */ /* * 1995/8/26 -- Andreas Busse -- added Mips support. */ /* * 1995/10/18 -- Ralf Baechle -- Portability cleanup; move machine dependent * features to asm/floppy.h. */ /* * 1998/1/21 -- Richard Gooch <rgooch@atnf.csiro.au> -- devfs support */ /* * 1998/05/07 -- Russell King -- More portability cleanups; moved definition of * interrupt and dma channel to asm/floppy.h. Cleaned up some formatting & * use of '0' for NULL. */ /* * 1998/06/07 -- Alan Cox -- Merged the 2.0.34 fixes for resource allocation * failures. */ /* * 1998/09/20 -- David Weinehall -- Added slow-down code for buggy PS/2-drives. */ /* * 1999/08/13 -- Paul Slootman -- floppy stopped working on Alpha after 24 * days, 6 hours, 32 minutes and 32 seconds (i.e. MAXINT jiffies; ints were * being used to store jiffies, which are unsigned longs). */ /* * 2000/08/28 -- Arnaldo Carvalho de Melo <acme@conectiva.com.br> * - get rid of check_region * - s/suser/capable/ */ /* * 2001/08/26 -- Paul Gortmaker - fix insmod oops on machines with no * floppy controller (lingering task on list after module is gone... boom.) */ /* * 2002/02/07 -- Anton Altaparmakov - Fix io ports reservation to correct range * (0x3f2-0x3f5, 0x3f7). This fix is a bit of a hack but the proper fix * requires many non-obvious changes in arch dependent code. */ /* 2003/07/28 -- Daniele Bellucci <bellucda@tiscali.it>. * Better audit of register_blkdev. */ #undef FLOPPY_SILENT_DCL_CLEAR #define REALLY_SLOW_IO #define DEBUGT 2 #define DPRINT(format, args...) \ pr_info("floppy%d: " format, current_drive, ##args) #define DCL_DEBUG /* debug disk change line */ #ifdef DCL_DEBUG #define debug_dcl(test, fmt, args...) \ do { if ((test) & FD_DEBUG) DPRINT(fmt, ##args); } while (0) #else #define debug_dcl(test, fmt, args...) \ do { if (0) DPRINT(fmt, ##args); } while (0) #endif /* do print messages for unexpected interrupts */ static int print_unex = 1; #include <linux/module.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/workqueue.h> #define FDPATCHES #include <linux/fdreg.h> #include <linux/fd.h> #include <linux/hdreg.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/mm.h> #include <linux/bio.h> #include <linux/string.h> #include <linux/jiffies.h> #include <linux/fcntl.h> #include <linux/delay.h> #include <linux/mc146818rtc.h> /* CMOS defines */ #include <linux/ioport.h> #include <linux/interrupt.h> #include <linux/init.h> #include <linux/platform_device.h> #include <linux/mod_devicetable.h> #include <linux/mutex.h> #include <linux/io.h> #include <linux/uaccess.h> #include <linux/async.h> #include <linux/compat.h> /* * PS/2 floppies have much slower step rates than regular floppies. * It's been recommended that take about 1/4 of the default speed * in some more extreme cases. */ static DEFINE_MUTEX(floppy_mutex); static int slow_floppy; #include <asm/dma.h> #include <asm/irq.h> static int FLOPPY_IRQ = 6; static int FLOPPY_DMA = 2; static int can_use_virtual_dma = 2; /* ======= * can use virtual DMA: * 0 = use of virtual DMA disallowed by config * 1 = use of virtual DMA prescribed by config * 2 = no virtual DMA preference configured. By default try hard DMA, * but fall back on virtual DMA when not enough memory available */ static int use_virtual_dma; /* ======= * use virtual DMA * 0 using hard DMA * 1 using virtual DMA * This variable is set to virtual when a DMA mem problem arises, and * reset back in floppy_grab_irq_and_dma. * It is not safe to reset it in other circumstances, because the floppy * driver may have several buffers in use at once, and we do currently not * record each buffers capabilities */ static DEFINE_SPINLOCK(floppy_lock); static unsigned short virtual_dma_port = 0x3f0; irqreturn_t floppy_interrupt(int irq, void *dev_id); static int set_dor(int fdc, char mask, char data); #define K_64 0x10000 /* 64KB */ /* the following is the mask of allowed drives. By default units 2 and * 3 of both floppy controllers are disabled, because switching on the * motor of these drives causes system hangs on some PCI computers. drive * 0 is the low bit (0x1), and drive 7 is the high bit (0x80). Bits are on if * a drive is allowed. * * NOTE: This must come before we include the arch floppy header because * some ports reference this variable from there. -DaveM */ static int allowed_drive_mask = 0x33; #include <asm/floppy.h> static int irqdma_allocated; #include <linux/blk-mq.h> #include <linux/blkpg.h> #include <linux/cdrom.h> /* for the compatibility eject ioctl */ #include <linux/completion.h> static LIST_HEAD(floppy_reqs); static struct request *current_req; static int set_next_request(void); #ifndef fd_get_dma_residue #define fd_get_dma_residue() get_dma_residue(FLOPPY_DMA) #endif /* Dma Memory related stuff */ #ifndef fd_dma_mem_free #define fd_dma_mem_free(addr, size) free_pages(addr, get_order(size)) #endif #ifndef fd_dma_mem_alloc #define fd_dma_mem_alloc(size) __get_dma_pages(GFP_KERNEL, get_order(size)) #endif #ifndef fd_cacheflush #define fd_cacheflush(addr, size) /* nothing... */ #endif static inline void fallback_on_nodma_alloc(char **addr, size_t l) { #ifdef FLOPPY_CAN_FALLBACK_ON_NODMA if (*addr) return; /* we have the memory */ if (can_use_virtual_dma != 2) return; /* no fallback allowed */ pr_info("DMA memory shortage. Temporarily falling back on virtual DMA\n"); *addr = (char *)nodma_mem_alloc(l); #else return; #endif } /* End dma memory related stuff */ static unsigned long fake_change; static bool initialized; #define ITYPE(x) (((x) >> 2) & 0x1f) #define TOMINOR(x) ((x & 3) | ((x & 4) << 5)) #define UNIT(x) ((x) & 0x03) /* drive on fdc */ #define FDC(x) (((x) & 0x04) >> 2) /* fdc of drive */ /* reverse mapping from unit and fdc to drive */ #define REVDRIVE(fdc, unit) ((unit) + ((fdc) << 2)) #define DP (&drive_params[current_drive]) #define DRS (&drive_state[current_drive]) #define DRWE (&write_errors[current_drive]) #define FDCS (&fdc_state[fdc]) #define UDP (&drive_params[drive]) #define UDRS (&drive_state[drive]) #define UDRWE (&write_errors[drive]) #define UFDCS (&fdc_state[FDC(drive)]) #define PH_HEAD(floppy, head) (((((floppy)->stretch & 2) >> 1) ^ head) << 2) #define STRETCH(floppy) ((floppy)->stretch & FD_STRETCH) /* read/write */ #define COMMAND (raw_cmd->cmd[0]) #define DR_SELECT (raw_cmd->cmd[1]) #define TRACK (raw_cmd->cmd[2]) #define HEAD (raw_cmd->cmd[3]) #define SECTOR (raw_cmd->cmd[4]) #define SIZECODE (raw_cmd->cmd[5]) #define SECT_PER_TRACK (raw_cmd->cmd[6]) #define GAP (raw_cmd->cmd[7]) #define SIZECODE2 (raw_cmd->cmd[8]) #define NR_RW 9 /* format */ #define F_SIZECODE (raw_cmd->cmd[2]) #define F_SECT_PER_TRACK (raw_cmd->cmd[3]) #define F_GAP (raw_cmd->cmd[4]) #define F_FILL (raw_cmd->cmd[5]) #define NR_F 6 /* * Maximum disk size (in kilobytes). * This default is used whenever the current disk size is unknown. * [Now it is rather a minimum] */ #define MAX_DISK_SIZE 4 /* 3984 */ /* * globals used by 'result()' */ #define MAX_REPLIES 16 static unsigned char reply_buffer[MAX_REPLIES]; static int inr; /* size of reply buffer, when called from interrupt */ #define ST0 (reply_buffer[0]) #define ST1 (reply_buffer[1]) #define ST2 (reply_buffer[2]) #define ST3 (reply_buffer[0]) /* result of GETSTATUS */ #define R_TRACK (reply_buffer[3]) #define R_HEAD (reply_buffer[4]) #define R_SECTOR (reply_buffer[5]) #define R_SIZECODE (reply_buffer[6]) #define SEL_DLY (2 * HZ / 100) /* * this struct defines the different floppy drive types. */ static struct { struct floppy_drive_params params; const char *name; /* name printed while booting */ } default_drive_params[] = { /* NOTE: the time values in jiffies should be in msec! CMOS drive type | Maximum data rate supported by drive type | | Head load time, msec | | | Head unload time, msec (not used) | | | | Step rate interval, usec | | | | | Time needed for spinup time (jiffies) | | | | | | Timeout for spinning down (jiffies) | | | | | | | Spindown offset (where disk stops) | | | | | | | | Select delay | | | | | | | | | RPS | | | | | | | | | | Max number of tracks | | | | | | | | | | | Interrupt timeout | | | | | | | | | | | | Max nonintlv. sectors | | | | | | | | | | | | | -Max Errors- flags */ {{0, 500, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 80, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4, 8, 2, 1, 5, 3,10}, 3*HZ/2, 0 }, "unknown" }, {{1, 300, 16, 16, 8000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 40, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 1, 0, 0, 0, 0, 0, 0, 0}, 3*HZ/2, 1 }, "360K PC" }, /*5 1/4 360 KB PC*/ {{2, 500, 16, 16, 6000, 4*HZ/10, 3*HZ, 14, SEL_DLY, 6, 83, 3*HZ, 17, {3,1,2,0,2}, 0, 0, { 2, 5, 6,23,10,20,12, 0}, 3*HZ/2, 2 }, "1.2M" }, /*5 1/4 HD AT*/ {{3, 250, 16, 16, 3000, 1*HZ, 3*HZ, 0, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 4,22,21,30, 3, 0, 0, 0}, 3*HZ/2, 4 }, "720k" }, /*3 1/2 DD*/ {{4, 500, 16, 16, 4000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 20, {3,1,2,0,2}, 0, 0, { 7, 4,25,22,31,21,29,11}, 3*HZ/2, 7 }, "1.44M" }, /*3 1/2 HD*/ {{5, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M AMI BIOS" }, /*3 1/2 ED*/ {{6, 1000, 15, 8, 3000, 4*HZ/10, 3*HZ, 10, SEL_DLY, 5, 83, 3*HZ, 40, {3,1,2,0,2}, 0, 0, { 7, 8, 4,25,28,22,31,21}, 3*HZ/2, 8 }, "2.88M" } /*3 1/2 ED*/ /* | --autodetected formats--- | | | * read_track | | Name printed when booting * | Native format * Frequency of disk change checks */ }; static struct floppy_drive_params drive_params[N_DRIVE]; static struct floppy_drive_struct drive_state[N_DRIVE]; static struct floppy_write_errors write_errors[N_DRIVE]; static struct timer_list motor_off_timer[N_DRIVE]; static struct gendisk *disks[N_DRIVE]; static struct blk_mq_tag_set tag_sets[N_DRIVE]; static struct block_device *opened_bdev[N_DRIVE]; static DEFINE_MUTEX(open_lock); static struct floppy_raw_cmd *raw_cmd, default_raw_cmd; /* * This struct defines the different floppy types. * * Bit 0 of 'stretch' tells if the tracks need to be doubled for some * types (e.g. 360kB diskette in 1.2MB drive, etc.). Bit 1 of 'stretch' * tells if the disk is in Commodore 1581 format, which means side 0 sectors * are located on side 1 of the disk but with a side 0 ID, and vice-versa. * This is the same as the Sharp MZ-80 5.25" CP/M disk format, except that the * 1581's logical side 0 is on physical side 1, whereas the Sharp's logical * side 0 is on physical side 0 (but with the misnamed sector IDs). * 'stretch' should probably be renamed to something more general, like * 'options'. * * Bits 2 through 9 of 'stretch' tell the number of the first sector. * The LSB (bit 2) is flipped. For most disks, the first sector * is 1 (represented by 0x00<<2). For some CP/M and music sampler * disks (such as Ensoniq EPS 16plus) it is 0 (represented as 0x01<<2). * For Amstrad CPC disks it is 0xC1 (represented as 0xC0<<2). * * Other parameters should be self-explanatory (see also setfdprm(8)). */ /* Size | Sectors per track | | Head | | | Tracks | | | | Stretch | | | | | Gap 1 size | | | | | | Data rate, | 0x40 for perp | | | | | | | Spec1 (stepping rate, head unload | | | | | | | | /fmt gap (gap2) */ static struct floppy_struct floppy_type[32] = { { 0, 0,0, 0,0,0x00,0x00,0x00,0x00,NULL }, /* 0 no testing */ { 720, 9,2,40,0,0x2A,0x02,0xDF,0x50,"d360" }, /* 1 360KB PC */ { 2400,15,2,80,0,0x1B,0x00,0xDF,0x54,"h1200" }, /* 2 1.2MB AT */ { 720, 9,1,80,0,0x2A,0x02,0xDF,0x50,"D360" }, /* 3 360KB SS 3.5" */ { 1440, 9,2,80,0,0x2A,0x02,0xDF,0x50,"D720" }, /* 4 720KB 3.5" */ { 720, 9,2,40,1,0x23,0x01,0xDF,0x50,"h360" }, /* 5 360KB AT */ { 1440, 9,2,80,0,0x23,0x01,0xDF,0x50,"h720" }, /* 6 720KB AT */ { 2880,18,2,80,0,0x1B,0x00,0xCF,0x6C,"H1440" }, /* 7 1.44MB 3.5" */ { 5760,36,2,80,0,0x1B,0x43,0xAF,0x54,"E2880" }, /* 8 2.88MB 3.5" */ { 6240,39,2,80,0,0x1B,0x43,0xAF,0x28,"E3120" }, /* 9 3.12MB 3.5" */ { 2880,18,2,80,0,0x25,0x00,0xDF,0x02,"h1440" }, /* 10 1.44MB 5.25" */ { 3360,21,2,80,0,0x1C,0x00,0xCF,0x0C,"H1680" }, /* 11 1.68MB 3.5" */ { 820,10,2,41,1,0x25,0x01,0xDF,0x2E,"h410" }, /* 12 410KB 5.25" */ { 1640,10,2,82,0,0x25,0x02,0xDF,0x2E,"H820" }, /* 13 820KB 3.5" */ { 2952,18,2,82,0,0x25,0x00,0xDF,0x02,"h1476" }, /* 14 1.48MB 5.25" */ { 3444,21,2,82,0,0x25,0x00,0xDF,0x0C,"H1722" }, /* 15 1.72MB 3.5" */ { 840,10,2,42,1,0x25,0x01,0xDF,0x2E,"h420" }, /* 16 420KB 5.25" */ { 1660,10,2,83,0,0x25,0x02,0xDF,0x2E,"H830" }, /* 17 830KB 3.5" */ { 2988,18,2,83,0,0x25,0x00,0xDF,0x02,"h1494" }, /* 18 1.49MB 5.25" */ { 3486,21,2,83,0,0x25,0x00,0xDF,0x0C,"H1743" }, /* 19 1.74 MB 3.5" */ { 1760,11,2,80,0,0x1C,0x09,0xCF,0x00,"h880" }, /* 20 880KB 5.25" */ { 2080,13,2,80,0,0x1C,0x01,0xCF,0x00,"D1040" }, /* 21 1.04MB 3.5" */ { 2240,14,2,80,0,0x1C,0x19,0xCF,0x00,"D1120" }, /* 22 1.12MB 3.5" */ { 3200,20,2,80,0,0x1C,0x20,0xCF,0x2C,"h1600" }, /* 23 1.6MB 5.25" */ { 3520,22,2,80,0,0x1C,0x08,0xCF,0x2e,"H1760" }, /* 24 1.76MB 3.5" */ { 3840,24,2,80,0,0x1C,0x20,0xCF,0x00,"H1920" }, /* 25 1.92MB 3.5" */ { 6400,40,2,80,0,0x25,0x5B,0xCF,0x00,"E3200" }, /* 26 3.20MB 3.5" */ { 7040,44,2,80,0,0x25,0x5B,0xCF,0x00,"E3520" }, /* 27 3.52MB 3.5" */ { 7680,48,2,80,0,0x25,0x63,0xCF,0x00,"E3840" }, /* 28 3.84MB 3.5" */ { 3680,23,2,80,0,0x1C,0x10,0xCF,0x00,"H1840" }, /* 29 1.84MB 3.5" */ { 1600,10,2,80,0,0x25,0x02,0xDF,0x2E,"D800" }, /* 30 800KB 3.5" */ { 3200,20,2,80,0,0x1C,0x00,0xCF,0x2C,"H1600" }, /* 31 1.6MB 3.5" */ }; #define SECTSIZE (_FD_SECTSIZE(*floppy)) /* Auto-detection: Disk type used until the next media change occurs. */ static struct floppy_struct *current_type[N_DRIVE]; /* * User-provided type information. current_type points to * the respective entry of this array. */ static struct floppy_struct user_params[N_DRIVE]; static sector_t floppy_sizes[256]; static char floppy_device_name[] = "floppy"; /* * The driver is trying to determine the correct media format * while probing is set. rw_interrupt() clears it after a * successful access. */ static int probing; /* Synchronization of FDC access. */ #define FD_COMMAND_NONE -1 #define FD_COMMAND_ERROR 2 #define FD_COMMAND_OKAY 3 static volatile int command_status = FD_COMMAND_NONE; static unsigned long fdc_busy; static DECLARE_WAIT_QUEUE_HEAD(fdc_wait); static DECLARE_WAIT_QUEUE_HEAD(command_done); /* Errors during formatting are counted here. */ static int format_errors; /* Format request descriptor. */ static struct format_descr format_req; /* * Rate is 0 for 500kb/s, 1 for 300kbps, 2 for 250kbps * Spec1 is 0xSH, where S is stepping rate (F=1ms, E=2ms, D=3ms etc), * H is head unload time (1=16ms, 2=32ms, etc) */ /* * Track buffer * Because these are written to by the DMA controller, they must * not contain a 64k byte boundary crossing, or data will be * corrupted/lost. */ static char *floppy_track_buffer; static int max_buffer_sectors; static int *errors; typedef void (*done_f)(int); static const struct cont_t { void (*interrupt)(void); /* this is called after the interrupt of the * main command */ void (*redo)(void); /* this is called to retry the operation */ void (*error)(void); /* this is called to tally an error */ done_f done; /* this is called to say if the operation has * succeeded/failed */ } *cont; static void floppy_ready(void); static void floppy_start(void); static void process_fd_request(void); static void recalibrate_floppy(void); static void floppy_shutdown(struct work_struct *); static int floppy_request_regions(int); static void floppy_release_regions(int); static int floppy_grab_irq_and_dma(void); static void floppy_release_irq_and_dma(void); /* * The "reset" variable should be tested whenever an interrupt is scheduled, * after the commands have been sent. This is to ensure that the driver doesn't * get wedged when the interrupt doesn't come because of a failed command. * reset doesn't need to be tested before sending commands, because * output_byte is automatically disabled when reset is set. */ static void reset_fdc(void); /* * These are global variables, as that's the easiest way to give * information to interrupts. They are the data used for the current * request. */ #define NO_TRACK -1 #define NEED_1_RECAL -2 #define NEED_2_RECAL -3 static atomic_t usage_count = ATOMIC_INIT(0); /* buffer related variables */ static int buffer_track = -1; static int buffer_drive = -1; static int buffer_min = -1; static int buffer_max = -1; /* fdc related variables, should end up in a struct */ static struct floppy_fdc_state fdc_state[N_FDC]; static int fdc; /* current fdc */ static struct workqueue_struct *floppy_wq; static struct floppy_struct *_floppy = floppy_type; static unsigned char current_drive; static long current_count_sectors; static unsigned char fsector_t; /* sector in track */ static unsigned char in_sector_offset; /* offset within physical sector, * expressed in units of 512 bytes */ static inline bool drive_no_geom(int drive) { return !current_type[drive] && !ITYPE(UDRS->fd_device); } #ifndef fd_eject static inline int fd_eject(int drive) { return -EINVAL; } #endif /* * Debugging * ========= */ #ifdef DEBUGT static long unsigned debugtimer; static inline void set_debugt(void) { debugtimer = jiffies; } static inline void debugt(const char *func, const char *msg) { if (DP->flags & DEBUGT) pr_info("%s:%s dtime=%lu\n", func, msg, jiffies - debugtimer); } #else static inline void set_debugt(void) { } static inline void debugt(const char *func, const char *msg) { } #endif /* DEBUGT */ static DECLARE_DELAYED_WORK(fd_timeout, floppy_shutdown); static const char *timeout_message; static void is_alive(const char *func, const char *message) { /* this routine checks whether the floppy driver is "alive" */ if (test_bit(0, &fdc_busy) && command_status < 2 && !delayed_work_pending(&fd_timeout)) { DPRINT("%s: timeout handler died. %s\n", func, message); } } static void (*do_floppy)(void) = NULL; #define OLOGSIZE 20 static void (*lasthandler)(void); static unsigned long interruptjiffies; static unsigned long resultjiffies; static int resultsize; static unsigned long lastredo; static struct output_log { unsigned char data; unsigned char status; unsigned long jiffies; } output_log[OLOGSIZE]; static int output_log_pos; #define current_reqD -1 #define MAXTIMEOUT -2 static void __reschedule_timeout(int drive, const char *message) { unsigned long delay; if (drive == current_reqD) drive = current_drive; if (drive < 0 || drive >= N_DRIVE) { delay = 20UL * HZ; drive = 0; } else delay = UDP->timeout; mod_delayed_work(floppy_wq, &fd_timeout, delay); if (UDP->flags & FD_DEBUG) DPRINT("reschedule timeout %s\n", message); timeout_message = message; } static void reschedule_timeout(int drive, const char *message) { unsigned long flags; spin_lock_irqsave(&floppy_lock, flags); __reschedule_timeout(drive, message); spin_unlock_irqrestore(&floppy_lock, flags); } #define INFBOUND(a, b) (a) = max_t(int, a, b) #define SUPBOUND(a, b) (a) = min_t(int, a, b) /* * Bottom half floppy driver. * ========================== * * This part of the file contains the code talking directly to the hardware, * and also the main service loop (seek-configure-spinup-command) */ /* * disk change. * This routine is responsible for maintaining the FD_DISK_CHANGE flag, * and the last_checked date. * * last_checked is the date of the last check which showed 'no disk change' * FD_DISK_CHANGE is set under two conditions: * 1. The floppy has been changed after some i/o to that floppy already * took place. * 2. No floppy disk is in the drive. This is done in order to ensure that * requests are quickly flushed in case there is no disk in the drive. It * follows that FD_DISK_CHANGE can only be cleared if there is a disk in * the drive. * * For 1., maxblock is observed. Maxblock is 0 if no i/o has taken place yet. * For 2., FD_DISK_NEWCHANGE is watched. FD_DISK_NEWCHANGE is cleared on * each seek. If a disk is present, the disk change line should also be * cleared on each seek. Thus, if FD_DISK_NEWCHANGE is clear, but the disk * change line is set, this means either that no disk is in the drive, or * that it has been removed since the last seek. * * This means that we really have a third possibility too: * The floppy has been changed after the last seek. */ static int disk_change(int drive) { int fdc = FDC(drive); if (time_before(jiffies, UDRS->select_date + UDP->select_delay)) DPRINT("WARNING disk change called early\n"); if (!(FDCS->dor & (0x10 << UNIT(drive))) || (FDCS->dor & 3) != UNIT(drive) || fdc != FDC(drive)) { DPRINT("probing disk change on unselected drive\n"); DPRINT("drive=%d fdc=%d dor=%x\n", drive, FDC(drive), (unsigned int)FDCS->dor); } debug_dcl(UDP->flags, "checking disk change line for drive %d\n", drive); debug_dcl(UDP->flags, "jiffies=%lu\n", jiffies); debug_dcl(UDP->flags, "disk change line=%x\n", fd_inb(FD_DIR) & 0x80); debug_dcl(UDP->flags, "flags=%lx\n", UDRS->flags); if (UDP->flags & FD_BROKEN_DCL) return test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if ((fd_inb(FD_DIR) ^ UDP->flags) & 0x80) { set_bit(FD_VERIFY_BIT, &UDRS->flags); /* verify write protection */ if (UDRS->maxblock) /* mark it changed */ set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); /* invalidate its geometry */ if (UDRS->keep_data >= 0) { if ((UDP->flags & FTD_MSG) && current_type[drive] != NULL) DPRINT("Disk type is undefined after disk change\n"); current_type[drive] = NULL; floppy_sizes[TOMINOR(drive)] = MAX_DISK_SIZE << 1; } return 1; } else { UDRS->last_checked = jiffies; clear_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); } return 0; } static inline int is_selected(int dor, int unit) { return ((dor & (0x10 << unit)) && (dor & 3) == unit); } static bool is_ready_state(int status) { int state = status & (STATUS_READY | STATUS_DIR | STATUS_DMA); return state == STATUS_READY; } static int set_dor(int fdc, char mask, char data) { unsigned char unit; unsigned char drive; unsigned char newdor; unsigned char olddor; if (FDCS->address == -1) return -1; olddor = FDCS->dor; newdor = (olddor & mask) | data; if (newdor != olddor) { unit = olddor & 0x3; if (is_selected(olddor, unit) && !is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); debug_dcl(UDP->flags, "calling disk change from set_dor\n"); disk_change(drive); } FDCS->dor = newdor; fd_outb(newdor, FD_DOR); unit = newdor & 0x3; if (!is_selected(olddor, unit) && is_selected(newdor, unit)) { drive = REVDRIVE(fdc, unit); UDRS->select_date = jiffies; } } return olddor; } static void twaddle(void) { if (DP->select_delay) return; fd_outb(FDCS->dor & ~(0x10 << UNIT(current_drive)), FD_DOR); fd_outb(FDCS->dor, FD_DOR); DRS->select_date = jiffies; } /* * Reset all driver information about the current fdc. * This is needed after a reset, and after a raw command. */ static void reset_fdc_info(int mode) { int drive; FDCS->spec1 = FDCS->spec2 = -1; FDCS->need_configure = 1; FDCS->perp_mode = 1; FDCS->rawcmd = 0; for (drive = 0; drive < N_DRIVE; drive++) if (FDC(drive) == fdc && (mode || UDRS->track != NEED_1_RECAL)) UDRS->track = NEED_2_RECAL; } /* selects the fdc and drive, and enables the fdc's input/dma. */ static void set_fdc(int drive) { if (drive >= 0 && drive < N_DRIVE) { fdc = FDC(drive); current_drive = drive; } if (fdc != 1 && fdc != 0) { pr_info("bad fdc value\n"); return; } set_dor(fdc, ~0, 8); #if N_FDC > 1 set_dor(1 - fdc, ~8, 0); #endif if (FDCS->rawcmd == 2) reset_fdc_info(1); if (fd_inb(FD_STATUS) != STATUS_READY) FDCS->reset = 1; } /* locks the driver */ static int lock_fdc(int drive) { if (WARN(atomic_read(&usage_count) == 0, "Trying to lock fdc while usage count=0\n")) return -1; if (wait_event_interruptible(fdc_wait, !test_and_set_bit(0, &fdc_busy))) return -EINTR; command_status = FD_COMMAND_NONE; reschedule_timeout(drive, "lock fdc"); set_fdc(drive); return 0; } /* unlocks the driver */ static void unlock_fdc(void) { if (!test_bit(0, &fdc_busy)) DPRINT("FDC access conflict!\n"); raw_cmd = NULL; command_status = FD_COMMAND_NONE; cancel_delayed_work(&fd_timeout); do_floppy = NULL; cont = NULL; clear_bit(0, &fdc_busy); wake_up(&fdc_wait); } /* switches the motor off after a given timeout */ static void motor_off_callback(struct timer_list *t) { unsigned long nr = t - motor_off_timer; unsigned char mask = ~(0x10 << UNIT(nr)); if (WARN_ON_ONCE(nr >= N_DRIVE)) return; set_dor(FDC(nr), mask, 0); } /* schedules motor off */ static void floppy_off(unsigned int drive) { unsigned long volatile delta; int fdc = FDC(drive); if (!(FDCS->dor & (0x10 << UNIT(drive)))) return; del_timer(motor_off_timer + drive); /* make spindle stop in a position which minimizes spinup time * next time */ if (UDP->rps) { delta = jiffies - UDRS->first_read_date + HZ - UDP->spindown_offset; delta = ((delta * UDP->rps) % HZ) / UDP->rps; motor_off_timer[drive].expires = jiffies + UDP->spindown - delta; } add_timer(motor_off_timer + drive); } /* * cycle through all N_DRIVE floppy drives, for disk change testing. * stopping at current drive. This is done before any long operation, to * be sure to have up to date disk change information. */ static void scandrives(void) { int i; int drive; int saved_drive; if (DP->select_delay) return; saved_drive = current_drive; for (i = 0; i < N_DRIVE; i++) { drive = (saved_drive + i + 1) % N_DRIVE; if (UDRS->fd_ref == 0 || UDP->select_delay != 0) continue; /* skip closed drives */ set_fdc(drive); if (!(set_dor(fdc, ~3, UNIT(drive) | (0x10 << UNIT(drive))) & (0x10 << UNIT(drive)))) /* switch the motor off again, if it was off to * begin with */ set_dor(fdc, ~(0x10 << UNIT(drive)), 0); } set_fdc(saved_drive); } static void empty(void) { } static void (*floppy_work_fn)(void); static void floppy_work_workfn(struct work_struct *work) { floppy_work_fn(); } static DECLARE_WORK(floppy_work, floppy_work_workfn); static void schedule_bh(void (*handler)(void)) { WARN_ON(work_pending(&floppy_work)); floppy_work_fn = handler; queue_work(floppy_wq, &floppy_work); } static void (*fd_timer_fn)(void) = NULL; static void fd_timer_workfn(struct work_struct *work) { fd_timer_fn(); } static DECLARE_DELAYED_WORK(fd_timer, fd_timer_workfn); static void cancel_activity(void) { do_floppy = NULL; cancel_delayed_work_sync(&fd_timer); cancel_work_sync(&floppy_work); } /* this function makes sure that the disk stays in the drive during the * transfer */ static void fd_watchdog(void) { debug_dcl(DP->flags, "calling disk change from watchdog\n"); if (disk_change(current_drive)) { DPRINT("disk removed during i/o\n"); cancel_activity(); cont->done(0); reset_fdc(); } else { cancel_delayed_work(&fd_timer); fd_timer_fn = fd_watchdog; queue_delayed_work(floppy_wq, &fd_timer, HZ / 10); } } static void main_command_interrupt(void) { cancel_delayed_work(&fd_timer); cont->interrupt(); } /* waits for a delay (spinup or select) to pass */ static int fd_wait_for_completion(unsigned long expires, void (*function)(void)) { if (FDCS->reset) { reset_fdc(); /* do the reset during sleep to win time * if we don't need to sleep, it's a good * occasion anyways */ return 1; } if (time_before(jiffies, expires)) { cancel_delayed_work(&fd_timer); fd_timer_fn = function; queue_delayed_work(floppy_wq, &fd_timer, expires - jiffies); return 1; } return 0; } static void setup_DMA(void) { unsigned long f; if (raw_cmd->length == 0) { int i; pr_info("zero dma transfer size:"); for (i = 0; i < raw_cmd->cmd_count; i++) pr_cont("%x,", raw_cmd->cmd[i]); pr_cont("\n"); cont->done(0); FDCS->reset = 1; return; } if (((unsigned long)raw_cmd->kernel_data) % 512) { pr_info("non aligned address: %p\n", raw_cmd->kernel_data); cont->done(0); FDCS->reset = 1; return; } f = claim_dma_lock(); fd_disable_dma(); #ifdef fd_dma_setup if (fd_dma_setup(raw_cmd->kernel_data, raw_cmd->length, (raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE, FDCS->address) < 0) { release_dma_lock(f); cont->done(0); FDCS->reset = 1; return; } release_dma_lock(f); #else fd_clear_dma_ff(); fd_cacheflush(raw_cmd->kernel_data, raw_cmd->length); fd_set_dma_mode((raw_cmd->flags & FD_RAW_READ) ? DMA_MODE_READ : DMA_MODE_WRITE); fd_set_dma_addr(raw_cmd->kernel_data); fd_set_dma_count(raw_cmd->length); virtual_dma_port = FDCS->address; fd_enable_dma(); release_dma_lock(f); #endif } static void show_floppy(void); /* waits until the fdc becomes ready */ static int wait_til_ready(void) { int status; int counter; if (FDCS->reset) return -1; for (counter = 0; counter < 10000; counter++) { status = fd_inb(FD_STATUS); if (status & STATUS_READY) return status; } if (initialized) { DPRINT("Getstatus times out (%x) on fdc %d\n", status, fdc); show_floppy(); } FDCS->reset = 1; return -1; } /* sends a command byte to the fdc */ static int output_byte(char byte) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) { fd_outb(byte, FD_DATA); output_log[output_log_pos].data = byte; output_log[output_log_pos].status = status; output_log[output_log_pos].jiffies = jiffies; output_log_pos = (output_log_pos + 1) % OLOGSIZE; return 0; } FDCS->reset = 1; if (initialized) { DPRINT("Unable to send byte %x to FDC. Fdc=%x Status=%x\n", byte, fdc, status); show_floppy(); } return -1; } /* gets the response from the fdc */ static int result(void) { int i; int status = 0; for (i = 0; i < MAX_REPLIES; i++) { status = wait_til_ready(); if (status < 0) break; status &= STATUS_DIR | STATUS_READY | STATUS_BUSY | STATUS_DMA; if ((status & ~STATUS_BUSY) == STATUS_READY) { resultjiffies = jiffies; resultsize = i; return i; } if (status == (STATUS_DIR | STATUS_READY | STATUS_BUSY)) reply_buffer[i] = fd_inb(FD_DATA); else break; } if (initialized) { DPRINT("get result error. Fdc=%d Last status=%x Read bytes=%d\n", fdc, status, i); show_floppy(); } FDCS->reset = 1; return -1; } #define MORE_OUTPUT -2 /* does the fdc need more output? */ static int need_more_output(void) { int status = wait_til_ready(); if (status < 0) return -1; if (is_ready_state(status)) return MORE_OUTPUT; return result(); } /* Set perpendicular mode as required, based on data rate, if supported. * 82077 Now tested. 1Mbps data rate only possible with 82077-1. */ static void perpendicular_mode(void) { unsigned char perp_mode; if (raw_cmd->rate & 0x40) { switch (raw_cmd->rate & 3) { case 0: perp_mode = 2; break; case 3: perp_mode = 3; break; default: DPRINT("Invalid data rate for perpendicular mode!\n"); cont->done(0); FDCS->reset = 1; /* * convenient way to return to * redo without too much hassle * (deep stack et al.) */ return; } } else perp_mode = 0; if (FDCS->perp_mode == perp_mode) return; if (FDCS->version >= FDC_82077_ORIG) { output_byte(FD_PERPENDICULAR); output_byte(perp_mode); FDCS->perp_mode = perp_mode; } else if (perp_mode) { DPRINT("perpendicular mode not supported by this FDC.\n"); } } /* perpendicular_mode */ static int fifo_depth = 0xa; static int no_fifo; static int fdc_configure(void) { /* Turn on FIFO */ output_byte(FD_CONFIGURE); if (need_more_output() != MORE_OUTPUT) return 0; output_byte(0); output_byte(0x10 | (no_fifo & 0x20) | (fifo_depth & 0xf)); output_byte(0); /* pre-compensation from track 0 upwards */ return 1; } #define NOMINAL_DTR 500 /* Issue a "SPECIFY" command to set the step rate time, head unload time, * head load time, and DMA disable flag to values needed by floppy. * * The value "dtr" is the data transfer rate in Kbps. It is needed * to account for the data rate-based scaling done by the 82072 and 82077 * FDC types. This parameter is ignored for other types of FDCs (i.e. * 8272a). * * Note that changing the data transfer rate has a (probably deleterious) * effect on the parameters subject to scaling for 82072/82077 FDCs, so * fdc_specify is called again after each data transfer rate * change. * * srt: 1000 to 16000 in microseconds * hut: 16 to 240 milliseconds * hlt: 2 to 254 milliseconds * * These values are rounded up to the next highest available delay time. */ static void fdc_specify(void) { unsigned char spec1; unsigned char spec2; unsigned long srt; unsigned long hlt; unsigned long hut; unsigned long dtr = NOMINAL_DTR; unsigned long scale_dtr = NOMINAL_DTR; int hlt_max_code = 0x7f; int hut_max_code = 0xf; if (FDCS->need_configure && FDCS->version >= FDC_82072A) { fdc_configure(); FDCS->need_configure = 0; } switch (raw_cmd->rate & 0x03) { case 3: dtr = 1000; break; case 1: dtr = 300; if (FDCS->version >= FDC_82078) { /* chose the default rate table, not the one * where 1 = 2 Mbps */ output_byte(FD_DRIVESPEC); if (need_more_output() == MORE_OUTPUT) { output_byte(UNIT(current_drive)); output_byte(0xc0); } } break; case 2: dtr = 250; break; } if (FDCS->version >= FDC_82072) { scale_dtr = dtr; hlt_max_code = 0x00; /* 0==256msec*dtr0/dtr (not linear!) */ hut_max_code = 0x0; /* 0==256msec*dtr0/dtr (not linear!) */ } /* Convert step rate from microseconds to milliseconds and 4 bits */ srt = 16 - DIV_ROUND_UP(DP->srt * scale_dtr / 1000, NOMINAL_DTR); if (slow_floppy) srt = srt / 4; SUPBOUND(srt, 0xf); INFBOUND(srt, 0); hlt = DIV_ROUND_UP(DP->hlt * scale_dtr / 2, NOMINAL_DTR); if (hlt < 0x01) hlt = 0x01; else if (hlt > 0x7f) hlt = hlt_max_code; hut = DIV_ROUND_UP(DP->hut * scale_dtr / 16, NOMINAL_DTR); if (hut < 0x1) hut = 0x1; else if (hut > 0xf) hut = hut_max_code; spec1 = (srt << 4) | hut; spec2 = (hlt << 1) | (use_virtual_dma & 1); /* If these parameters did not change, just return with success */ if (FDCS->spec1 != spec1 || FDCS->spec2 != spec2) { /* Go ahead and set spec1 and spec2 */ output_byte(FD_SPECIFY); output_byte(FDCS->spec1 = spec1); output_byte(FDCS->spec2 = spec2); } } /* fdc_specify */ /* Set the FDC's data transfer rate on behalf of the specified drive. * NOTE: with 82072/82077 FDCs, changing the data rate requires a reissue * of the specify command (i.e. using the fdc_specify function). */ static int fdc_dtr(void) { /* If data rate not already set to desired value, set it. */ if ((raw_cmd->rate & 3) == FDCS->dtr) return 0; /* Set dtr */ fd_outb(raw_cmd->rate & 3, FD_DCR); /* TODO: some FDC/drive combinations (C&T 82C711 with TEAC 1.2MB) * need a stabilization period of several milliseconds to be * enforced after data rate changes before R/W operations. * Pause 5 msec to avoid trouble. (Needs to be 2 jiffies) */ FDCS->dtr = raw_cmd->rate & 3; return fd_wait_for_completion(jiffies + 2UL * HZ / 100, floppy_ready); } /* fdc_dtr */ static void tell_sector(void) { pr_cont(": track %d, head %d, sector %d, size %d", R_TRACK, R_HEAD, R_SECTOR, R_SIZECODE); } /* tell_sector */ static void print_errors(void) { DPRINT(""); if (ST0 & ST0_ECE) { pr_cont("Recalibrate failed!"); } else if (ST2 & ST2_CRC) { pr_cont("data CRC error"); tell_sector(); } else if (ST1 & ST1_CRC) { pr_cont("CRC error"); tell_sector(); } else if ((ST1 & (ST1_MAM | ST1_ND)) || (ST2 & ST2_MAM)) { if (!probing) { pr_cont("sector not found"); tell_sector(); } else pr_cont("probe failed..."); } else if (ST2 & ST2_WC) { /* seek error */ pr_cont("wrong cylinder"); } else if (ST2 & ST2_BC) { /* cylinder marked as bad */ pr_cont("bad cylinder"); } else { pr_cont("unknown error. ST[0..2] are: 0x%x 0x%x 0x%x", ST0, ST1, ST2); tell_sector(); } pr_cont("\n"); } /* * OK, this error interpreting routine is called after a * DMA read/write has succeeded * or failed, so we check the results, and copy any buffers. * hhb: Added better error reporting. * ak: Made this into a separate routine. */ static int interpret_errors(void) { char bad; if (inr != 7) { DPRINT("-- FDC reply error\n"); FDCS->reset = 1; return 1; } /* check IC to find cause of interrupt */ switch (ST0 & ST0_INTR) { case 0x40: /* error occurred during command execution */ if (ST1 & ST1_EOC) return 0; /* occurs with pseudo-DMA */ bad = 1; if (ST1 & ST1_WP) { DPRINT("Drive is write protected\n"); clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); cont->done(0); bad = 2; } else if (ST1 & ST1_ND) { set_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); } else if (ST1 & ST1_OR) { if (DP->flags & FTD_MSG) DPRINT("Over/Underrun - retrying\n"); bad = 0; } else if (*errors >= DP->max_errors.reporting) { print_errors(); } if (ST2 & ST2_WC || ST2 & ST2_BC) /* wrong cylinder => recal */ DRS->track = NEED_2_RECAL; return bad; case 0x80: /* invalid command given */ DPRINT("Invalid FDC command given!\n"); cont->done(0); return 2; case 0xc0: DPRINT("Abnormal termination caused by polling\n"); cont->error(); return 2; default: /* (0) Normal command termination */ return 0; } } /* * This routine is called when everything should be correctly set up * for the transfer (i.e. floppy motor is on, the correct floppy is * selected, and the head is sitting on the right track). */ static void setup_rw_floppy(void) { int i; int r; int flags; unsigned long ready_date; void (*function)(void); flags = raw_cmd->flags; if (flags & (FD_RAW_READ | FD_RAW_WRITE)) flags |= FD_RAW_INTR; if ((flags & FD_RAW_SPIN) && !(flags & FD_RAW_NO_MOTOR)) { ready_date = DRS->spinup_date + DP->spinup; /* If spinup will take a long time, rerun scandrives * again just before spinup completion. Beware that * after scandrives, we must again wait for selection. */ if (time_after(ready_date, jiffies + DP->select_delay)) { ready_date -= DP->select_delay; function = floppy_start; } else function = setup_rw_floppy; /* wait until the floppy is spinning fast enough */ if (fd_wait_for_completion(ready_date, function)) return; } if ((flags & FD_RAW_READ) || (flags & FD_RAW_WRITE)) setup_DMA(); if (flags & FD_RAW_INTR) do_floppy = main_command_interrupt; r = 0; for (i = 0; i < raw_cmd->cmd_count; i++) r |= output_byte(raw_cmd->cmd[i]); debugt(__func__, "rw_command"); if (r) { cont->error(); reset_fdc(); return; } if (!(flags & FD_RAW_INTR)) { inr = result(); cont->interrupt(); } else if (flags & FD_RAW_NEED_DISK) fd_watchdog(); } static int blind_seek; /* * This is the routine called after every seek (or recalibrate) interrupt * from the floppy controller. */ static void seek_interrupt(void) { debugt(__func__, ""); if (inr != 2 || (ST0 & 0xF8) != 0x20) { DPRINT("seek failed\n"); DRS->track = NEED_2_RECAL; cont->error(); cont->redo(); return; } if (DRS->track >= 0 && DRS->track != ST1 && !blind_seek) { debug_dcl(DP->flags, "clearing NEWCHANGE flag because of effective seek\n"); debug_dcl(DP->flags, "jiffies=%lu\n", jiffies); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); /* effective seek */ DRS->select_date = jiffies; } DRS->track = ST1; floppy_ready(); } static void check_wp(void) { if (test_bit(FD_VERIFY_BIT, &DRS->flags)) { /* check write protection */ output_byte(FD_GETSTATUS); output_byte(UNIT(current_drive)); if (result() != 1) { FDCS->reset = 1; return; } clear_bit(FD_VERIFY_BIT, &DRS->flags); clear_bit(FD_NEED_TWADDLE_BIT, &DRS->flags); debug_dcl(DP->flags, "checking whether disk is write protected\n"); debug_dcl(DP->flags, "wp=%x\n", ST3 & 0x40); if (!(ST3 & 0x40)) set_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); else clear_bit(FD_DISK_WRITABLE_BIT, &DRS->flags); } } static void seek_floppy(void) { int track; blind_seek = 0; debug_dcl(DP->flags, "calling disk change from %s\n", __func__); if (!test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && disk_change(current_drive) && (raw_cmd->flags & FD_RAW_NEED_DISK)) { /* the media changed flag should be cleared after the seek. * If it isn't, this means that there is really no disk in * the drive. */ set_bit(FD_DISK_CHANGED_BIT, &DRS->flags); cont->done(0); cont->redo(); return; } if (DRS->track <= NEED_1_RECAL) { recalibrate_floppy(); return; } else if (test_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags) && (raw_cmd->flags & FD_RAW_NEED_DISK) && (DRS->track <= NO_TRACK || DRS->track == raw_cmd->track)) { /* we seek to clear the media-changed condition. Does anybody * know a more elegant way, which works on all drives? */ if (raw_cmd->track) track = raw_cmd->track - 1; else { if (DP->flags & FD_SILENT_DCL_CLEAR) { set_dor(fdc, ~(0x10 << UNIT(current_drive)), 0); blind_seek = 1; raw_cmd->flags |= FD_RAW_NEED_SEEK; } track = 1; } } else { check_wp(); if (raw_cmd->track != DRS->track && (raw_cmd->flags & FD_RAW_NEED_SEEK)) track = raw_cmd->track; else { setup_rw_floppy(); return; } } do_floppy = seek_interrupt; output_byte(FD_SEEK); output_byte(UNIT(current_drive)); if (output_byte(track) < 0) { reset_fdc(); return; } debugt(__func__, ""); } static void recal_interrupt(void) { debugt(__func__, ""); if (inr != 2) FDCS->reset = 1; else if (ST0 & ST0_ECE) { switch (DRS->track) { case NEED_1_RECAL: debugt(__func__, "need 1 recal"); /* after a second recalibrate, we still haven't * reached track 0. Probably no drive. Raise an * error, as failing immediately might upset * computers possessed by the Devil :-) */ cont->error(); cont->redo(); return; case NEED_2_RECAL: debugt(__func__, "need 2 recal"); /* If we already did a recalibrate, * and we are not at track 0, this * means we have moved. (The only way * not to move at recalibration is to * be already at track 0.) Clear the * new change flag */ debug_dcl(DP->flags, "clearing NEWCHANGE flag because of second recalibrate\n"); clear_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); DRS->select_date = jiffies; /* fall through */ default: debugt(__func__, "default"); /* Recalibrate moves the head by at * most 80 steps. If after one * recalibrate we don't have reached * track 0, this might mean that we * started beyond track 80. Try * again. */ DRS->track = NEED_1_RECAL; break; } } else DRS->track = ST1; floppy_ready(); } static void print_result(char *message, int inr) { int i; DPRINT("%s ", message); if (inr >= 0) for (i = 0; i < inr; i++) pr_cont("repl[%d]=%x ", i, reply_buffer[i]); pr_cont("\n"); } /* interrupt handler. Note that this can be called externally on the Sparc */ irqreturn_t floppy_interrupt(int irq, void *dev_id) { int do_print; unsigned long f; void (*handler)(void) = do_floppy; lasthandler = handler; interruptjiffies = jiffies; f = claim_dma_lock(); fd_disable_dma(); release_dma_lock(f); do_floppy = NULL; if (fdc >= N_FDC || FDCS->address == -1) { /* we don't even know which FDC is the culprit */ pr_info("DOR0=%x\n", fdc_state[0].dor); pr_info("floppy interrupt on bizarre fdc %d\n", fdc); pr_info("handler=%ps\n", handler); is_alive(__func__, "bizarre fdc"); return IRQ_NONE; } FDCS->reset = 0; /* We have to clear the reset flag here, because apparently on boxes * with level triggered interrupts (PS/2, Sparc, ...), it is needed to * emit SENSEI's to clear the interrupt line. And FDCS->reset blocks the * emission of the SENSEI's. * It is OK to emit floppy commands because we are in an interrupt * handler here, and thus we have to fear no interference of other * activity. */ do_print = !handler && print_unex && initialized; inr = result(); if (do_print) print_result("unexpected interrupt", inr); if (inr == 0) { int max_sensei = 4; do { output_byte(FD_SENSEI); inr = result(); if (do_print) print_result("sensei", inr); max_sensei--; } while ((ST0 & 0x83) != UNIT(current_drive) && inr == 2 && max_sensei); } if (!handler) { FDCS->reset = 1; return IRQ_NONE; } schedule_bh(handler); is_alive(__func__, "normal interrupt end"); /* FIXME! Was it really for us? */ return IRQ_HANDLED; } static void recalibrate_floppy(void) { debugt(__func__, ""); do_floppy = recal_interrupt; output_byte(FD_RECALIBRATE); if (output_byte(UNIT(current_drive)) < 0) reset_fdc(); } /* * Must do 4 FD_SENSEIs after reset because of ``drive polling''. */ static void reset_interrupt(void) { debugt(__func__, ""); result(); /* get the status ready for set_fdc */ if (FDCS->reset) { pr_info("reset set in interrupt, calling %ps\n", cont->error); cont->error(); /* a reset just after a reset. BAD! */ } cont->redo(); } /* * reset is done by pulling bit 2 of DOR low for a while (old FDCs), * or by setting the self clearing bit 7 of STATUS (newer FDCs) */ static void reset_fdc(void) { unsigned long flags; do_floppy = reset_interrupt; FDCS->reset = 0; reset_fdc_info(0); /* Pseudo-DMA may intercept 'reset finished' interrupt. */ /* Irrelevant for systems with true DMA (i386). */ flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); if (FDCS->version >= FDC_82072A) fd_outb(0x80 | (FDCS->dtr & 3), FD_STATUS); else { fd_outb(FDCS->dor & ~0x04, FD_DOR); udelay(FD_RESET_DELAY); fd_outb(FDCS->dor, FD_DOR); } } static void show_floppy(void) { int i; pr_info("\n"); pr_info("floppy driver state\n"); pr_info("-------------------\n"); pr_info("now=%lu last interrupt=%lu diff=%lu last called handler=%ps\n", jiffies, interruptjiffies, jiffies - interruptjiffies, lasthandler); pr_info("timeout_message=%s\n", timeout_message); pr_info("last output bytes:\n"); for (i = 0; i < OLOGSIZE; i++) pr_info("%2x %2x %lu\n", output_log[(i + output_log_pos) % OLOGSIZE].data, output_log[(i + output_log_pos) % OLOGSIZE].status, output_log[(i + output_log_pos) % OLOGSIZE].jiffies); pr_info("last result at %lu\n", resultjiffies); pr_info("last redo_fd_request at %lu\n", lastredo); print_hex_dump(KERN_INFO, "", DUMP_PREFIX_NONE, 16, 1, reply_buffer, resultsize, true); pr_info("status=%x\n", fd_inb(FD_STATUS)); pr_info("fdc_busy=%lu\n", fdc_busy); if (do_floppy) pr_info("do_floppy=%ps\n", do_floppy); if (work_pending(&floppy_work)) pr_info("floppy_work.func=%ps\n", floppy_work.func); if (delayed_work_pending(&fd_timer)) pr_info("delayed work.function=%p expires=%ld\n", fd_timer.work.func, fd_timer.timer.expires - jiffies); if (delayed_work_pending(&fd_timeout)) pr_info("timer_function=%p expires=%ld\n", fd_timeout.work.func, fd_timeout.timer.expires - jiffies); pr_info("cont=%p\n", cont); pr_info("current_req=%p\n", current_req); pr_info("command_status=%d\n", command_status); pr_info("\n"); } static void floppy_shutdown(struct work_struct *arg) { unsigned long flags; if (initialized) show_floppy(); cancel_activity(); flags = claim_dma_lock(); fd_disable_dma(); release_dma_lock(flags); /* avoid dma going to a random drive after shutdown */ if (initialized) DPRINT("floppy timeout called\n"); FDCS->reset = 1; if (cont) { cont->done(0); cont->redo(); /* this will recall reset when needed */ } else { pr_info("no cont in shutdown!\n"); process_fd_request(); } is_alive(__func__, ""); } /* start motor, check media-changed condition and write protection */ static int start_motor(void (*function)(void)) { int mask; int data; mask = 0xfc; data = UNIT(current_drive); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR)) { if (!(FDCS->dor & (0x10 << UNIT(current_drive)))) { set_debugt(); /* no read since this drive is running */ DRS->first_read_date = 0; /* note motor start time if motor is not yet running */ DRS->spinup_date = jiffies; data |= (0x10 << UNIT(current_drive)); } } else if (FDCS->dor & (0x10 << UNIT(current_drive))) mask &= ~(0x10 << UNIT(current_drive)); /* starts motor and selects floppy */ del_timer(motor_off_timer + current_drive); set_dor(fdc, mask, data); /* wait_for_completion also schedules reset if needed. */ return fd_wait_for_completion(DRS->select_date + DP->select_delay, function); } static void floppy_ready(void) { if (FDCS->reset) { reset_fdc(); return; } if (start_motor(floppy_ready)) return; if (fdc_dtr()) return; debug_dcl(DP->flags, "calling disk change from floppy_ready\n"); if (!(raw_cmd->flags & FD_RAW_NO_MOTOR) && disk_change(current_drive) && !DP->select_delay) twaddle(); /* this clears the dcl on certain * drive/controller combinations */ #ifdef fd_chose_dma_mode if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) { unsigned long flags = claim_dma_lock(); fd_chose_dma_mode(raw_cmd->kernel_data, raw_cmd->length); release_dma_lock(flags); } #endif if (raw_cmd->flags & (FD_RAW_NEED_SEEK | FD_RAW_NEED_DISK)) { perpendicular_mode(); fdc_specify(); /* must be done here because of hut, hlt ... */ seek_floppy(); } else { if ((raw_cmd->flags & FD_RAW_READ) || (raw_cmd->flags & FD_RAW_WRITE)) fdc_specify(); setup_rw_floppy(); } } static void floppy_start(void) { reschedule_timeout(current_reqD, "floppy start"); scandrives(); debug_dcl(DP->flags, "setting NEWCHANGE in floppy_start\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); floppy_ready(); } /* * ======================================================================== * here ends the bottom half. Exported routines are: * floppy_start, floppy_off, floppy_ready, lock_fdc, unlock_fdc, set_fdc, * start_motor, reset_fdc, reset_fdc_info, interpret_errors. * Initialization also uses output_byte, result, set_dor, floppy_interrupt * and set_dor. * ======================================================================== */ /* * General purpose continuations. * ============================== */ static void do_wakeup(void) { reschedule_timeout(MAXTIMEOUT, "do wakeup"); cont = NULL; command_status += 2; wake_up(&command_done); } static const struct cont_t wakeup_cont = { .interrupt = empty, .redo = do_wakeup, .error = empty, .done = (done_f)empty }; static const struct cont_t intr_cont = { .interrupt = empty, .redo = process_fd_request, .error = empty, .done = (done_f)empty }; static int wait_til_done(void (*handler)(void), bool interruptible) { int ret; schedule_bh(handler); if (interruptible) wait_event_interruptible(command_done, command_status >= 2); else wait_event(command_done, command_status >= 2); if (command_status < 2) { cancel_activity(); cont = &intr_cont; reset_fdc(); return -EINTR; } if (FDCS->reset) command_status = FD_COMMAND_ERROR; if (command_status == FD_COMMAND_OKAY) ret = 0; else ret = -EIO; command_status = FD_COMMAND_NONE; return ret; } static void generic_done(int result) { command_status = result; cont = &wakeup_cont; } static void generic_success(void) { cont->done(1); } static void generic_failure(void) { cont->done(0); } static void success_and_wakeup(void) { generic_success(); cont->redo(); } /* * formatting and rw support. * ========================== */ static int next_valid_format(void) { int probed_format; probed_format = DRS->probed_format; while (1) { if (probed_format >= 8 || !DP->autodetect[probed_format]) { DRS->probed_format = 0; return 1; } if (floppy_type[DP->autodetect[probed_format]].sect) { DRS->probed_format = probed_format; return 0; } probed_format++; } } static void bad_flp_intr(void) { int err_count; if (probing) { DRS->probed_format++; if (!next_valid_format()) return; } err_count = ++(*errors); INFBOUND(DRWE->badness, err_count); if (err_count > DP->max_errors.abort) cont->done(0); if (err_count > DP->max_errors.reset) FDCS->reset = 1; else if (err_count > DP->max_errors.recal) DRS->track = NEED_2_RECAL; } static void set_floppy(int drive) { int type = ITYPE(UDRS->fd_device); if (type) _floppy = floppy_type + type; else _floppy = current_type[drive]; } /* * formatting support. * =================== */ static void format_interrupt(void) { switch (interpret_errors()) { case 1: cont->error(); case 2: break; case 0: cont->done(1); } cont->redo(); } #define FM_MODE(x, y) ((y) & ~(((x)->rate & 0x80) >> 1)) #define CT(x) ((x) | 0xc0) static void setup_format_params(int track) { int n; int il; int count; int head_shift; int track_shift; struct fparm { unsigned char track, head, sect, size; } *here = (struct fparm *)floppy_track_buffer; raw_cmd = &default_raw_cmd; raw_cmd->track = track; raw_cmd->flags = (FD_RAW_WRITE | FD_RAW_INTR | FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK); raw_cmd->rate = _floppy->rate & 0x43; raw_cmd->cmd_count = NR_F; COMMAND = FM_MODE(_floppy, FD_FORMAT); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, format_req.head); F_SIZECODE = FD_SIZECODE(_floppy); F_SECT_PER_TRACK = _floppy->sect << 2 >> F_SIZECODE; F_GAP = _floppy->fmt_gap; F_FILL = FD_FILL_BYTE; raw_cmd->kernel_data = floppy_track_buffer; raw_cmd->length = 4 * F_SECT_PER_TRACK; if (!F_SECT_PER_TRACK) return; /* allow for about 30ms for data transport per track */ head_shift = (F_SECT_PER_TRACK + 5) / 6; /* a ``cylinder'' is two tracks plus a little stepping time */ track_shift = 2 * head_shift + 3; /* position of logical sector 1 on this track */ n = (track_shift * format_req.track + head_shift * format_req.head) % F_SECT_PER_TRACK; /* determine interleave */ il = 1; if (_floppy->fmt_gap < 0x22) il++; /* initialize field */ for (count = 0; count < F_SECT_PER_TRACK; ++count) { here[count].track = format_req.track; here[count].head = format_req.head; here[count].sect = 0; here[count].size = F_SIZECODE; } /* place logical sectors */ for (count = 1; count <= F_SECT_PER_TRACK; ++count) { here[n].sect = count; n = (n + il) % F_SECT_PER_TRACK; if (here[n].sect) { /* sector busy, find next free sector */ ++n; if (n >= F_SECT_PER_TRACK) { n -= F_SECT_PER_TRACK; while (here[n].sect) ++n; } } } if (_floppy->stretch & FD_SECTBASEMASK) { for (count = 0; count < F_SECT_PER_TRACK; count++) here[count].sect += FD_SECTBASE(_floppy) - 1; } } static void redo_format(void) { buffer_track = -1; setup_format_params(format_req.track << STRETCH(_floppy)); floppy_start(); debugt(__func__, "queue format request"); } static const struct cont_t format_cont = { .interrupt = format_interrupt, .redo = redo_format, .error = bad_flp_intr, .done = generic_done }; static int do_format(int drive, struct format_descr *tmp_format_req) { int ret; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); if (!_floppy || _floppy->track > DP->tracks || tmp_format_req->track >= _floppy->track || tmp_format_req->head >= _floppy->head || (_floppy->sect << 2) % (1 << FD_SIZECODE(_floppy)) || !_floppy->fmt_gap) { process_fd_request(); return -EINVAL; } format_req = *tmp_format_req; format_errors = 0; cont = &format_cont; errors = &format_errors; ret = wait_til_done(redo_format, true); if (ret == -EINTR) return -EINTR; process_fd_request(); return ret; } /* * Buffer read/write and support * ============================= */ static void floppy_end_request(struct request *req, blk_status_t error) { unsigned int nr_sectors = current_count_sectors; unsigned int drive = (unsigned long)req->rq_disk->private_data; /* current_count_sectors can be zero if transfer failed */ if (error) nr_sectors = blk_rq_cur_sectors(req); if (blk_update_request(req, error, nr_sectors << 9)) return; __blk_mq_end_request(req, error); /* We're done with the request */ floppy_off(drive); current_req = NULL; } /* new request_done. Can handle physical sectors which are smaller than a * logical buffer */ static void request_done(int uptodate) { struct request *req = current_req; int block; char msg[sizeof("request done ") + sizeof(int) * 3]; probing = 0; snprintf(msg, sizeof(msg), "request done %d", uptodate); reschedule_timeout(MAXTIMEOUT, msg); if (!req) { pr_info("floppy.c: no request in request_done\n"); return; } if (uptodate) { /* maintain values for invalidation on geometry * change */ block = current_count_sectors + blk_rq_pos(req); INFBOUND(DRS->maxblock, block); if (block > _floppy->sect) DRS->maxtrack = 1; floppy_end_request(req, 0); } else { if (rq_data_dir(req) == WRITE) { /* record write error information */ DRWE->write_errors++; if (DRWE->write_errors == 1) { DRWE->first_error_sector = blk_rq_pos(req); DRWE->first_error_generation = DRS->generation; } DRWE->last_error_sector = blk_rq_pos(req); DRWE->last_error_generation = DRS->generation; } floppy_end_request(req, BLK_STS_IOERR); } } /* Interrupt handler evaluating the result of the r/w operation */ static void rw_interrupt(void) { int eoc; int ssize; int heads; int nr_sectors; if (R_HEAD >= 2) { /* some Toshiba floppy controllers occasionnally seem to * return bogus interrupts after read/write operations, which * can be recognized by a bad head number (>= 2) */ return; } if (!DRS->first_read_date) DRS->first_read_date = jiffies; nr_sectors = 0; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); if (ST1 & ST1_EOC) eoc = 1; else eoc = 0; if (COMMAND & 0x80) heads = 2; else heads = 1; nr_sectors = (((R_TRACK - TRACK) * heads + R_HEAD - HEAD) * SECT_PER_TRACK + R_SECTOR - SECTOR + eoc) << SIZECODE >> 2; if (nr_sectors / ssize > DIV_ROUND_UP(in_sector_offset + current_count_sectors, ssize)) { DPRINT("long rw: %x instead of %lx\n", nr_sectors, current_count_sectors); pr_info("rs=%d s=%d\n", R_SECTOR, SECTOR); pr_info("rh=%d h=%d\n", R_HEAD, HEAD); pr_info("rt=%d t=%d\n", R_TRACK, TRACK); pr_info("heads=%d eoc=%d\n", heads, eoc); pr_info("spt=%d st=%d ss=%d\n", SECT_PER_TRACK, fsector_t, ssize); pr_info("in_sector_offset=%d\n", in_sector_offset); } nr_sectors -= in_sector_offset; INFBOUND(nr_sectors, 0); SUPBOUND(current_count_sectors, nr_sectors); switch (interpret_errors()) { case 2: cont->redo(); return; case 1: if (!current_count_sectors) { cont->error(); cont->redo(); return; } break; case 0: if (!current_count_sectors) { cont->redo(); return; } current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; break; } if (probing) { if (DP->flags & FTD_MSG) DPRINT("Auto-detected floppy type %s in fd%d\n", _floppy->name, current_drive); current_type[current_drive] = _floppy; floppy_sizes[TOMINOR(current_drive)] = _floppy->size; probing = 0; } if (CT(COMMAND) != FD_READ || raw_cmd->kernel_data == bio_data(current_req->bio)) { /* transfer directly from buffer */ cont->done(1); } else if (CT(COMMAND) == FD_READ) { buffer_track = raw_cmd->track; buffer_drive = current_drive; INFBOUND(buffer_max, nr_sectors + fsector_t); } cont->redo(); } /* Compute maximal contiguous buffer size. */ static int buffer_chain_size(void) { struct bio_vec bv; int size; struct req_iterator iter; char *base; base = bio_data(current_req->bio); size = 0; rq_for_each_segment(bv, current_req, iter) { if (page_address(bv.bv_page) + bv.bv_offset != base + size) break; size += bv.bv_len; } return size >> 9; } /* Compute the maximal transfer size */ static int transfer_size(int ssize, int max_sector, int max_size) { SUPBOUND(max_sector, fsector_t + max_size); /* alignment */ max_sector -= (max_sector % _floppy->sect) % ssize; /* transfer size, beginning not aligned */ current_count_sectors = max_sector - fsector_t; return max_sector; } /* * Move data from/to the track buffer to/from the buffer cache. */ static void copy_buffer(int ssize, int max_sector, int max_sector_2) { int remaining; /* number of transferred 512-byte sectors */ struct bio_vec bv; char *buffer; char *dma_buffer; int size; struct req_iterator iter; max_sector = transfer_size(ssize, min(max_sector, max_sector_2), blk_rq_sectors(current_req)); if (current_count_sectors <= 0 && CT(COMMAND) == FD_WRITE && buffer_max > fsector_t + blk_rq_sectors(current_req)) current_count_sectors = min_t(int, buffer_max - fsector_t, blk_rq_sectors(current_req)); remaining = current_count_sectors << 9; if (remaining > blk_rq_bytes(current_req) && CT(COMMAND) == FD_WRITE) { DPRINT("in copy buffer\n"); pr_info("current_count_sectors=%ld\n", current_count_sectors); pr_info("remaining=%d\n", remaining >> 9); pr_info("current_req->nr_sectors=%u\n", blk_rq_sectors(current_req)); pr_info("current_req->current_nr_sectors=%u\n", blk_rq_cur_sectors(current_req)); pr_info("max_sector=%d\n", max_sector); pr_info("ssize=%d\n", ssize); } buffer_max = max(max_sector, buffer_max); dma_buffer = floppy_track_buffer + ((fsector_t - buffer_min) << 9); size = blk_rq_cur_bytes(current_req); rq_for_each_segment(bv, current_req, iter) { if (!remaining) break; size = bv.bv_len; SUPBOUND(size, remaining); buffer = page_address(bv.bv_page) + bv.bv_offset; if (dma_buffer + size > floppy_track_buffer + (max_buffer_sectors << 10) || dma_buffer < floppy_track_buffer) { DPRINT("buffer overrun in copy buffer %d\n", (int)((floppy_track_buffer - dma_buffer) >> 9)); pr_info("fsector_t=%d buffer_min=%d\n", fsector_t, buffer_min); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); break; } if (((unsigned long)buffer) % 512) DPRINT("%p buffer not aligned\n", buffer); if (CT(COMMAND) == FD_READ) memcpy(buffer, dma_buffer, size); else memcpy(dma_buffer, buffer, size); remaining -= size; dma_buffer += size; } if (remaining) { if (remaining > 0) max_sector -= remaining >> 9; DPRINT("weirdness: remaining %d\n", remaining >> 9); } } /* work around a bug in pseudo DMA * (on some FDCs) pseudo DMA does not stop when the CPU stops * sending data. Hence we need a different way to signal the * transfer length: We use SECT_PER_TRACK. Unfortunately, this * does not work with MT, hence we can only transfer one head at * a time */ static void virtualdmabug_workaround(void) { int hard_sectors; int end_sector; if (CT(COMMAND) == FD_WRITE) { COMMAND &= ~0x80; /* switch off multiple track mode */ hard_sectors = raw_cmd->length >> (7 + SIZECODE); end_sector = SECTOR + hard_sectors - 1; if (end_sector > SECT_PER_TRACK) { pr_info("too many sectors %d > %d\n", end_sector, SECT_PER_TRACK); return; } SECT_PER_TRACK = end_sector; /* make sure SECT_PER_TRACK * points to end of transfer */ } } /* * Formulate a read/write request. * this routine decides where to load the data (directly to buffer, or to * tmp floppy area), how much data to load (the size of the buffer, the whole * track, or a single sector) * All floppy_track_buffer handling goes in here. If we ever add track buffer * allocation on the fly, it should be done here. No other part should need * modification. */ static int make_raw_rw_request(void) { int aligned_sector_t; int max_sector; int max_size; int tracksize; int ssize; if (WARN(max_buffer_sectors == 0, "VFS: Block I/O scheduled on unopened device\n")) return 0; set_fdc((long)current_req->rq_disk->private_data); raw_cmd = &default_raw_cmd; raw_cmd->flags = FD_RAW_SPIN | FD_RAW_NEED_DISK | FD_RAW_NEED_SEEK; raw_cmd->cmd_count = NR_RW; if (rq_data_dir(current_req) == READ) { raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if (rq_data_dir(current_req) == WRITE) { raw_cmd->flags |= FD_RAW_WRITE; COMMAND = FM_MODE(_floppy, FD_WRITE); } else { DPRINT("%s: unknown command\n", __func__); return 0; } max_sector = _floppy->sect * _floppy->head; TRACK = (int)blk_rq_pos(current_req) / max_sector; fsector_t = (int)blk_rq_pos(current_req) % max_sector; if (_floppy->track && TRACK >= _floppy->track) { if (blk_rq_cur_sectors(current_req) & 1) { current_count_sectors = 1; return 1; } else return 0; } HEAD = fsector_t / _floppy->sect; if (((_floppy->stretch & (FD_SWAPSIDES | FD_SECTBASEMASK)) || test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) && fsector_t < _floppy->sect) max_sector = _floppy->sect; /* 2M disks have phantom sectors on the first track */ if ((_floppy->rate & FD_2M) && (!TRACK) && (!HEAD)) { max_sector = 2 * _floppy->sect / 3; if (fsector_t >= max_sector) { current_count_sectors = min_t(int, _floppy->sect - fsector_t, blk_rq_sectors(current_req)); return 1; } SIZECODE = 2; } else SIZECODE = FD_SIZECODE(_floppy); raw_cmd->rate = _floppy->rate & 0x43; if ((_floppy->rate & FD_2M) && (TRACK || HEAD) && raw_cmd->rate == 2) raw_cmd->rate = 1; if (SIZECODE) SIZECODE2 = 0xff; else SIZECODE2 = 0x80; raw_cmd->track = TRACK << STRETCH(_floppy); DR_SELECT = UNIT(current_drive) + PH_HEAD(_floppy, HEAD); GAP = _floppy->gap; ssize = DIV_ROUND_UP(1 << SIZECODE, 4); SECT_PER_TRACK = _floppy->sect << 2 >> SIZECODE; SECTOR = ((fsector_t % _floppy->sect) << 2 >> SIZECODE) + FD_SECTBASE(_floppy); /* tracksize describes the size which can be filled up with sectors * of size ssize. */ tracksize = _floppy->sect - _floppy->sect % ssize; if (tracksize < _floppy->sect) { SECT_PER_TRACK++; if (tracksize <= fsector_t % _floppy->sect) SECTOR--; /* if we are beyond tracksize, fill up using smaller sectors */ while (tracksize <= fsector_t % _floppy->sect) { while (tracksize + ssize > _floppy->sect) { SIZECODE--; ssize >>= 1; } SECTOR++; SECT_PER_TRACK++; tracksize += ssize; } max_sector = HEAD * _floppy->sect + tracksize; } else if (!TRACK && !HEAD && !(_floppy->rate & FD_2M) && probing) { max_sector = _floppy->sect; } else if (!HEAD && CT(COMMAND) == FD_WRITE) { /* for virtual DMA bug workaround */ max_sector = _floppy->sect; } in_sector_offset = (fsector_t % _floppy->sect) % ssize; aligned_sector_t = fsector_t - in_sector_offset; max_size = blk_rq_sectors(current_req); if ((raw_cmd->track == buffer_track) && (current_drive == buffer_drive) && (fsector_t >= buffer_min) && (fsector_t < buffer_max)) { /* data already in track buffer */ if (CT(COMMAND) == FD_READ) { copy_buffer(1, max_sector, buffer_max); return 1; } } else if (in_sector_offset || blk_rq_sectors(current_req) < ssize) { if (CT(COMMAND) == FD_WRITE) { unsigned int sectors; sectors = fsector_t + blk_rq_sectors(current_req); if (sectors > ssize && sectors < ssize + ssize) max_size = ssize + ssize; else max_size = ssize; } raw_cmd->flags &= ~FD_RAW_WRITE; raw_cmd->flags |= FD_RAW_READ; COMMAND = FM_MODE(_floppy, FD_READ); } else if ((unsigned long)bio_data(current_req->bio) < MAX_DMA_ADDRESS) { unsigned long dma_limit; int direct, indirect; indirect = transfer_size(ssize, max_sector, max_buffer_sectors * 2) - fsector_t; /* * Do NOT use minimum() here---MAX_DMA_ADDRESS is 64 bits wide * on a 64 bit machine! */ max_size = buffer_chain_size(); dma_limit = (MAX_DMA_ADDRESS - ((unsigned long)bio_data(current_req->bio))) >> 9; if ((unsigned long)max_size > dma_limit) max_size = dma_limit; /* 64 kb boundaries */ if (CROSS_64KB(bio_data(current_req->bio), max_size << 9)) max_size = (K_64 - ((unsigned long)bio_data(current_req->bio)) % K_64) >> 9; direct = transfer_size(ssize, max_sector, max_size) - fsector_t; /* * We try to read tracks, but if we get too many errors, we * go back to reading just one sector at a time. * * This means we should be able to read a sector even if there * are other bad sectors on this track. */ if (!direct || (indirect * 2 > direct * 3 && *errors < DP->max_errors.read_track && ((!probing || (DP->read_track & (1 << DRS->probed_format)))))) { max_size = blk_rq_sectors(current_req); } else { raw_cmd->kernel_data = bio_data(current_req->bio); raw_cmd->length = current_count_sectors << 9; if (raw_cmd->length == 0) { DPRINT("%s: zero dma transfer attempted\n", __func__); DPRINT("indirect=%d direct=%d fsector_t=%d\n", indirect, direct, fsector_t); return 0; } virtualdmabug_workaround(); return 2; } } if (CT(COMMAND) == FD_READ) max_size = max_sector; /* unbounded */ /* claim buffer track if needed */ if (buffer_track != raw_cmd->track || /* bad track */ buffer_drive != current_drive || /* bad drive */ fsector_t > buffer_max || fsector_t < buffer_min || ((CT(COMMAND) == FD_READ || (!in_sector_offset && blk_rq_sectors(current_req) >= ssize)) && max_sector > 2 * max_buffer_sectors + buffer_min && max_size + fsector_t > 2 * max_buffer_sectors + buffer_min)) { /* not enough space */ buffer_track = -1; buffer_drive = current_drive; buffer_max = buffer_min = aligned_sector_t; } raw_cmd->kernel_data = floppy_track_buffer + ((aligned_sector_t - buffer_min) << 9); if (CT(COMMAND) == FD_WRITE) { /* copy write buffer to track buffer. * if we get here, we know that the write * is either aligned or the data already in the buffer * (buffer will be overwritten) */ if (in_sector_offset && buffer_track == -1) DPRINT("internal error offset !=0 on write\n"); buffer_track = raw_cmd->track; buffer_drive = current_drive; copy_buffer(ssize, max_sector, 2 * max_buffer_sectors + buffer_min); } else transfer_size(ssize, max_sector, 2 * max_buffer_sectors + buffer_min - aligned_sector_t); /* round up current_count_sectors to get dma xfer size */ raw_cmd->length = in_sector_offset + current_count_sectors; raw_cmd->length = ((raw_cmd->length - 1) | (ssize - 1)) + 1; raw_cmd->length <<= 9; if ((raw_cmd->length < current_count_sectors << 9) || (raw_cmd->kernel_data != bio_data(current_req->bio) && CT(COMMAND) == FD_WRITE && (aligned_sector_t + (raw_cmd->length >> 9) > buffer_max || aligned_sector_t < buffer_min)) || raw_cmd->length % (128 << SIZECODE) || raw_cmd->length <= 0 || current_count_sectors <= 0) { DPRINT("fractionary current count b=%lx s=%lx\n", raw_cmd->length, current_count_sectors); if (raw_cmd->kernel_data != bio_data(current_req->bio)) pr_info("addr=%d, length=%ld\n", (int)((raw_cmd->kernel_data - floppy_track_buffer) >> 9), current_count_sectors); pr_info("st=%d ast=%d mse=%d msi=%d\n", fsector_t, aligned_sector_t, max_sector, max_size); pr_info("ssize=%x SIZECODE=%d\n", ssize, SIZECODE); pr_info("command=%x SECTOR=%d HEAD=%d, TRACK=%d\n", COMMAND, SECTOR, HEAD, TRACK); pr_info("buffer drive=%d\n", buffer_drive); pr_info("buffer track=%d\n", buffer_track); pr_info("buffer_min=%d\n", buffer_min); pr_info("buffer_max=%d\n", buffer_max); return 0; } if (raw_cmd->kernel_data != bio_data(current_req->bio)) { if (raw_cmd->kernel_data < floppy_track_buffer || current_count_sectors < 0 || raw_cmd->length < 0 || raw_cmd->kernel_data + raw_cmd->length > floppy_track_buffer + (max_buffer_sectors << 10)) { DPRINT("buffer overrun in schedule dma\n"); pr_info("fsector_t=%d buffer_min=%d current_count=%ld\n", fsector_t, buffer_min, raw_cmd->length >> 9); pr_info("current_count_sectors=%ld\n", current_count_sectors); if (CT(COMMAND) == FD_READ) pr_info("read\n"); if (CT(COMMAND) == FD_WRITE) pr_info("write\n"); return 0; } } else if (raw_cmd->length > blk_rq_bytes(current_req) || current_count_sectors > blk_rq_sectors(current_req)) { DPRINT("buffer overrun in direct transfer\n"); return 0; } else if (raw_cmd->length < current_count_sectors << 9) { DPRINT("more sectors than bytes\n"); pr_info("bytes=%ld\n", raw_cmd->length >> 9); pr_info("sectors=%ld\n", current_count_sectors); } if (raw_cmd->length == 0) { DPRINT("zero dma transfer attempted from make_raw_request\n"); return 0; } virtualdmabug_workaround(); return 2; } static int set_next_request(void) { current_req = list_first_entry_or_null(&floppy_reqs, struct request, queuelist); if (current_req) { current_req->error_count = 0; list_del_init(&current_req->queuelist); } return current_req != NULL; } static void redo_fd_request(void) { int drive; int tmp; lastredo = jiffies; if (current_drive < N_DRIVE) floppy_off(current_drive); do_request: if (!current_req) { int pending; spin_lock_irq(&floppy_lock); pending = set_next_request(); spin_unlock_irq(&floppy_lock); if (!pending) { do_floppy = NULL; unlock_fdc(); return; } } drive = (long)current_req->rq_disk->private_data; set_fdc(drive); reschedule_timeout(current_reqD, "redo fd request"); set_floppy(drive); raw_cmd = &default_raw_cmd; raw_cmd->flags = 0; if (start_motor(redo_fd_request)) return; disk_change(current_drive); if (test_bit(current_drive, &fake_change) || test_bit(FD_DISK_CHANGED_BIT, &DRS->flags)) { DPRINT("disk absent or changed during operation\n"); request_done(0); goto do_request; } if (!_floppy) { /* Autodetection */ if (!probing) { DRS->probed_format = 0; if (next_valid_format()) { DPRINT("no autodetectable formats\n"); _floppy = NULL; request_done(0); goto do_request; } } probing = 1; _floppy = floppy_type + DP->autodetect[DRS->probed_format]; } else probing = 0; errors = &(current_req->error_count); tmp = make_raw_rw_request(); if (tmp < 2) { request_done(tmp); goto do_request; } if (test_bit(FD_NEED_TWADDLE_BIT, &DRS->flags)) twaddle(); schedule_bh(floppy_start); debugt(__func__, "queue fd request"); return; } static const struct cont_t rw_cont = { .interrupt = rw_interrupt, .redo = redo_fd_request, .error = bad_flp_intr, .done = request_done }; static void process_fd_request(void) { cont = &rw_cont; schedule_bh(redo_fd_request); } static blk_status_t floppy_queue_rq(struct blk_mq_hw_ctx *hctx, const struct blk_mq_queue_data *bd) { blk_mq_start_request(bd->rq); if (WARN(max_buffer_sectors == 0, "VFS: %s called on non-open device\n", __func__)) return BLK_STS_IOERR; if (WARN(atomic_read(&usage_count) == 0, "warning: usage count=0, current_req=%p sect=%ld flags=%llx\n", current_req, (long)blk_rq_pos(current_req), (unsigned long long) current_req->cmd_flags)) return BLK_STS_IOERR; spin_lock_irq(&floppy_lock); list_add_tail(&bd->rq->queuelist, &floppy_reqs); spin_unlock_irq(&floppy_lock); if (test_and_set_bit(0, &fdc_busy)) { /* fdc busy, this new request will be treated when the current one is done */ is_alive(__func__, "old request running"); return BLK_STS_OK; } command_status = FD_COMMAND_NONE; __reschedule_timeout(MAXTIMEOUT, "fd_request"); set_fdc(0); process_fd_request(); is_alive(__func__, ""); return BLK_STS_OK; } static const struct cont_t poll_cont = { .interrupt = success_and_wakeup, .redo = floppy_ready, .error = generic_failure, .done = generic_done }; static int poll_drive(bool interruptible, int flag) { /* no auto-sense, just clear dcl */ raw_cmd = &default_raw_cmd; raw_cmd->flags = flag; raw_cmd->track = 0; raw_cmd->cmd_count = 0; cont = &poll_cont; debug_dcl(DP->flags, "setting NEWCHANGE in poll_drive\n"); set_bit(FD_DISK_NEWCHANGE_BIT, &DRS->flags); return wait_til_done(floppy_ready, interruptible); } /* * User triggered reset * ==================== */ static void reset_intr(void) { pr_info("weird, reset interrupt called\n"); } static const struct cont_t reset_cont = { .interrupt = reset_intr, .redo = success_and_wakeup, .error = generic_failure, .done = generic_done }; static int user_reset_fdc(int drive, int arg, bool interruptible) { int ret; if (lock_fdc(drive)) return -EINTR; if (arg == FD_RESET_ALWAYS) FDCS->reset = 1; if (FDCS->reset) { cont = &reset_cont; ret = wait_til_done(reset_fdc, interruptible); if (ret == -EINTR) return -EINTR; } process_fd_request(); return 0; } /* * Misc Ioctl's and support * ======================== */ static inline int fd_copyout(void __user *param, const void *address, unsigned long size) { return copy_to_user(param, address, size) ? -EFAULT : 0; } static inline int fd_copyin(void __user *param, void *address, unsigned long size) { return copy_from_user(address, param, size) ? -EFAULT : 0; } static const char *drive_name(int type, int drive) { struct floppy_struct *floppy; if (type) floppy = floppy_type + type; else { if (UDP->native_format) floppy = floppy_type + UDP->native_format; else return "(null)"; } if (floppy->name) return floppy->name; else return "(null)"; } /* raw commands */ static void raw_cmd_done(int flag) { int i; if (!flag) { raw_cmd->flags |= FD_RAW_FAILURE; raw_cmd->flags |= FD_RAW_HARDFAILURE; } else { raw_cmd->reply_count = inr; if (raw_cmd->reply_count > MAX_REPLIES) raw_cmd->reply_count = 0; for (i = 0; i < raw_cmd->reply_count; i++) raw_cmd->reply[i] = reply_buffer[i]; if (raw_cmd->flags & (FD_RAW_READ | FD_RAW_WRITE)) { unsigned long flags; flags = claim_dma_lock(); raw_cmd->length = fd_get_dma_residue(); release_dma_lock(flags); } if ((raw_cmd->flags & FD_RAW_SOFTFAILURE) && (!raw_cmd->reply_count || (raw_cmd->reply[0] & 0xc0))) raw_cmd->flags |= FD_RAW_FAILURE; if (disk_change(current_drive)) raw_cmd->flags |= FD_RAW_DISK_CHANGE; else raw_cmd->flags &= ~FD_RAW_DISK_CHANGE; if (raw_cmd->flags & FD_RAW_NO_MOTOR_AFTER) motor_off_callback(&motor_off_timer[current_drive]); if (raw_cmd->next && (!(raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_FAILURE)) && ((raw_cmd->flags & FD_RAW_FAILURE) || !(raw_cmd->flags & FD_RAW_STOP_IF_SUCCESS))) { raw_cmd = raw_cmd->next; return; } } generic_done(flag); } static const struct cont_t raw_cmd_cont = { .interrupt = success_and_wakeup, .redo = floppy_start, .error = generic_failure, .done = raw_cmd_done }; static int raw_cmd_copyout(int cmd, void __user *param, struct floppy_raw_cmd *ptr) { int ret; while (ptr) { struct floppy_raw_cmd cmd = *ptr; cmd.next = NULL; cmd.kernel_data = NULL; ret = copy_to_user(param, &cmd, sizeof(cmd)); if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if ((ptr->flags & FD_RAW_READ) && ptr->buffer_length) { if (ptr->length >= 0 && ptr->length <= ptr->buffer_length) { long length = ptr->buffer_length - ptr->length; ret = fd_copyout(ptr->data, ptr->kernel_data, length); if (ret) return ret; } } ptr = ptr->next; } return 0; } static void raw_cmd_free(struct floppy_raw_cmd **ptr) { struct floppy_raw_cmd *next; struct floppy_raw_cmd *this; this = *ptr; *ptr = NULL; while (this) { if (this->buffer_length) { fd_dma_mem_free((unsigned long)this->kernel_data, this->buffer_length); this->buffer_length = 0; } next = this->next; kfree(this); this = next; } } static int raw_cmd_copyin(int cmd, void __user *param, struct floppy_raw_cmd **rcmd) { struct floppy_raw_cmd *ptr; int ret; int i; *rcmd = NULL; loop: ptr = kmalloc(sizeof(struct floppy_raw_cmd), GFP_KERNEL); if (!ptr) return -ENOMEM; *rcmd = ptr; ret = copy_from_user(ptr, param, sizeof(*ptr)); ptr->next = NULL; ptr->buffer_length = 0; ptr->kernel_data = NULL; if (ret) return -EFAULT; param += sizeof(struct floppy_raw_cmd); if (ptr->cmd_count > 33) /* the command may now also take up the space * initially intended for the reply & the * reply count. Needed for long 82078 commands * such as RESTORE, which takes ... 17 command * bytes. Murphy's law #137: When you reserve * 16 bytes for a structure, you'll one day * discover that you really need 17... */ return -EINVAL; for (i = 0; i < 16; i++) ptr->reply[i] = 0; ptr->resultcode = 0; if (ptr->flags & (FD_RAW_READ | FD_RAW_WRITE)) { if (ptr->length <= 0) return -EINVAL; ptr->kernel_data = (char *)fd_dma_mem_alloc(ptr->length); fallback_on_nodma_alloc(&ptr->kernel_data, ptr->length); if (!ptr->kernel_data) return -ENOMEM; ptr->buffer_length = ptr->length; } if (ptr->flags & FD_RAW_WRITE) { ret = fd_copyin(ptr->data, ptr->kernel_data, ptr->length); if (ret) return ret; } if (ptr->flags & FD_RAW_MORE) { rcmd = &(ptr->next); ptr->rate &= 0x43; goto loop; } return 0; } static int raw_cmd_ioctl(int cmd, void __user *param) { struct floppy_raw_cmd *my_raw_cmd; int drive; int ret2; int ret; if (FDCS->rawcmd <= 1) FDCS->rawcmd = 1; for (drive = 0; drive < N_DRIVE; drive++) { if (FDC(drive) != fdc) continue; if (drive == current_drive) { if (UDRS->fd_ref > 1) { FDCS->rawcmd = 2; break; } } else if (UDRS->fd_ref) { FDCS->rawcmd = 2; break; } } if (FDCS->reset) return -EIO; ret = raw_cmd_copyin(cmd, param, &my_raw_cmd); if (ret) { raw_cmd_free(&my_raw_cmd); return ret; } raw_cmd = my_raw_cmd; cont = &raw_cmd_cont; ret = wait_til_done(floppy_start, true); debug_dcl(DP->flags, "calling disk change from raw_cmd ioctl\n"); if (ret != -EINTR && FDCS->reset) ret = -EIO; DRS->track = NO_TRACK; ret2 = raw_cmd_copyout(cmd, param, my_raw_cmd); if (!ret) ret = ret2; raw_cmd_free(&my_raw_cmd); return ret; } static int invalidate_drive(struct block_device *bdev) { /* invalidate the buffer track to force a reread */ set_bit((long)bdev->bd_disk->private_data, &fake_change); process_fd_request(); check_disk_change(bdev); return 0; } static int set_geometry(unsigned int cmd, struct floppy_struct *g, int drive, int type, struct block_device *bdev) { int cnt; /* sanity checking for parameters. */ if ((int)g->sect <= 0 || (int)g->head <= 0 || /* check for overflow in max_sector */ (int)(g->sect * g->head) <= 0 || /* check for zero in F_SECT_PER_TRACK */ (unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 || g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) || /* check if reserved bits are set */ (g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0) return -EINVAL; if (type) { if (!capable(CAP_SYS_ADMIN)) return -EPERM; mutex_lock(&open_lock); if (lock_fdc(drive)) { mutex_unlock(&open_lock); return -EINTR; } floppy_type[type] = *g; floppy_type[type].name = "user format"; for (cnt = type << 2; cnt < (type << 2) + 4; cnt++) floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] = floppy_type[type].size + 1; process_fd_request(); for (cnt = 0; cnt < N_DRIVE; cnt++) { struct block_device *bdev = opened_bdev[cnt]; if (!bdev || ITYPE(drive_state[cnt].fd_device) != type) continue; __invalidate_device(bdev, true); } mutex_unlock(&open_lock); } else { int oldStretch; if (lock_fdc(drive)) return -EINTR; if (cmd != FDDEFPRM) { /* notice a disk change immediately, else * we lose our settings immediately*/ if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; } oldStretch = g->stretch; user_params[drive] = *g; if (buffer_drive == drive) SUPBOUND(buffer_max, user_params[drive].sect); current_type[drive] = &user_params[drive]; floppy_sizes[drive] = user_params[drive].size; if (cmd == FDDEFPRM) DRS->keep_data = -1; else DRS->keep_data = 1; /* invalidation. Invalidate only when needed, i.e. * when there are already sectors in the buffer cache * whose number will change. This is useful, because * mtools often changes the geometry of the disk after * looking at the boot block */ if (DRS->maxblock > user_params[drive].sect || DRS->maxtrack || ((user_params[drive].sect ^ oldStretch) & (FD_SWAPSIDES | FD_SECTBASEMASK))) invalidate_drive(bdev); else process_fd_request(); } return 0; } /* handle obsolete ioctl's */ static unsigned int ioctl_table[] = { FDCLRPRM, FDSETPRM, FDDEFPRM, FDGETPRM, FDMSGON, FDMSGOFF, FDFMTBEG, FDFMTTRK, FDFMTEND, FDSETEMSGTRESH, FDFLUSH, FDSETMAXERRS, FDGETMAXERRS, FDGETDRVTYP, FDSETDRVPRM, FDGETDRVPRM, FDGETDRVSTAT, FDPOLLDRVSTAT, FDRESET, FDGETFDCSTAT, FDWERRORCLR, FDWERRORGET, FDRAWCMD, FDEJECT, FDTWADDLE }; static int normalize_ioctl(unsigned int *cmd, int *size) { int i; for (i = 0; i < ARRAY_SIZE(ioctl_table); i++) { if ((*cmd & 0xffff) == (ioctl_table[i] & 0xffff)) { *size = _IOC_SIZE(*cmd); *cmd = ioctl_table[i]; if (*size > _IOC_SIZE(*cmd)) { pr_info("ioctl not yet supported\n"); return -EFAULT; } return 0; } } return -EINVAL; } static int get_floppy_geometry(int drive, int type, struct floppy_struct **g) { if (type) *g = &floppy_type[type]; else { if (lock_fdc(drive)) return -EINTR; if (poll_drive(false, 0) == -EINTR) return -EINTR; process_fd_request(); *g = current_type[drive]; } if (!*g) return -ENODEV; return 0; } static int fd_getgeo(struct block_device *bdev, struct hd_geometry *geo) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(drive_state[drive].fd_device); struct floppy_struct *g; int ret; ret = get_floppy_geometry(drive, type, &g); if (ret) return ret; geo->heads = g->head; geo->sectors = g->sect; geo->cylinders = g->track; return 0; } static bool valid_floppy_drive_params(const short autodetect[8], int native_format) { size_t floppy_type_size = ARRAY_SIZE(floppy_type); size_t i = 0; for (i = 0; i < 8; ++i) { if (autodetect[i] < 0 || autodetect[i] >= floppy_type_size) return false; } if (native_format < 0 || native_format >= floppy_type_size) return false; return true; } static int fd_locked_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; int type = ITYPE(UDRS->fd_device); int i; int ret; int size; union inparam { struct floppy_struct g; /* geometry */ struct format_descr f; struct floppy_max_errors max_errors; struct floppy_drive_params dp; } inparam; /* parameters coming from user space */ const void *outparam; /* parameters passed back to user space */ /* convert compatibility eject ioctls into floppy eject ioctl. * We do this in order to provide a means to eject floppy disks before * installing the new fdutils package */ if (cmd == CDROMEJECT || /* CD-ROM eject */ cmd == 0x6470) { /* SunOS floppy eject */ DPRINT("obsolete eject ioctl\n"); DPRINT("please use floppycontrol --eject\n"); cmd = FDEJECT; } if (!((cmd & 0xff00) == 0x0200)) return -EINVAL; /* convert the old style command into a new style command */ ret = normalize_ioctl(&cmd, &size); if (ret) return ret; /* permission checks */ if (((cmd & 0x40) && !(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) || ((cmd & 0x80) && !capable(CAP_SYS_ADMIN))) return -EPERM; if (WARN_ON(size < 0 || size > sizeof(inparam))) return -EINVAL; /* copyin */ memset(&inparam, 0, sizeof(inparam)); if (_IOC_DIR(cmd) & _IOC_WRITE) { ret = fd_copyin((void __user *)param, &inparam, size); if (ret) return ret; } switch (cmd) { case FDEJECT: if (UDRS->fd_ref != 1) /* somebody else has this drive open */ return -EBUSY; if (lock_fdc(drive)) return -EINTR; /* do the actual eject. Fails on * non-Sparc architectures */ ret = fd_eject(UNIT(drive)); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); process_fd_request(); return ret; case FDCLRPRM: if (lock_fdc(drive)) return -EINTR; current_type[drive] = NULL; floppy_sizes[drive] = MAX_DISK_SIZE << 1; UDRS->keep_data = 0; return invalidate_drive(bdev); case FDSETPRM: case FDDEFPRM: return set_geometry(cmd, &inparam.g, drive, type, bdev); case FDGETPRM: ret = get_floppy_geometry(drive, type, (struct floppy_struct **)&outparam); if (ret) return ret; memcpy(&inparam.g, outparam, offsetof(struct floppy_struct, name)); outparam = &inparam.g; break; case FDMSGON: UDP->flags |= FTD_MSG; return 0; case FDMSGOFF: UDP->flags &= ~FTD_MSG; return 0; case FDFMTBEG: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; ret = UDRS->flags; process_fd_request(); if (ret & FD_VERIFY) return -ENODEV; if (!(ret & FD_DISK_WRITABLE)) return -EROFS; return 0; case FDFMTTRK: if (UDRS->fd_ref != 1) return -EBUSY; return do_format(drive, &inparam.f); case FDFMTEND: case FDFLUSH: if (lock_fdc(drive)) return -EINTR; return invalidate_drive(bdev); case FDSETEMSGTRESH: UDP->max_errors.reporting = (unsigned short)(param & 0x0f); return 0; case FDGETMAXERRS: outparam = &UDP->max_errors; break; case FDSETMAXERRS: UDP->max_errors = inparam.max_errors; break; case FDGETDRVTYP: outparam = drive_name(type, drive); SUPBOUND(size, strlen((const char *)outparam) + 1); break; case FDSETDRVPRM: if (!valid_floppy_drive_params(inparam.dp.autodetect, inparam.dp.native_format)) return -EINVAL; *UDP = inparam.dp; break; case FDGETDRVPRM: outparam = UDP; break; case FDPOLLDRVSTAT: if (lock_fdc(drive)) return -EINTR; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) return -EINTR; process_fd_request(); /* fall through */ case FDGETDRVSTAT: outparam = UDRS; break; case FDRESET: return user_reset_fdc(drive, (int)param, true); case FDGETFDCSTAT: outparam = UFDCS; break; case FDWERRORCLR: memset(UDRWE, 0, sizeof(*UDRWE)); return 0; case FDWERRORGET: outparam = UDRWE; break; case FDRAWCMD: if (type) return -EINVAL; if (lock_fdc(drive)) return -EINTR; set_floppy(drive); i = raw_cmd_ioctl(cmd, (void __user *)param); if (i == -EINTR) return -EINTR; process_fd_request(); return i; case FDTWADDLE: if (lock_fdc(drive)) return -EINTR; twaddle(); process_fd_request(); return 0; default: return -EINVAL; } if (_IOC_DIR(cmd) & _IOC_READ) return fd_copyout((void __user *)param, outparam, size); return 0; } static int fd_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int ret; mutex_lock(&floppy_mutex); ret = fd_locked_ioctl(bdev, mode, cmd, param); mutex_unlock(&floppy_mutex); return ret; } #ifdef CONFIG_COMPAT struct compat_floppy_drive_params { char cmos; compat_ulong_t max_dtr; compat_ulong_t hlt; compat_ulong_t hut; compat_ulong_t srt; compat_ulong_t spinup; compat_ulong_t spindown; unsigned char spindown_offset; unsigned char select_delay; unsigned char rps; unsigned char tracks; compat_ulong_t timeout; unsigned char interleave_sect; struct floppy_max_errors max_errors; char flags; char read_track; short autodetect[8]; compat_int_t checkfreq; compat_int_t native_format; }; struct compat_floppy_drive_struct { signed char flags; compat_ulong_t spinup_date; compat_ulong_t select_date; compat_ulong_t first_read_date; short probed_format; short track; short maxblock; short maxtrack; compat_int_t generation; compat_int_t keep_data; compat_int_t fd_ref; compat_int_t fd_device; compat_int_t last_checked; compat_caddr_t dmabuf; compat_int_t bufblocks; }; struct compat_floppy_fdc_state { compat_int_t spec1; compat_int_t spec2; compat_int_t dtr; unsigned char version; unsigned char dor; compat_ulong_t address; unsigned int rawcmd:2; unsigned int reset:1; unsigned int need_configure:1; unsigned int perp_mode:2; unsigned int has_fifo:1; unsigned int driver_version; unsigned char track[4]; }; struct compat_floppy_write_errors { unsigned int write_errors; compat_ulong_t first_error_sector; compat_int_t first_error_generation; compat_ulong_t last_error_sector; compat_int_t last_error_generation; compat_uint_t badness; }; #define FDSETPRM32 _IOW(2, 0x42, struct compat_floppy_struct) #define FDDEFPRM32 _IOW(2, 0x43, struct compat_floppy_struct) #define FDSETDRVPRM32 _IOW(2, 0x90, struct compat_floppy_drive_params) #define FDGETDRVPRM32 _IOR(2, 0x11, struct compat_floppy_drive_params) #define FDGETDRVSTAT32 _IOR(2, 0x12, struct compat_floppy_drive_struct) #define FDPOLLDRVSTAT32 _IOR(2, 0x13, struct compat_floppy_drive_struct) #define FDGETFDCSTAT32 _IOR(2, 0x15, struct compat_floppy_fdc_state) #define FDWERRORGET32 _IOR(2, 0x17, struct compat_floppy_write_errors) static int compat_set_geometry(struct block_device *bdev, fmode_t mode, unsigned int cmd, struct compat_floppy_struct __user *arg) { struct floppy_struct v; int drive, type; int err; BUILD_BUG_ON(offsetof(struct floppy_struct, name) != offsetof(struct compat_floppy_struct, name)); if (!(mode & (FMODE_WRITE | FMODE_WRITE_IOCTL))) return -EPERM; memset(&v, 0, sizeof(struct floppy_struct)); if (copy_from_user(&v, arg, offsetof(struct floppy_struct, name))) return -EFAULT; mutex_lock(&floppy_mutex); drive = (long)bdev->bd_disk->private_data; type = ITYPE(UDRS->fd_device); err = set_geometry(cmd == FDSETPRM32 ? FDSETPRM : FDDEFPRM, &v, drive, type, bdev); mutex_unlock(&floppy_mutex); return err; } static int compat_get_prm(int drive, struct compat_floppy_struct __user *arg) { struct compat_floppy_struct v; struct floppy_struct *p; int err; memset(&v, 0, sizeof(v)); mutex_lock(&floppy_mutex); err = get_floppy_geometry(drive, ITYPE(UDRS->fd_device), &p); if (err) { mutex_unlock(&floppy_mutex); return err; } memcpy(&v, p, offsetof(struct floppy_struct, name)); mutex_unlock(&floppy_mutex); if (copy_to_user(arg, &v, sizeof(struct compat_floppy_struct))) return -EFAULT; return 0; } static int compat_setdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; if (!capable(CAP_SYS_ADMIN)) return -EPERM; if (copy_from_user(&v, arg, sizeof(struct compat_floppy_drive_params))) return -EFAULT; if (!valid_floppy_drive_params(v.autodetect, v.native_format)) return -EINVAL; mutex_lock(&floppy_mutex); UDP->cmos = v.cmos; UDP->max_dtr = v.max_dtr; UDP->hlt = v.hlt; UDP->hut = v.hut; UDP->srt = v.srt; UDP->spinup = v.spinup; UDP->spindown = v.spindown; UDP->spindown_offset = v.spindown_offset; UDP->select_delay = v.select_delay; UDP->rps = v.rps; UDP->tracks = v.tracks; UDP->timeout = v.timeout; UDP->interleave_sect = v.interleave_sect; UDP->max_errors = v.max_errors; UDP->flags = v.flags; UDP->read_track = v.read_track; memcpy(UDP->autodetect, v.autodetect, sizeof(v.autodetect)); UDP->checkfreq = v.checkfreq; UDP->native_format = v.native_format; mutex_unlock(&floppy_mutex); return 0; } static int compat_getdrvprm(int drive, struct compat_floppy_drive_params __user *arg) { struct compat_floppy_drive_params v; memset(&v, 0, sizeof(struct compat_floppy_drive_params)); mutex_lock(&floppy_mutex); v.cmos = UDP->cmos; v.max_dtr = UDP->max_dtr; v.hlt = UDP->hlt; v.hut = UDP->hut; v.srt = UDP->srt; v.spinup = UDP->spinup; v.spindown = UDP->spindown; v.spindown_offset = UDP->spindown_offset; v.select_delay = UDP->select_delay; v.rps = UDP->rps; v.tracks = UDP->tracks; v.timeout = UDP->timeout; v.interleave_sect = UDP->interleave_sect; v.max_errors = UDP->max_errors; v.flags = UDP->flags; v.read_track = UDP->read_track; memcpy(v.autodetect, UDP->autodetect, sizeof(v.autodetect)); v.checkfreq = UDP->checkfreq; v.native_format = UDP->native_format; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_params))) return -EFAULT; return 0; } static int compat_getdrvstat(int drive, bool poll, struct compat_floppy_drive_struct __user *arg) { struct compat_floppy_drive_struct v; memset(&v, 0, sizeof(struct compat_floppy_drive_struct)); mutex_lock(&floppy_mutex); if (poll) { if (lock_fdc(drive)) goto Eintr; if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR) goto Eintr; process_fd_request(); } v.spinup_date = UDRS->spinup_date; v.select_date = UDRS->select_date; v.first_read_date = UDRS->first_read_date; v.probed_format = UDRS->probed_format; v.track = UDRS->track; v.maxblock = UDRS->maxblock; v.maxtrack = UDRS->maxtrack; v.generation = UDRS->generation; v.keep_data = UDRS->keep_data; v.fd_ref = UDRS->fd_ref; v.fd_device = UDRS->fd_device; v.last_checked = UDRS->last_checked; v.dmabuf = (uintptr_t)UDRS->dmabuf; v.bufblocks = UDRS->bufblocks; mutex_unlock(&floppy_mutex); if (copy_from_user(arg, &v, sizeof(struct compat_floppy_drive_struct))) return -EFAULT; return 0; Eintr: mutex_unlock(&floppy_mutex); return -EINTR; } static int compat_getfdcstat(int drive, struct compat_floppy_fdc_state __user *arg) { struct compat_floppy_fdc_state v32; struct floppy_fdc_state v; mutex_lock(&floppy_mutex); v = *UFDCS; mutex_unlock(&floppy_mutex); memset(&v32, 0, sizeof(struct compat_floppy_fdc_state)); v32.spec1 = v.spec1; v32.spec2 = v.spec2; v32.dtr = v.dtr; v32.version = v.version; v32.dor = v.dor; v32.address = v.address; v32.rawcmd = v.rawcmd; v32.reset = v.reset; v32.need_configure = v.need_configure; v32.perp_mode = v.perp_mode; v32.has_fifo = v.has_fifo; v32.driver_version = v.driver_version; memcpy(v32.track, v.track, 4); if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_fdc_state))) return -EFAULT; return 0; } static int compat_werrorget(int drive, struct compat_floppy_write_errors __user *arg) { struct compat_floppy_write_errors v32; struct floppy_write_errors v; memset(&v32, 0, sizeof(struct compat_floppy_write_errors)); mutex_lock(&floppy_mutex); v = *UDRWE; mutex_unlock(&floppy_mutex); v32.write_errors = v.write_errors; v32.first_error_sector = v.first_error_sector; v32.first_error_generation = v.first_error_generation; v32.last_error_sector = v.last_error_sector; v32.last_error_generation = v.last_error_generation; v32.badness = v.badness; if (copy_to_user(arg, &v32, sizeof(struct compat_floppy_write_errors))) return -EFAULT; return 0; } static int fd_compat_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long param) { int drive = (long)bdev->bd_disk->private_data; switch (cmd) { case FDMSGON: case FDMSGOFF: case FDSETEMSGTRESH: case FDFLUSH: case FDWERRORCLR: case FDEJECT: case FDCLRPRM: case FDFMTBEG: case FDRESET: case FDTWADDLE: return fd_ioctl(bdev, mode, cmd, param); case FDSETMAXERRS: case FDGETMAXERRS: case FDGETDRVTYP: case FDFMTEND: case FDFMTTRK: case FDRAWCMD: return fd_ioctl(bdev, mode, cmd, (unsigned long)compat_ptr(param)); case FDSETPRM32: case FDDEFPRM32: return compat_set_geometry(bdev, mode, cmd, compat_ptr(param)); case FDGETPRM32: return compat_get_prm(drive, compat_ptr(param)); case FDSETDRVPRM32: return compat_setdrvprm(drive, compat_ptr(param)); case FDGETDRVPRM32: return compat_getdrvprm(drive, compat_ptr(param)); case FDPOLLDRVSTAT32: return compat_getdrvstat(drive, true, compat_ptr(param)); case FDGETDRVSTAT32: return compat_getdrvstat(drive, false, compat_ptr(param)); case FDGETFDCSTAT32: return compat_getfdcstat(drive, compat_ptr(param)); case FDWERRORGET32: return compat_werrorget(drive, compat_ptr(param)); } return -EINVAL; } #endif static void __init config_types(void) { bool has_drive = false; int drive; /* read drive info out of physical CMOS */ drive = 0; if (!UDP->cmos) UDP->cmos = FLOPPY0_TYPE; drive = 1; if (!UDP->cmos && FLOPPY1_TYPE) UDP->cmos = FLOPPY1_TYPE; /* FIXME: additional physical CMOS drive detection should go here */ for (drive = 0; drive < N_DRIVE; drive++) { unsigned int type = UDP->cmos; struct floppy_drive_params *params; const char *name = NULL; char temparea[32]; if (type < ARRAY_SIZE(default_drive_params)) { params = &default_drive_params[type].params; if (type) { name = default_drive_params[type].name; allowed_drive_mask |= 1 << drive; } else allowed_drive_mask &= ~(1 << drive); } else { params = &default_drive_params[0].params; snprintf(temparea, sizeof(temparea), "unknown type %d (usb?)", type); name = temparea; } if (name) { const char *prepend; if (!has_drive) { prepend = ""; has_drive = true; pr_info("Floppy drive(s):"); } else { prepend = ","; } pr_cont("%s fd%d is %s", prepend, drive, name); } *UDP = *params; } if (has_drive) pr_cont("\n"); } static void floppy_release(struct gendisk *disk, fmode_t mode) { int drive = (long)disk->private_data; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); if (!UDRS->fd_ref--) { DPRINT("floppy_release with fd_ref == 0"); UDRS->fd_ref = 0; } if (!UDRS->fd_ref) opened_bdev[drive] = NULL; mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); } /* * floppy_open check for aliasing (/dev/fd0 can be the same as * /dev/PS0 etc), and disallows simultaneous access to the same * drive with different device numbers. */ static int floppy_open(struct block_device *bdev, fmode_t mode) { int drive = (long)bdev->bd_disk->private_data; int old_dev, new_dev; int try; int res = -EBUSY; char *tmp; mutex_lock(&floppy_mutex); mutex_lock(&open_lock); old_dev = UDRS->fd_device; if (opened_bdev[drive] && opened_bdev[drive] != bdev) goto out2; if (!UDRS->fd_ref && (UDP->flags & FD_BROKEN_DCL)) { set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); } UDRS->fd_ref++; opened_bdev[drive] = bdev; res = -ENXIO; if (!floppy_track_buffer) { /* if opening an ED drive, reserve a big buffer, * else reserve a small one */ if ((UDP->cmos == 6) || (UDP->cmos == 5)) try = 64; /* Only 48 actually useful */ else try = 32; /* Only 24 actually useful */ tmp = (char *)fd_dma_mem_alloc(1024 * try); if (!tmp && !floppy_track_buffer) { try >>= 1; /* buffer only one side */ INFBOUND(try, 16); tmp = (char *)fd_dma_mem_alloc(1024 * try); } if (!tmp && !floppy_track_buffer) fallback_on_nodma_alloc(&tmp, 2048 * try); if (!tmp && !floppy_track_buffer) { DPRINT("Unable to allocate DMA memory\n"); goto out; } if (floppy_track_buffer) { if (tmp) fd_dma_mem_free((unsigned long)tmp, try * 1024); } else { buffer_min = buffer_max = -1; floppy_track_buffer = tmp; max_buffer_sectors = try; } } new_dev = MINOR(bdev->bd_dev); UDRS->fd_device = new_dev; set_capacity(disks[drive], floppy_sizes[new_dev]); if (old_dev != -1 && old_dev != new_dev) { if (buffer_drive == drive) buffer_track = -1; } if (UFDCS->rawcmd == 1) UFDCS->rawcmd = 2; if (!(mode & FMODE_NDELAY)) { if (mode & (FMODE_READ|FMODE_WRITE)) { UDRS->last_checked = 0; clear_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); check_disk_change(bdev); if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags)) goto out; if (test_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags)) goto out; } res = -EROFS; if ((mode & FMODE_WRITE) && !test_bit(FD_DISK_WRITABLE_BIT, &UDRS->flags)) goto out; } mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return 0; out: UDRS->fd_ref--; if (!UDRS->fd_ref) opened_bdev[drive] = NULL; out2: mutex_unlock(&open_lock); mutex_unlock(&floppy_mutex); return res; } /* * Check if the disk has been changed or if a change has been faked. */ static unsigned int floppy_check_events(struct gendisk *disk, unsigned int clearing) { int drive = (long)disk->private_data; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)) return DISK_EVENT_MEDIA_CHANGE; if (time_after(jiffies, UDRS->last_checked + UDP->checkfreq)) { if (lock_fdc(drive)) return 0; poll_drive(false, 0); process_fd_request(); } if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) return DISK_EVENT_MEDIA_CHANGE; return 0; } /* * This implements "read block 0" for floppy_revalidate(). * Needed for format autodetection, checking whether there is * a disk in the drive, and whether that disk is writable. */ struct rb0_cbdata { int drive; struct completion complete; }; static void floppy_rb0_cb(struct bio *bio) { struct rb0_cbdata *cbdata = (struct rb0_cbdata *)bio->bi_private; int drive = cbdata->drive; if (bio->bi_status) { pr_info("floppy: error %d while reading block 0\n", bio->bi_status); set_bit(FD_OPEN_SHOULD_FAIL_BIT, &UDRS->flags); } complete(&cbdata->complete); } static int __floppy_read_block_0(struct block_device *bdev, int drive) { struct bio bio; struct bio_vec bio_vec; struct page *page; struct rb0_cbdata cbdata; size_t size; page = alloc_page(GFP_NOIO); if (!page) { process_fd_request(); return -ENOMEM; } size = bdev->bd_block_size; if (!size) size = 1024; cbdata.drive = drive; bio_init(&bio, &bio_vec, 1); bio_set_dev(&bio, bdev); bio_add_page(&bio, page, size, 0); bio.bi_iter.bi_sector = 0; bio.bi_flags |= (1 << BIO_QUIET); bio.bi_private = &cbdata; bio.bi_end_io = floppy_rb0_cb; bio_set_op_attrs(&bio, REQ_OP_READ, 0); init_completion(&cbdata.complete); submit_bio(&bio); process_fd_request(); wait_for_completion(&cbdata.complete); __free_page(page); return 0; } /* revalidate the floppy disk, i.e. trigger format autodetection by reading * the bootblock (block 0). "Autodetection" is also needed to check whether * there is a disk in the drive at all... Thus we also do it for fixed * geometry formats */ static int floppy_revalidate(struct gendisk *disk) { int drive = (long)disk->private_data; int cf; int res = 0; if (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags) || test_bit(drive, &fake_change) || drive_no_geom(drive)) { if (WARN(atomic_read(&usage_count) == 0, "VFS: revalidate called on non-open device.\n")) return -EFAULT; res = lock_fdc(drive); if (res) return res; cf = (test_bit(FD_DISK_CHANGED_BIT, &UDRS->flags) || test_bit(FD_VERIFY_BIT, &UDRS->flags)); if (!(cf || test_bit(drive, &fake_change) || drive_no_geom(drive))) { process_fd_request(); /*already done by another thread */ return 0; } UDRS->maxblock = 0; UDRS->maxtrack = 0; if (buffer_drive == drive) buffer_track = -1; clear_bit(drive, &fake_change); clear_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); if (cf) UDRS->generation++; if (drive_no_geom(drive)) { /* auto-sensing */ res = __floppy_read_block_0(opened_bdev[drive], drive); } else { if (cf) poll_drive(false, FD_RAW_NEED_DISK); process_fd_request(); } } set_capacity(disk, floppy_sizes[UDRS->fd_device]); return res; } static const struct block_device_operations floppy_fops = { .owner = THIS_MODULE, .open = floppy_open, .release = floppy_release, .ioctl = fd_ioctl, .getgeo = fd_getgeo, .check_events = floppy_check_events, .revalidate_disk = floppy_revalidate, #ifdef CONFIG_COMPAT .compat_ioctl = fd_compat_ioctl, #endif }; /* * Floppy Driver initialization * ============================= */ /* Determine the floppy disk controller type */ /* This routine was written by David C. Niemi */ static char __init get_fdc_version(void) { int r; output_byte(FD_DUMPREGS); /* 82072 and better know DUMPREGS */ if (FDCS->reset) return FDC_NONE; r = result(); if (r <= 0x00) return FDC_NONE; /* No FDC present ??? */ if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is an 8272A\n", fdc); return FDC_8272A; /* 8272a/765 don't know DUMPREGS */ } if (r != 10) { pr_info("FDC %d init: DUMPREGS: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (!fdc_configure()) { pr_info("FDC %d is an 82072\n", fdc); return FDC_82072; /* 82072 doesn't know CONFIGURE */ } output_byte(FD_PERPENDICULAR); if (need_more_output() == MORE_OUTPUT) { output_byte(0); } else { pr_info("FDC %d is an 82072A\n", fdc); return FDC_82072A; /* 82072A as found on Sparcs. */ } output_byte(FD_UNLOCK); r = result(); if ((r == 1) && (reply_buffer[0] == 0x80)) { pr_info("FDC %d is a pre-1991 82077\n", fdc); return FDC_82077_ORIG; /* Pre-1991 82077, doesn't know * LOCK/UNLOCK */ } if ((r != 1) || (reply_buffer[0] != 0x00)) { pr_info("FDC %d init: UNLOCK: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } output_byte(FD_PARTID); r = result(); if (r != 1) { pr_info("FDC %d init: PARTID: unexpected return of %d bytes.\n", fdc, r); return FDC_UNKNOWN; } if (reply_buffer[0] == 0x80) { pr_info("FDC %d is a post-1991 82077\n", fdc); return FDC_82077; /* Revised 82077AA passes all the tests */ } switch (reply_buffer[0] >> 5) { case 0x0: /* Either a 82078-1 or a 82078SL running at 5Volt */ pr_info("FDC %d is an 82078.\n", fdc); return FDC_82078; case 0x1: pr_info("FDC %d is a 44pin 82078\n", fdc); return FDC_82078; case 0x2: pr_info("FDC %d is a S82078B\n", fdc); return FDC_S82078B; case 0x3: pr_info("FDC %d is a National Semiconductor PC87306\n", fdc); return FDC_87306; default: pr_info("FDC %d init: 82078 variant with unknown PARTID=%d.\n", fdc, reply_buffer[0] >> 5); return FDC_82078_UNKN; } } /* get_fdc_version */ /* lilo configuration */ static void __init floppy_set_flags(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) default_drive_params[i].params.flags |= param2; else default_drive_params[i].params.flags &= ~param2; } DPRINT("%s flag 0x%x\n", param2 ? "Setting" : "Clearing", param); } static void __init daring(int *ints, int param, int param2) { int i; for (i = 0; i < ARRAY_SIZE(default_drive_params); i++) { if (param) { default_drive_params[i].params.select_delay = 0; default_drive_params[i].params.flags |= FD_SILENT_DCL_CLEAR; } else { default_drive_params[i].params.select_delay = 2 * HZ / 100; default_drive_params[i].params.flags &= ~FD_SILENT_DCL_CLEAR; } } DPRINT("Assuming %s floppy hardware\n", param ? "standard" : "broken"); } static void __init set_cmos(int *ints, int dummy, int dummy2) { int current_drive = 0; if (ints[0] != 2) { DPRINT("wrong number of parameters for CMOS\n"); return; } current_drive = ints[1]; if (current_drive < 0 || current_drive >= 8) { DPRINT("bad drive for set_cmos\n"); return; } #if N_FDC > 1 if (current_drive >= 4 && !FDC2) FDC2 = 0x370; #endif DP->cmos = ints[2]; DPRINT("setting CMOS code to %d\n", ints[2]); } static struct param_table { const char *name; void (*fn) (int *ints, int param, int param2); int *var; int def_param; int param2; } config_params[] __initdata = { {"allowed_drive_mask", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"all_drives", NULL, &allowed_drive_mask, 0xff, 0}, /* obsolete */ {"asus_pci", NULL, &allowed_drive_mask, 0x33, 0}, {"irq", NULL, &FLOPPY_IRQ, 6, 0}, {"dma", NULL, &FLOPPY_DMA, 2, 0}, {"daring", daring, NULL, 1, 0}, #if N_FDC > 1 {"two_fdc", NULL, &FDC2, 0x370, 0}, {"one_fdc", NULL, &FDC2, 0, 0}, #endif {"thinkpad", floppy_set_flags, NULL, 1, FD_INVERTED_DCL}, {"broken_dcl", floppy_set_flags, NULL, 1, FD_BROKEN_DCL}, {"messages", floppy_set_flags, NULL, 1, FTD_MSG}, {"silent_dcl_clear", floppy_set_flags, NULL, 1, FD_SILENT_DCL_CLEAR}, {"debug", floppy_set_flags, NULL, 1, FD_DEBUG}, {"nodma", NULL, &can_use_virtual_dma, 1, 0}, {"omnibook", NULL, &can_use_virtual_dma, 1, 0}, {"yesdma", NULL, &can_use_virtual_dma, 0, 0}, {"fifo_depth", NULL, &fifo_depth, 0xa, 0}, {"nofifo", NULL, &no_fifo, 0x20, 0}, {"usefifo", NULL, &no_fifo, 0, 0}, {"cmos", set_cmos, NULL, 0, 0}, {"slow", NULL, &slow_floppy, 1, 0}, {"unexpected_interrupts", NULL, &print_unex, 1, 0}, {"no_unexpected_interrupts", NULL, &print_unex, 0, 0}, {"L40SX", NULL, &print_unex, 0, 0} EXTRA_FLOPPY_PARAMS }; static int __init floppy_setup(char *str) { int i; int param; int ints[11]; str = get_options(str, ARRAY_SIZE(ints), ints); if (str) { for (i = 0; i < ARRAY_SIZE(config_params); i++) { if (strcmp(str, config_params[i].name) == 0) { if (ints[0]) param = ints[1]; else param = config_params[i].def_param; if (config_params[i].fn) config_params[i].fn(ints, param, config_params[i]. param2); if (config_params[i].var) { DPRINT("%s=%d\n", str, param); *config_params[i].var = param; } return 1; } } } if (str) { DPRINT("unknown floppy option [%s]\n", str); DPRINT("allowed options are:"); for (i = 0; i < ARRAY_SIZE(config_params); i++) pr_cont(" %s", config_params[i].name); pr_cont("\n"); } else DPRINT("botched floppy option\n"); DPRINT("Read Documentation/blockdev/floppy.txt\n"); return 0; } static int have_no_fdc = -ENODEV; static ssize_t floppy_cmos_show(struct device *dev, struct device_attribute *attr, char *buf) { struct platform_device *p = to_platform_device(dev); int drive; drive = p->id; return sprintf(buf, "%X\n", UDP->cmos); } static DEVICE_ATTR(cmos, 0444, floppy_cmos_show, NULL); static struct attribute *floppy_dev_attrs[] = { &dev_attr_cmos.attr, NULL }; ATTRIBUTE_GROUPS(floppy_dev); static void floppy_device_release(struct device *dev) { } static int floppy_resume(struct device *dev) { int fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) user_reset_fdc(-1, FD_RESET_ALWAYS, false); return 0; } static const struct dev_pm_ops floppy_pm_ops = { .resume = floppy_resume, .restore = floppy_resume, }; static struct platform_driver floppy_driver = { .driver = { .name = "floppy", .pm = &floppy_pm_ops, }, }; static const struct blk_mq_ops floppy_mq_ops = { .queue_rq = floppy_queue_rq, }; static struct platform_device floppy_device[N_DRIVE]; static bool floppy_available(int drive) { if (!(allowed_drive_mask & (1 << drive))) return false; if (fdc_state[FDC(drive)].version == FDC_NONE) return false; return true; } static struct kobject *floppy_find(dev_t dev, int *part, void *data) { int drive = (*part & 3) | ((*part & 0x80) >> 5); if (drive >= N_DRIVE || !floppy_available(drive)) return NULL; if (((*part >> 2) & 0x1f) >= ARRAY_SIZE(floppy_type)) return NULL; *part = 0; return get_disk_and_module(disks[drive]); } static int __init do_floppy_init(void) { int i, unit, drive, err; set_debugt(); interruptjiffies = resultjiffies = jiffies; #if defined(CONFIG_PPC) if (check_legacy_ioport(FDC1)) return -ENODEV; #endif raw_cmd = NULL; floppy_wq = alloc_ordered_workqueue("floppy", 0); if (!floppy_wq) return -ENOMEM; for (drive = 0; drive < N_DRIVE; drive++) { disks[drive] = alloc_disk(1); if (!disks[drive]) { err = -ENOMEM; goto out_put_disk; } disks[drive]->queue = blk_mq_init_sq_queue(&tag_sets[drive], &floppy_mq_ops, 2, BLK_MQ_F_SHOULD_MERGE); if (IS_ERR(disks[drive]->queue)) { err = PTR_ERR(disks[drive]->queue); disks[drive]->queue = NULL; goto out_put_disk; } blk_queue_bounce_limit(disks[drive]->queue, BLK_BOUNCE_HIGH); blk_queue_max_hw_sectors(disks[drive]->queue, 64); disks[drive]->major = FLOPPY_MAJOR; disks[drive]->first_minor = TOMINOR(drive); disks[drive]->fops = &floppy_fops; disks[drive]->events = DISK_EVENT_MEDIA_CHANGE; sprintf(disks[drive]->disk_name, "fd%d", drive); timer_setup(&motor_off_timer[drive], motor_off_callback, 0); } err = register_blkdev(FLOPPY_MAJOR, "fd"); if (err) goto out_put_disk; err = platform_driver_register(&floppy_driver); if (err) goto out_unreg_blkdev; blk_register_region(MKDEV(FLOPPY_MAJOR, 0), 256, THIS_MODULE, floppy_find, NULL, NULL); for (i = 0; i < 256; i++) if (ITYPE(i)) floppy_sizes[i] = floppy_type[ITYPE(i)].size; else floppy_sizes[i] = MAX_DISK_SIZE << 1; reschedule_timeout(MAXTIMEOUT, "floppy init"); config_types(); for (i = 0; i < N_FDC; i++) { fdc = i; memset(FDCS, 0, sizeof(*FDCS)); FDCS->dtr = -1; FDCS->dor = 0x4; #if defined(__sparc__) || defined(__mc68000__) /*sparcs/sun3x don't have a DOR reset which we can fall back on to */ #ifdef __mc68000__ if (MACH_IS_SUN3X) #endif FDCS->version = FDC_82072A; #endif } use_virtual_dma = can_use_virtual_dma & 1; fdc_state[0].address = FDC1; if (fdc_state[0].address == -1) { cancel_delayed_work(&fd_timeout); err = -ENODEV; goto out_unreg_region; } #if N_FDC > 1 fdc_state[1].address = FDC2; #endif fdc = 0; /* reset fdc in case of unexpected interrupt */ err = floppy_grab_irq_and_dma(); if (err) { cancel_delayed_work(&fd_timeout); err = -EBUSY; goto out_unreg_region; } /* initialise drive state */ for (drive = 0; drive < N_DRIVE; drive++) { memset(UDRS, 0, sizeof(*UDRS)); memset(UDRWE, 0, sizeof(*UDRWE)); set_bit(FD_DISK_NEWCHANGE_BIT, &UDRS->flags); set_bit(FD_DISK_CHANGED_BIT, &UDRS->flags); set_bit(FD_VERIFY_BIT, &UDRS->flags); UDRS->fd_device = -1; floppy_track_buffer = NULL; max_buffer_sectors = 0; } /* * Small 10 msec delay to let through any interrupt that * initialization might have triggered, to not * confuse detection: */ msleep(10); for (i = 0; i < N_FDC; i++) { fdc = i; FDCS->driver_version = FD_DRIVER_VERSION; for (unit = 0; unit < 4; unit++) FDCS->track[unit] = 0; if (FDCS->address == -1) continue; FDCS->rawcmd = 2; if (user_reset_fdc(-1, FD_RESET_ALWAYS, false)) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; FDCS->version = FDC_NONE; continue; } /* Try to determine the floppy controller type */ FDCS->version = get_fdc_version(); if (FDCS->version == FDC_NONE) { /* free ioports reserved by floppy_grab_irq_and_dma() */ floppy_release_regions(fdc); FDCS->address = -1; continue; } if (can_use_virtual_dma == 2 && FDCS->version < FDC_82072A) can_use_virtual_dma = 0; have_no_fdc = 0; /* Not all FDCs seem to be able to handle the version command * properly, so force a reset for the standard FDC clones, * to avoid interrupt garbage. */ user_reset_fdc(-1, FD_RESET_ALWAYS, false); } fdc = 0; cancel_delayed_work(&fd_timeout); current_drive = 0; initialized = true; if (have_no_fdc) { DPRINT("no floppy controllers found\n"); err = have_no_fdc; goto out_release_dma; } for (drive = 0; drive < N_DRIVE; drive++) { if (!floppy_available(drive)) continue; floppy_device[drive].name = floppy_device_name; floppy_device[drive].id = drive; floppy_device[drive].dev.release = floppy_device_release; floppy_device[drive].dev.groups = floppy_dev_groups; err = platform_device_register(&floppy_device[drive]); if (err) goto out_remove_drives; /* to be cleaned up... */ disks[drive]->private_data = (void *)(long)drive; disks[drive]->flags |= GENHD_FL_REMOVABLE; device_add_disk(&floppy_device[drive].dev, disks[drive], NULL); } return 0; out_remove_drives: while (drive--) { if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } } out_release_dma: if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); out_unreg_region: blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); platform_driver_unregister(&floppy_driver); out_unreg_blkdev: unregister_blkdev(FLOPPY_MAJOR, "fd"); out_put_disk: destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { if (!disks[drive]) break; if (disks[drive]->queue) { del_timer_sync(&motor_off_timer[drive]); blk_cleanup_queue(disks[drive]->queue); disks[drive]->queue = NULL; blk_mq_free_tag_set(&tag_sets[drive]); } put_disk(disks[drive]); } return err; } #ifndef MODULE static __init void floppy_async_init(void *data, async_cookie_t cookie) { do_floppy_init(); } #endif static int __init floppy_init(void) { #ifdef MODULE return do_floppy_init(); #else /* Don't hold up the bootup by the floppy initialization */ async_schedule(floppy_async_init, NULL); return 0; #endif } static const struct io_region { int offset; int size; } io_regions[] = { { 2, 1 }, /* address + 3 is sometimes reserved by pnp bios for motherboard */ { 4, 2 }, /* address + 6 is reserved, and may be taken by IDE. * Unfortunately, Adaptec doesn't know this :-(, */ { 7, 1 }, }; static void floppy_release_allocated_regions(int fdc, const struct io_region *p) { while (p != io_regions) { p--; release_region(FDCS->address + p->offset, p->size); } } #define ARRAY_END(X) (&((X)[ARRAY_SIZE(X)])) static int floppy_request_regions(int fdc) { const struct io_region *p; for (p = io_regions; p < ARRAY_END(io_regions); p++) { if (!request_region(FDCS->address + p->offset, p->size, "floppy")) { DPRINT("Floppy io-port 0x%04lx in use\n", FDCS->address + p->offset); floppy_release_allocated_regions(fdc, p); return -EBUSY; } } return 0; } static void floppy_release_regions(int fdc) { floppy_release_allocated_regions(fdc, ARRAY_END(io_regions)); } static int floppy_grab_irq_and_dma(void) { if (atomic_inc_return(&usage_count) > 1) return 0; /* * We might have scheduled a free_irq(), wait it to * drain first: */ flush_workqueue(floppy_wq); if (fd_request_irq()) { DPRINT("Unable to grab IRQ%d for the floppy driver\n", FLOPPY_IRQ); atomic_dec(&usage_count); return -1; } if (fd_request_dma()) { DPRINT("Unable to grab DMA%d for the floppy driver\n", FLOPPY_DMA); if (can_use_virtual_dma & 2) use_virtual_dma = can_use_virtual_dma = 1; if (!(can_use_virtual_dma & 1)) { fd_free_irq(); atomic_dec(&usage_count); return -1; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { if (floppy_request_regions(fdc)) goto cleanup; } } for (fdc = 0; fdc < N_FDC; fdc++) { if (FDCS->address != -1) { reset_fdc_info(1); fd_outb(FDCS->dor, FD_DOR); } } fdc = 0; set_dor(0, ~0, 8); /* avoid immediate interrupt */ for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) fd_outb(FDCS->dor, FD_DOR); /* * The driver will try and free resources and relies on us * to know if they were allocated or not. */ fdc = 0; irqdma_allocated = 1; return 0; cleanup: fd_free_irq(); fd_free_dma(); while (--fdc >= 0) floppy_release_regions(fdc); atomic_dec(&usage_count); return -1; } static void floppy_release_irq_and_dma(void) { int old_fdc; #ifndef __sparc__ int drive; #endif long tmpsize; unsigned long tmpaddr; if (!atomic_dec_and_test(&usage_count)) return; if (irqdma_allocated) { fd_disable_dma(); fd_free_dma(); fd_free_irq(); irqdma_allocated = 0; } set_dor(0, ~0, 8); #if N_FDC > 1 set_dor(1, ~8, 0); #endif if (floppy_track_buffer && max_buffer_sectors) { tmpsize = max_buffer_sectors * 1024; tmpaddr = (unsigned long)floppy_track_buffer; floppy_track_buffer = NULL; max_buffer_sectors = 0; buffer_min = buffer_max = -1; fd_dma_mem_free(tmpaddr, tmpsize); } #ifndef __sparc__ for (drive = 0; drive < N_FDC * 4; drive++) if (timer_pending(motor_off_timer + drive)) pr_info("motor off timer %d still active\n", drive); #endif if (delayed_work_pending(&fd_timeout)) pr_info("floppy timer still active:%s\n", timeout_message); if (delayed_work_pending(&fd_timer)) pr_info("auxiliary floppy timer still active\n"); if (work_pending(&floppy_work)) pr_info("work still pending\n"); old_fdc = fdc; for (fdc = 0; fdc < N_FDC; fdc++) if (FDCS->address != -1) floppy_release_regions(fdc); fdc = old_fdc; } #ifdef MODULE static char *floppy; static void __init parse_floppy_cfg_string(char *cfg) { char *ptr; while (*cfg) { ptr = cfg; while (*cfg && *cfg != ' ' && *cfg != '\t') cfg++; if (*cfg) { *cfg = '\0'; cfg++; } if (*ptr) floppy_setup(ptr); } } static int __init floppy_module_init(void) { if (floppy) parse_floppy_cfg_string(floppy); return floppy_init(); } module_init(floppy_module_init); static void __exit floppy_module_exit(void) { int drive; blk_unregister_region(MKDEV(FLOPPY_MAJOR, 0), 256); unregister_blkdev(FLOPPY_MAJOR, "fd"); platform_driver_unregister(&floppy_driver); destroy_workqueue(floppy_wq); for (drive = 0; drive < N_DRIVE; drive++) { del_timer_sync(&motor_off_timer[drive]); if (floppy_available(drive)) { del_gendisk(disks[drive]); platform_device_unregister(&floppy_device[drive]); } blk_cleanup_queue(disks[drive]->queue); blk_mq_free_tag_set(&tag_sets[drive]); /* * These disks have not called add_disk(). Don't put down * queue reference in put_disk(). */ if (!(allowed_drive_mask & (1 << drive)) || fdc_state[FDC(drive)].version == FDC_NONE) disks[drive]->queue = NULL; put_disk(disks[drive]); } cancel_delayed_work_sync(&fd_timeout); cancel_delayed_work_sync(&fd_timer); if (atomic_read(&usage_count)) floppy_release_irq_and_dma(); /* eject disk, if any */ fd_eject(0); } module_exit(floppy_module_exit); module_param(floppy, charp, 0); module_param(FLOPPY_IRQ, int, 0); module_param(FLOPPY_DMA, int, 0); MODULE_AUTHOR("Alain L. Knaff"); MODULE_SUPPORTED_DEVICE("fd"); MODULE_LICENSE("GPL"); /* This doesn't actually get used other than for module information */ static const struct pnp_device_id floppy_pnpids[] = { {"PNP0700", 0}, {} }; MODULE_DEVICE_TABLE(pnp, floppy_pnpids); #else __setup("floppy=", floppy_setup); module_init(floppy_init) #endif MODULE_ALIAS_BLOCKDEV_MAJOR(FLOPPY_MAJOR);
./CrossVul/dataset_final_sorted/CWE-190/c/good_966_0
crossvul-cpp_data_bad_401_3
/* * Description: * History: yang@haipo.me, 2017/04/26, create */ # include <stdbool.h> # include <openssl/sha.h> # include "ut_log.h" # include "ut_misc.h" # include "ut_base64.h" # include "ut_ws_svr.h" struct ws_frame { uint8_t fin; uint8_t opcode; uint64_t payload_len; void *payload; }; struct clt_info { nw_ses *ses; void *privdata; double last_activity; struct http_parser parser; sds field; bool field_set; sds value; bool value_set; bool upgrade; sds remote; sds url; sds message; http_request_t *request; struct ws_frame frame; }; static int on_http_message_begin(http_parser* parser) { struct clt_info *info = parser->data; if (info->request) http_request_release(info->request); info->request = http_request_new(); if (info->request == NULL) { return -__LINE__; } return 0; } static int send_hand_shake_reply(nw_ses *ses, char *protocol, const char *key) { unsigned char hash[20]; sds data = sdsnew(key); data = sdscat(data, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); SHA1((const unsigned char *)data, sdslen(data), hash); sdsfree(data); sds b4message; base64_encode(hash, sizeof(hash), &b4message); http_response_t *response = http_response_new(); http_response_set_header(response, "Upgrade", "websocket"); http_response_set_header(response, "Connection", "Upgrade"); http_response_set_header(response, "Sec-WebSocket-Accept", b4message); if (protocol) { http_response_set_header(response, "Sec-WebSocket-Protocol", protocol); } response->status = 101; sds message = http_response_encode(response); nw_ses_send(ses, message, sdslen(message)); sdsfree(message); sdsfree(b4message); return 0; } static bool is_good_protocol(const char *protocol_list, const char *protocol) { char *tmp = strdup(protocol_list); char *pch = strtok(tmp, ", "); while (pch != NULL) { if (strcmp(pch, protocol) == 0) { free(tmp); return true; } pch = strtok(NULL, ", "); } free(tmp); return false; } static bool is_good_origin(const char *origin, const char *require) { size_t origin_len = strlen(origin); size_t require_len = strlen(require); if (origin_len < require_len) return false; if (memcmp(origin + (origin_len - require_len), require, require_len) != 0) return false; return true; } static int on_http_message_complete(http_parser* parser) { struct clt_info *info = parser->data; ws_svr *svr = ws_svr_from_ses(info->ses); info->request->version_major = parser->http_major; info->request->version_minor = parser->http_minor; info->request->method = parser->method; dict_entry *entry; dict_iterator *iter = dict_get_iterator(info->request->headers); while ((entry = dict_next(iter)) != NULL) { log_trace("Header: %s: %s", (char *)entry->key, (char *)entry->val); } dict_release_iterator(iter); if (info->request->method != HTTP_GET) goto error; if (http_request_get_header(info->request, "Host") == NULL) goto error; double version = info->request->version_major + info->request->version_minor * 0.1; if (version < 1.1) goto error; const char *upgrade = http_request_get_header(info->request, "Upgrade"); if (upgrade == NULL || strcasecmp(upgrade, "websocket") != 0) goto error; const char *connection = http_request_get_header(info->request, "Connection"); if (connection == NULL) goto error; else { bool found_upgrade = false; int count; sds *tokens = sdssplitlen(connection, strlen(connection), ",", 1, &count); if (tokens == NULL) goto error; for (int i = 0; i < count; i++) { sds token = tokens[i]; sdstrim(token, " "); if (strcasecmp(token, "Upgrade") == 0) { found_upgrade = true; break; } } sdsfreesplitres(tokens, count); if (!found_upgrade) goto error; } const char *ws_version = http_request_get_header(info->request, "Sec-WebSocket-Version"); if (ws_version == NULL || strcmp(ws_version, "13") != 0) goto error; const char *ws_key = http_request_get_header(info->request, "Sec-WebSocket-Key"); if (ws_key == NULL) goto error; const char *protocol_list = http_request_get_header(info->request, "Sec-WebSocket-Protocol"); if (protocol_list && !is_good_protocol(protocol_list, svr->protocol)) goto error; if (strlen(svr->origin) > 0) { const char *origin = http_request_get_header(info->request, "Origin"); if (origin == NULL || !is_good_origin(origin, svr->origin)) goto error; } if (svr->type.on_privdata_alloc) { info->privdata = svr->type.on_privdata_alloc(svr); if (info->privdata == NULL) goto error; } info->upgrade = true; info->remote = sdsnew(http_get_remote_ip(info->ses, info->request)); info->url = sdsnew(info->request->url); if (svr->type.on_upgrade) { svr->type.on_upgrade(info->ses, info->remote); } if (protocol_list) { send_hand_shake_reply(info->ses, svr->protocol, ws_key); } else { send_hand_shake_reply(info->ses, NULL, ws_key); } return 0; error: ws_svr_close_clt(ws_svr_from_ses(info->ses), info->ses); return -1; } static int on_http_url(http_parser* parser, const char* at, size_t length) { struct clt_info *info = parser->data; if (info->request->url) sdsfree(info->request->url); info->request->url = sdsnewlen(at, length); return 0; } static int on_http_header_field(http_parser* parser, const char* at, size_t length) { struct clt_info *info = parser->data; info->field_set = true; if (info->field == NULL) { info->field = sdsnewlen(at, length); } else { info->field = sdscpylen(info->field, at, length); } return 0; } static int on_http_header_value(http_parser* parser, const char* at, size_t length) { struct clt_info *info = parser->data; info->value_set = true; if (info->value == NULL) { info->value = sdsnewlen(at, length); } else { info->value = sdscpylen(info->value, at, length); } if (info->field_set && info->value_set) { http_request_set_header(info->request, info->field, info->value); info->field_set = false; info->value_set = false; } return 0; } static int on_http_body(http_parser* parser, const char* at, size_t length) { struct clt_info *info = parser->data; info->request->body = sdsnewlen(at, length); return 0; } static bool is_good_opcode(uint8_t opcode) { static uint8_t good_list[] = { 0x0, 0x1, 0x2, 0x8, 0x9, 0xa }; for (size_t i = 0; i < sizeof(good_list); ++i) { if (opcode == good_list[i]) return true; } return false; } static int decode_pkg(nw_ses *ses, void *data, size_t max) { struct clt_info *info = ses->privdata; if (!info->upgrade) { return max; } if (max < 2) return 0; uint8_t *p = data; size_t pkg_size = 0; memset(&info->frame, 0, sizeof(info->frame)); info->frame.fin = p[0] & 0x80; info->frame.opcode = p[0] & 0x0f; if (!is_good_opcode(info->frame.opcode)) return -1; uint8_t mask = p[1] & 0x80; if (mask == 0) return -1; uint8_t len = p[1] & 0x7f; if (len < 126) { pkg_size = 2; info->frame.payload_len = len; } else if (len == 126) { pkg_size = 2 + 2; if (max < pkg_size) return 0; info->frame.payload_len = be16toh(*(uint16_t *)(p + 2)); } else if (len == 127) { pkg_size = 2 + 8; if (max < pkg_size) return 0; info->frame.payload_len = be64toh(*(uint64_t *)(p + 2)); } uint8_t masks[4]; memcpy(masks, p + pkg_size, sizeof(masks)); pkg_size += sizeof(masks); info->frame.payload = p + pkg_size; pkg_size += info->frame.payload_len; if (max < pkg_size) return 0; p = info->frame.payload; for (size_t i = 0; i < info->frame.payload_len; ++i) { p[i] = p[i] ^ masks[i & 3]; } return pkg_size; } static void on_error_msg(nw_ses *ses, const char *msg) { log_error("peer: %s: %s", nw_sock_human_addr(&ses->peer_addr), msg); } static void on_new_connection(nw_ses *ses) { log_trace("new connection from: %s", nw_sock_human_addr(&ses->peer_addr)); struct clt_info *info = ses->privdata; memset(info, 0, sizeof(struct clt_info)); info->ses = ses; info->last_activity = current_timestamp(); http_parser_init(&info->parser, HTTP_REQUEST); info->parser.data = info; } static void on_connection_close(nw_ses *ses) { log_trace("connection %s close", nw_sock_human_addr(&ses->peer_addr)); struct clt_info *info = ses->privdata; struct ws_svr *svr = ws_svr_from_ses(ses); if (info->upgrade) { if (svr->type.on_close) { svr->type.on_close(ses, info->remote); } if (svr->type.on_privdata_free) { svr->type.on_privdata_free(svr, info->privdata); } } } static void *on_privdata_alloc(void *svr) { ws_svr *w_svr = ((nw_svr *)svr)->privdata; return nw_cache_alloc(w_svr->privdata_cache); } static void on_privdata_free(void *svr, void *privdata) { struct clt_info *info = privdata; if (info->field) { sdsfree(info->field); } if (info->value) { sdsfree(info->value); } if (info->remote) { sdsfree(info->remote); } if (info->url) { sdsfree(info->url); } if (info->message) { sdsfree(info->message); } if (info->request) { http_request_release(info->request); } ws_svr *w_svr = ((nw_svr *)svr)->privdata; nw_cache_free(w_svr->privdata_cache, privdata); } static int send_reply(nw_ses *ses, uint8_t opcode, void *payload, size_t payload_len) { if (payload == NULL) payload_len = 0; static void *buf; static size_t buf_size = 1024; if (buf == NULL) { buf = malloc(1024); if (buf == NULL) return -1; } size_t require_len = 10 + payload_len; if (buf_size < require_len) { void *new = realloc(buf, require_len); if (new == NULL) return -1; buf = new; buf_size = require_len; } size_t pkg_len = 0; uint8_t *p = buf; p[0] = 0; p[0] |= 0x1 << 7; p[0] |= opcode; p[1] = 0; if (payload_len < 126) { uint8_t len = payload_len; p[1] |= len; pkg_len = 2; } else if (payload_len <= 0xffff) { p[1] |= 126; uint16_t len = htobe16((uint16_t)payload_len); memcpy(p + 2, &len, sizeof(len)); pkg_len = 2 + sizeof(len); } else { p[1] |= 127; uint64_t len = htobe64(payload_len); memcpy(p + 2, &len, sizeof(len)); pkg_len = 2 + sizeof(len); } if (payload) { memcpy(p + pkg_len, payload, payload_len); pkg_len += payload_len; } return nw_ses_send(ses, buf, pkg_len); } static int send_pong_message(nw_ses *ses) { return send_reply(ses, 0xa, NULL, 0); } static void on_recv_pkg(nw_ses *ses, void *data, size_t size) { struct clt_info *info = ses->privdata; ws_svr *svr = ws_svr_from_ses(ses); info->last_activity = current_timestamp(); if (!info->upgrade) { size_t nparsed = http_parser_execute(&info->parser, &svr->settings, data, size); if (!info->parser.upgrade && nparsed != size) { log_error("peer: %s http parse error: %s (%s)", nw_sock_human_addr(&ses->peer_addr), http_errno_description(HTTP_PARSER_ERRNO(&info->parser)), http_errno_name(HTTP_PARSER_ERRNO(&info->parser))); nw_svr_close_clt(svr->raw_svr, ses); } return; } switch (info->frame.opcode) { case 0x8: nw_svr_close_clt(svr->raw_svr, ses); return; case 0x9: send_pong_message(ses); return; case 0xa: return; } if (info->message == NULL) info->message = sdsempty(); info->message = sdscatlen(info->message, info->frame.payload, info->frame.payload_len); if (info->frame.fin) { int ret = svr->type.on_message(ses, info->remote, info->url, info->message, sdslen(info->message)); if (ses->id != 0) { if (ret < 0) { nw_svr_close_clt(svr->raw_svr, ses); } else { sdsfree(info->message); info->message = NULL; } } } } static void on_timer(nw_timer *timer, void *privdata) { ws_svr *svr = privdata; double now = current_timestamp(); nw_ses *curr = svr->raw_svr->clt_list_head; nw_ses *next; while (curr) { next = curr->next; struct clt_info *info = curr->privdata; if (now - info->last_activity > svr->keep_alive) { log_error("peer: %s: last_activity: %f, idle too long", nw_sock_human_addr(&curr->peer_addr), info->last_activity); nw_svr_close_clt(svr->raw_svr, curr); } curr = next; } } ws_svr *ws_svr_create(ws_svr_cfg *cfg, ws_svr_type *type) { if (type->on_message == NULL) return NULL; if (type->on_privdata_alloc && !type->on_privdata_free) return NULL; ws_svr *svr = malloc(sizeof(ws_svr)); memset(svr, 0, sizeof(ws_svr)); nw_svr_cfg raw_cfg; memset(&raw_cfg, 0, sizeof(raw_cfg)); raw_cfg.bind_count = cfg->bind_count; raw_cfg.bind_arr = cfg->bind_arr; raw_cfg.max_pkg_size = cfg->max_pkg_size; raw_cfg.buf_limit = cfg->buf_limit; raw_cfg.read_mem = cfg->read_mem; raw_cfg.write_mem = cfg->write_mem; nw_svr_type st; memset(&st, 0, sizeof(st)); st.decode_pkg = decode_pkg; st.on_error_msg = on_error_msg; st.on_new_connection = on_new_connection; st.on_connection_close = on_connection_close; st.on_recv_pkg = on_recv_pkg; st.on_privdata_alloc = on_privdata_alloc; st.on_privdata_free = on_privdata_free; svr->raw_svr = nw_svr_create(&raw_cfg, &st, svr); if (svr->raw_svr == NULL) { free(svr); return NULL; } memset(&svr->settings, 0, sizeof(http_parser_settings)); svr->settings.on_message_begin = on_http_message_begin; svr->settings.on_url = on_http_url; svr->settings.on_header_field = on_http_header_field; svr->settings.on_header_value = on_http_header_value; svr->settings.on_body = on_http_body; svr->settings.on_message_complete = on_http_message_complete; svr->keep_alive = cfg->keep_alive; svr->protocol = strdup(cfg->protocol); svr->origin = strdup(cfg->origin); svr->privdata_cache = nw_cache_create(sizeof(struct clt_info)); memcpy(&svr->type, type, sizeof(ws_svr_type)); if (cfg->keep_alive > 0) { nw_timer_set(&svr->timer, 60, true, on_timer, svr); nw_timer_start(&svr->timer); } return svr; } int ws_svr_start(ws_svr *svr) { int ret = nw_svr_start(svr->raw_svr); if (ret < 0) return ret; return 0; } int ws_svr_stop(ws_svr *svr) { int ret = nw_svr_stop(svr->raw_svr); if (ret < 0) return ret; return 0; } ws_svr *ws_svr_from_ses(nw_ses *ses) { return ((nw_svr *)ses->svr)->privdata; } void *ws_ses_privdata(nw_ses *ses) { struct clt_info *info = ses->privdata; return info->privdata; } int ws_send_text(nw_ses *ses, char *message) { return send_reply(ses, 0x1, message, strlen(message)); } int ws_send_binary(nw_ses *ses, void *data, size_t size) { return send_reply(ses, 0x2, data, size); } static int broadcast_message(ws_svr *svr, uint8_t opcode, void *data, size_t size) { nw_ses *curr = svr->raw_svr->clt_list_head; while (curr) { nw_ses *next = curr->next; struct clt_info *info = curr->privdata; if (info->upgrade) { int ret = send_reply(curr, opcode, data, size); if (ret < 0) return ret; } curr = next; } return 0; } int ws_svr_broadcast_text(ws_svr *svr, char *message) { return broadcast_message(svr, 0x1, message, strlen(message)); } int ws_svr_broadcast_binary(ws_svr *svr, void *data, size_t size) { return broadcast_message(svr, 0x2, data, size); } void ws_svr_close_clt(ws_svr *svr, nw_ses *ses) { nw_svr_close_clt(svr->raw_svr, ses); } void ws_svr_release(ws_svr *svr) { nw_svr_release(svr->raw_svr); nw_timer_stop(&svr->timer); nw_cache_release(svr->privdata_cache); free(svr->protocol); free(svr); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_401_3
crossvul-cpp_data_bad_1203_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1203_0
crossvul-cpp_data_bad_401_0
/* * Description: network buf manager * History: yang@haipo.me, 2016/03/16, create */ # include <errno.h> # include <string.h> # include "nw_buf.h" # define NW_BUF_POOL_INIT_SIZE 64 # define NW_CACHE_INIT_SIZE 64 size_t nw_buf_size(nw_buf *buf) { return buf->wpos - buf->rpos; } size_t nw_buf_avail(nw_buf *buf) { return buf->size - buf->wpos; } size_t nw_buf_write(nw_buf *buf, const void *data, size_t len) { size_t available = buf->size - buf->wpos; size_t wlen = len > available ? available : len; memcpy(buf->data + buf->wpos, data, wlen); buf->wpos += wlen; return wlen; } void nw_buf_shift(nw_buf *buf) { if (buf->rpos == buf->wpos) { buf->rpos = buf->wpos = 0; } else if (buf->rpos != 0) { memmove(buf->data, buf->data + buf->rpos, buf->wpos - buf->rpos); buf->wpos -= buf->rpos; buf->rpos = 0; } } nw_buf_pool *nw_buf_pool_create(uint32_t size) { nw_buf_pool *pool = malloc(sizeof(nw_buf_pool)); if (pool == NULL) return NULL; pool->size = size; pool->used = 0; pool->free = 0; pool->free_total = NW_BUF_POOL_INIT_SIZE; pool->free_arr = malloc(pool->free_total * sizeof(nw_buf *)); if (pool->free_arr == NULL) { free(pool); return NULL; } return pool; } nw_buf *nw_buf_alloc(nw_buf_pool *pool) { if (pool->free) { nw_buf *buf = pool->free_arr[--pool->free]; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } nw_buf *buf = malloc(sizeof(nw_buf) + pool->size); if (buf == NULL) return NULL; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } } void nw_buf_pool_release(nw_buf_pool *pool) { for (uint32_t i = 0; i < pool->free; ++i) { free(pool->free_arr[i]); } free(pool->free_arr); free(pool); } nw_buf_list *nw_buf_list_create(nw_buf_pool *pool, uint32_t limit) { nw_buf_list *list = malloc(sizeof(nw_buf_list)); if (list == NULL) return NULL; list->pool = pool; list->count = 0; list->limit = limit; list->head = NULL; list->tail = NULL; return list; } size_t nw_buf_list_write(nw_buf_list *list, const void *data, size_t len) { const void *pos = data; size_t left = len; if (list->tail && nw_buf_avail(list->tail)) { size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } while (left) { if (list->limit && list->count >= list->limit) return len - left; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return len - left; if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } return len; } size_t nw_buf_list_append(nw_buf_list *list, const void *data, size_t len) { if (list->limit && list->count >= list->limit) return 0; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return 0; if (len > buf->size) { nw_buf_free(list->pool, buf); return 0; } nw_buf_write(buf, data, len); if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; return len; } void nw_buf_list_shift(nw_buf_list *list) { if (list->head) { nw_buf *tmp = list->head; list->head = tmp->next; if (list->head == NULL) { list->tail = NULL; } list->count--; nw_buf_free(list->pool, tmp); } } void nw_buf_list_release(nw_buf_list *list) { nw_buf *curr = list->head; nw_buf *next = NULL; while (curr) { next = curr->next; nw_buf_free(list->pool, curr); curr = next; } free(list); } nw_cache *nw_cache_create(uint32_t size) { nw_cache *cache = malloc(sizeof(nw_cache)); if (cache == NULL) return NULL; cache->size = size; cache->used = 0; cache->free = 0; cache->free_total = NW_CACHE_INIT_SIZE; cache->free_arr = malloc(cache->free_total * sizeof(void *)); if (cache->free_arr == NULL) { free(cache); return NULL; } return cache; } void *nw_cache_alloc(nw_cache *cache) { if (cache->free) return cache->free_arr[--cache->free]; return malloc(cache->size); } void nw_cache_free(nw_cache *cache, void *obj) { if (cache->free < cache->free_total) { cache->free_arr[cache->free++] = obj; } else { uint32_t new_free_total = cache->free_total * 2; void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *)); if (new_arr) { cache->free_total = new_free_total; cache->free_arr = new_arr; cache->free_arr[cache->free++] = obj; } else { free(obj); } } } void nw_cache_release(nw_cache *cache) { for (uint32_t i = 0; i < cache->free; ++i) { free(cache->free_arr[i]); } free(cache->free_arr); free(cache); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_401_0
crossvul-cpp_data_good_444_1
/* * uriparser - RFC 3986 URI parsing library * * Copyright (C) 2007, Weijia Song <songweijia@gmail.com> * Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org> * All rights reserved. * * 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 <ORGANIZATION> 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. */ /* What encodings are enabled? */ #include <uriparser/UriDefsConfig.h> #if (!defined(URI_PASS_ANSI) && !defined(URI_PASS_UNICODE)) /* Include SELF twice */ # ifdef URI_ENABLE_ANSI # define URI_PASS_ANSI 1 # include "UriQuery.c" # undef URI_PASS_ANSI # endif # ifdef URI_ENABLE_UNICODE # define URI_PASS_UNICODE 1 # include "UriQuery.c" # undef URI_PASS_UNICODE # endif #else # ifdef URI_PASS_ANSI # include <uriparser/UriDefsAnsi.h> # else # include <uriparser/UriDefsUnicode.h> # include <wchar.h> # endif #ifndef URI_DOXYGEN # include <uriparser/Uri.h> # include "UriCommon.h" #endif #include <limits.h> static int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks); static UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion); int URI_FUNC(ComposeQueryCharsRequired)(const URI_TYPE(QueryList) * queryList, int * charsRequired) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryCharsRequiredEx)(const URI_TYPE(QueryList) * queryList, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((queryList == NULL) || (charsRequired == NULL)) { return URI_ERROR_NULL; } return URI_FUNC(ComposeQueryEngine)(NULL, queryList, 0, NULL, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQuery)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryEx)(dest, queryList, maxChars, charsWritten, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryEx)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((dest == NULL) || (queryList == NULL)) { return URI_ERROR_NULL; } if (maxChars < 1) { return URI_ERROR_OUTPUT_TOO_LARGE; } return URI_FUNC(ComposeQueryEngine)(dest, queryList, maxChars, charsWritten, NULL, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMalloc)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryMallocEx)(dest, queryList, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMallocEx)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList, UriBool spaceToPlus, UriBool normalizeBreaks) { int charsRequired; int res; URI_CHAR * queryString; if (dest == NULL) { return URI_ERROR_NULL; } /* Calculate space */ res = URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, &charsRequired, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { return res; } charsRequired++; /* Allocate space */ queryString = malloc(charsRequired * sizeof(URI_CHAR)); if (queryString == NULL) { return URI_ERROR_MALLOC; } /* Put query in */ res = URI_FUNC(ComposeQueryEx)(queryString, queryList, charsRequired, NULL, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { free(queryString); return res; } *dest = queryString; return URI_SUCCESS; } int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); int keyRequiredChars; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); int valueRequiredChars; if ((keyLen >= INT_MAX / worstCase) || (valueLen >= INT_MAX / worstCase)) { return URI_ERROR_OUTPUT_TOO_LARGE; } keyRequiredChars = worstCase * keyLen; valueRequiredChars = worstCase * valueLen; if (dest == NULL) { (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } } else { if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } write = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); if (value != NULL) { if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; write = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; } UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion) { const int keyLen = (int)(keyAfter - keyFirst); const int valueLen = (int)(valueAfter - valueFirst); URI_CHAR * key; URI_CHAR * value; if ((prevNext == NULL) || (itemCount == NULL) || (keyFirst == NULL) || (keyAfter == NULL) || (keyFirst > keyAfter) || (valueFirst > valueAfter) || ((keyFirst == keyAfter) && (valueFirst == NULL) && (valueAfter == NULL))) { return URI_TRUE; } /* Append new empty item */ *prevNext = malloc(1 * sizeof(URI_TYPE(QueryList))); if (*prevNext == NULL) { return URI_FALSE; /* Raises malloc error */ } (*prevNext)->next = NULL; /* Fill key */ key = malloc((keyLen + 1) * sizeof(URI_CHAR)); if (key == NULL) { free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } key[keyLen] = _UT('\0'); if (keyLen > 0) { /* Copy 1:1 */ memcpy(key, keyFirst, keyLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(key, plusToSpace, breakConversion); } (*prevNext)->key = key; /* Fill value */ if (valueFirst != NULL) { value = malloc((valueLen + 1) * sizeof(URI_CHAR)); if (value == NULL) { free(key); free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } value[valueLen] = _UT('\0'); if (valueLen > 0) { /* Copy 1:1 */ memcpy(value, valueFirst, valueLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(value, plusToSpace, breakConversion); } (*prevNext)->value = value; } else { value = NULL; } (*prevNext)->value = value; (*itemCount)++; return URI_TRUE; } void URI_FUNC(FreeQueryList)(URI_TYPE(QueryList) * queryList) { while (queryList != NULL) { URI_TYPE(QueryList) * nextBackup = queryList->next; free((URI_CHAR *)queryList->key); /* const cast */ free((URI_CHAR *)queryList->value); /* const cast */ free(queryList); queryList = nextBackup; } } int URI_FUNC(DissectQueryMalloc)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast) { const UriBool plusToSpace = URI_TRUE; const UriBreakConversion breakConversion = URI_BR_DONT_TOUCH; return URI_FUNC(DissectQueryMallocEx)(dest, itemCount, first, afterLast, plusToSpace, breakConversion); } int URI_FUNC(DissectQueryMallocEx)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast, UriBool plusToSpace, UriBreakConversion breakConversion) { const URI_CHAR * walk = first; const URI_CHAR * keyFirst = first; const URI_CHAR * keyAfter = NULL; const URI_CHAR * valueFirst = NULL; const URI_CHAR * valueAfter = NULL; URI_TYPE(QueryList) ** prevNext = dest; int nullCounter; int * itemsAppended = (itemCount == NULL) ? &nullCounter : itemCount; if ((dest == NULL) || (first == NULL) || (afterLast == NULL)) { return URI_ERROR_NULL; } if (first > afterLast) { return URI_ERROR_RANGE_INVALID; } *dest = NULL; *itemsAppended = 0; /* Parse query string */ for (; walk < afterLast; walk++) { switch (*walk) { case _UT('&'): if (valueFirst != NULL) { valueAfter = walk; } else { keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } /* Make future items children of the current */ if ((prevNext != NULL) && (*prevNext != NULL)) { prevNext = &((*prevNext)->next); } if (walk + 1 < afterLast) { keyFirst = walk + 1; } else { keyFirst = NULL; } keyAfter = NULL; valueFirst = NULL; valueAfter = NULL; break; case _UT('='): /* NOTE: WE treat the first '=' as a separator, */ /* all following go into the value part */ if (keyAfter == NULL) { keyAfter = walk; if (walk + 1 <= afterLast) { valueFirst = walk + 1; valueAfter = walk + 1; } } break; default: break; } } if (valueFirst != NULL) { /* Must be key/value pair */ valueAfter = walk; } else { /* Must be key only */ keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } return URI_SUCCESS; } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_444_1
crossvul-cpp_data_bad_1834_5
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % IIIII CCCC OOO N N % % I C O O NN N % % I C O O N N N % % I C O O N NN % % IIIII CCCC OOO N N % % % % % % Read Microsoft Windows Icon Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/module.h" /* Define declarations. */ #if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__MINGW32__) || defined(__MINGW64__) #define BI_RGB 0 #define BI_RLE8 1 #define BI_BITFIELDS 3 #endif #define MaxIcons 1024 /* Typedef declarations. */ typedef struct _IconEntry { unsigned char width, height, colors, reserved; unsigned short int planes, bits_per_pixel; size_t size, offset; } IconEntry; typedef struct _IconFile { short reserved, resource_type, count; IconEntry directory[MaxIcons]; } IconFile; typedef struct _IconInfo { size_t file_size, ba_offset, offset_bits, size; ssize_t width, height; unsigned short planes, bits_per_pixel; size_t compression, image_size, x_pixels, y_pixels, number_colors, red_mask, green_mask, blue_mask, alpha_mask, colors_important; ssize_t colorspace; } IconInfo; /* Forward declaractions. */ static Image *AutoResizeImage(const Image *,const char *,MagickOffsetType *, ExceptionInfo *); static MagickBooleanType WriteICONImage(const ImageInfo *,Image *,ExceptionInfo *); Image *AutoResizeImage(const Image *image,const char *option, MagickOffsetType *count,ExceptionInfo *exception) { #define MAX_SIZES 16 char *q; const char *p; Image *resized, *images; register ssize_t i; size_t sizes[MAX_SIZES]={256,192,128,96,64,48,40,32,24,16}; images=NULL; *count=0; i=0; p=option; while (*p != '\0' && i < MAX_SIZES) { size_t size; while ((isspace((int) ((unsigned char) *p)) != 0)) p++; size=(size_t)strtol(p,&q,10); if (p == q || size < 16 || size > 256) return((Image *) NULL); p=q; sizes[i++]=size; while ((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) p++; } if (i==0) i=10; *count=i; for (i=0; i < *count; i++) { resized=ResizeImage(image,sizes[i],sizes[i],image->filter,exception); if (resized == (Image *) NULL) return(DestroyImageList(images)); if (images == (Image *) NULL) images=resized; else AppendImageToList(&images,resized); } return(images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d I C O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadICONImage() reads a Microsoft icon image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadICONImage method is: % % Image *ReadICONImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static Image *ReadICONImage(const ImageInfo *image_info, ExceptionInfo *exception) { IconFile icon_file; IconInfo icon_info; Image *image; MagickBooleanType status; register ssize_t i, x; register Quantum *q; register unsigned char *p; size_t bit, byte, bytes_per_line, one, scanline_pad; ssize_t count, offset, y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } icon_file.reserved=(short) ReadBlobLSBShort(image); icon_file.resource_type=(short) ReadBlobLSBShort(image); icon_file.count=(short) ReadBlobLSBShort(image); if ((icon_file.reserved != 0) || ((icon_file.resource_type != 1) && (icon_file.resource_type != 2)) || (icon_file.count > MaxIcons)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); for (i=0; i < icon_file.count; i++) { icon_file.directory[i].width=(unsigned char) ReadBlobByte(image); icon_file.directory[i].height=(unsigned char) ReadBlobByte(image); icon_file.directory[i].colors=(unsigned char) ReadBlobByte(image); icon_file.directory[i].reserved=(unsigned char) ReadBlobByte(image); icon_file.directory[i].planes=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].bits_per_pixel=(unsigned short) ReadBlobLSBShort(image); icon_file.directory[i].size=ReadBlobLSBLong(image); icon_file.directory[i].offset=ReadBlobLSBLong(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } } one=1; for (i=0; i < icon_file.count; i++) { /* Verify Icon identifier. */ offset=(ssize_t) SeekBlob(image,(MagickOffsetType) icon_file.directory[i].offset,SEEK_SET); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.size=ReadBlobLSBLong(image); icon_info.width=(unsigned char) ((int) ReadBlobLSBLong(image)); icon_info.height=(unsigned char) ((int) ReadBlobLSBLong(image)/2); icon_info.planes=ReadBlobLSBShort(image); icon_info.bits_per_pixel=ReadBlobLSBShort(image); if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile", image->filename); break; } if (((icon_info.planes == 18505) && (icon_info.bits_per_pixel == 21060)) || (icon_info.size == 0x474e5089)) { Image *icon_image; ImageInfo *read_info; size_t length; unsigned char *png; /* Icon image encoded as a compressed PNG image. */ length=icon_file.directory[i].size; png=(unsigned char *) AcquireQuantumMemory(length+16,sizeof(*png)); if (png == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) CopyMagickMemory(png,"\211PNG\r\n\032\n\000\000\000\015",12); png[12]=(unsigned char) icon_info.planes; png[13]=(unsigned char) (icon_info.planes >> 8); png[14]=(unsigned char) icon_info.bits_per_pixel; png[15]=(unsigned char) (icon_info.bits_per_pixel >> 8); count=ReadBlob(image,length-16,png+16); icon_image=(Image *) NULL; if (count > 0) { read_info=CloneImageInfo(image_info); (void) CopyMagickString(read_info->magick,"PNG",MagickPathExtent); icon_image=BlobToImage(read_info,png,length+16,exception); read_info=DestroyImageInfo(read_info); } png=(unsigned char *) RelinquishMagickMemory(png); if (icon_image == (Image *) NULL) { if (count != (ssize_t) (length-16)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); image=DestroyImageList(image); return((Image *) NULL); } DestroyBlob(icon_image); icon_image->blob=ReferenceBlob(image->blob); ReplaceImageInList(&image,icon_image); } else { if (icon_info.bits_per_pixel > 32) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); icon_info.compression=ReadBlobLSBLong(image); icon_info.image_size=ReadBlobLSBLong(image); icon_info.x_pixels=ReadBlobLSBLong(image); icon_info.y_pixels=ReadBlobLSBLong(image); icon_info.number_colors=ReadBlobLSBLong(image); icon_info.colors_important=ReadBlobLSBLong(image); image->alpha_trait=BlendPixelTrait; image->columns=(size_t) icon_file.directory[i].width; if ((ssize_t) image->columns > icon_info.width) image->columns=(size_t) icon_info.width; if (image->columns == 0) image->columns=256; image->rows=(size_t) icon_file.directory[i].height; if ((ssize_t) image->rows > icon_info.height) image->rows=(size_t) icon_info.height; if (image->rows == 0) image->rows=256; image->depth=icon_info.bits_per_pixel; if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene = %.20g",(double) i); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " size = %.20g",(double) icon_info.size); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " width = %.20g",(double) icon_file.directory[i].width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " height = %.20g",(double) icon_file.directory[i].height); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " colors = %.20g",(double ) icon_info.number_colors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " planes = %.20g",(double) icon_info.planes); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " bpp = %.20g",(double) icon_info.bits_per_pixel); } if ((icon_info.number_colors != 0) || (icon_info.bits_per_pixel <= 16U)) { image->storage_class=PseudoClass; image->colors=icon_info.number_colors; if (image->colors == 0) image->colors=one << icon_info.bits_per_pixel; } if (image->storage_class == PseudoClass) { register ssize_t i; unsigned char *icon_colormap; /* Read Icon raster colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) image->colors,4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) (4*image->colors),icon_colormap); if (count != (ssize_t) (4*image->colors)) ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); p=icon_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].blue=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].green=(Quantum) ScaleCharToQuantum(*p++); image->colormap[i].red=(Quantum) ScaleCharToQuantum(*p++); p++; } icon_colormap=(unsigned char *) RelinquishMagickMemory(icon_colormap); } /* Convert Icon raster image to pixel packets. */ if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); bytes_per_line=(((image->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; (void) bytes_per_line; scanline_pad=((((image->columns*icon_info.bits_per_pixel)+31) & ~31)- (image->columns*icon_info.bits_per_pixel)) >> 3; switch (icon_info.bits_per_pixel) { case 1: { /* Convert bitmap scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) (image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelIndex(image,((byte & (0x80 >> bit)) != 0 ? 0x01 : 0x00),q); q+=GetPixelChannels(image); } } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 4: { /* Read 4-bit Icon scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-1); x+=2) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); SetPixelIndex(image,((byte) & 0xf),q); q+=GetPixelChannels(image); } if ((image->columns % 2) != 0) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,((byte >> 4) & 0xf),q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 16: { /* Convert PseudoColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte=(size_t) ReadBlobByte(image); byte|=(size_t) (ReadBlobByte(image) << 8); SetPixelIndex(image,byte,q); q+=GetPixelChannels(image); } for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectColor scanline. */ for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { SetPixelBlue(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelGreen(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); SetPixelRed(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); if (icon_info.bits_per_pixel == 32) SetPixelAlpha(image,ScaleCharToQuantum((unsigned char) ReadBlobByte(image)),q); q+=GetPixelChannels(image); } if (icon_info.bits_per_pixel == 24) for (x=0; x < (ssize_t) scanline_pad; x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,LoadImageTag,image->rows-y-1, image->rows); if (status == MagickFalse) break; } } break; } default: ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } if (image_info->ping == MagickFalse) (void) SyncImage(image,exception); if (icon_info.bits_per_pixel != 32) { /* Read the ICON alpha mask. */ image->storage_class=DirectClass; for (y=(ssize_t) image->rows-1; y >= 0; y--) { q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < ((ssize_t) image->columns-7); x+=8) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < 8; bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 8) != 0) { byte=(size_t) ReadBlobByte(image); for (bit=0; bit < (image->columns % 8); bit++) { SetPixelAlpha(image,(((byte & (0x80 >> bit)) != 0) ? TransparentAlpha : OpaqueAlpha),q); q+=GetPixelChannels(image); } } if ((image->columns % 32) != 0) for (x=0; x < (ssize_t) ((32-(image->columns % 32))/8); x++) (void) ReadBlobByte(image); if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } if (EOFBlob(image) != MagickFalse) { ThrowFileException(exception,CorruptImageError, "UnexpectedEndOfFile",image->filename); break; } } /* Proceed to next image. */ if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; if (i < (ssize_t) (icon_file.count-1)) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); return((Image *) NULL); } image=SyncNextImageInList(image); status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; } } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r I C O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterICONImage() adds attributes for the Icon image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterICONImage method is: % % size_t RegisterICONImage(void) % */ ModuleExport size_t RegisterICONImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("ICON","CUR","Microsoft icon"); entry->decoder=(DecodeImageHandler *) ReadICONImage; entry->encoder=(EncodeImageHandler *) WriteICONImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("ICON","ICO","Microsoft icon"); entry->decoder=(DecodeImageHandler *) ReadICONImage; entry->encoder=(EncodeImageHandler *) WriteICONImage; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("ICON","ICON","Microsoft icon"); entry->decoder=(DecodeImageHandler *) ReadICONImage; entry->encoder=(EncodeImageHandler *) WriteICONImage; entry->flags^=CoderAdjoinFlag; entry->flags|=CoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r I C O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterICONImage() removes format registrations made by the % ICON module from the list of supported formats. % % The format of the UnregisterICONImage method is: % % UnregisterICONImage(void) % */ ModuleExport void UnregisterICONImage(void) { (void) UnregisterMagickInfo("CUR"); (void) UnregisterMagickInfo("ICO"); (void) UnregisterMagickInfo("ICON"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e I C O N I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteICONImage() writes an image in Microsoft Windows bitmap encoded % image format, version 3 for Windows or (if the image has a matte channel) % version 4. % % It encodes any subimage as a compressed PNG image ("BI_PNG)", only when its % dimensions are 256x256 and image->compression is undefined or is defined as % ZipCompression. % % The format of the WriteICONImage method is: % % MagickBooleanType WriteICONImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteICONImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const char *option; IconFile icon_file; IconInfo icon_info; Image *images, *next; MagickBooleanType status; MagickOffsetType offset, scene; register const Quantum *p; register ssize_t i, x; register unsigned char *q; size_t bytes_per_line, scanline_pad; ssize_t y; unsigned char bit, byte, *pixels; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); images=(Image *) NULL; option=GetImageOption(image_info,"icon:auto-resize"); if (option != (const char *) NULL) { images=AutoResizeImage(image,option,&scene,exception); if (images == (Image *) NULL) ThrowWriterException(ImageError,"InvalidDimensions"); } else { scene=0; next=image; do { if ((image->columns > 256L) || (image->rows > 256L)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); scene++; next=SyncNextImageInList(next); } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); } /* Dump out a ICON header template to be properly initialized later. */ (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,1); (void) WriteBlobLSBShort(image,(unsigned char) scene); (void) ResetMagickMemory(&icon_file,0,sizeof(icon_file)); (void) ResetMagickMemory(&icon_info,0,sizeof(icon_info)); scene=0; next=(images != (Image *) NULL) ? images : image; do { (void) WriteBlobByte(image,icon_file.directory[scene].width); (void) WriteBlobByte(image,icon_file.directory[scene].height); (void) WriteBlobByte(image,icon_file.directory[scene].colors); (void) WriteBlobByte(image,icon_file.directory[scene].reserved); (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); (void) WriteBlobLSBLong(image,(unsigned int) icon_file.directory[scene].size); (void) WriteBlobLSBLong(image,(unsigned int) icon_file.directory[scene].offset); scene++; next=SyncNextImageInList(next); } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); scene=0; next=(images != (Image *) NULL) ? images : image; do { if ((next->columns > 255L) && (next->rows > 255L) && ((next->compression == UndefinedCompression) || (next->compression == ZipCompression))) { Image *write_image; ImageInfo *write_info; size_t length; unsigned char *png; write_image=CloneImage(next,0,0,MagickTrue,exception); if (write_image == (Image *) NULL) { images=DestroyImageList(images); return(MagickFalse); } write_info=CloneImageInfo(image_info); (void) CopyMagickString(write_info->filename,"PNG:",MagickPathExtent); /* Don't write any ancillary chunks except for gAMA */ (void) SetImageArtifact(write_image,"png:include-chunk","none,gama"); /* Only write PNG32 formatted PNG (32-bit RGBA), 8 bits per channel */ (void) SetImageArtifact(write_image,"png:format","png32"); png=(unsigned char *) ImageToBlob(write_info,write_image,&length, exception); write_image=DestroyImage(write_image); write_info=DestroyImageInfo(write_info); if (png == (unsigned char *) NULL) { images=DestroyImageList(images); return(MagickFalse); } icon_file.directory[scene].width=0; icon_file.directory[scene].height=0; icon_file.directory[scene].colors=0; icon_file.directory[scene].reserved=0; icon_file.directory[scene].planes=1; icon_file.directory[scene].bits_per_pixel=32; icon_file.directory[scene].size=(size_t) length; icon_file.directory[scene].offset=(size_t) TellBlob(image); (void) WriteBlob(image,(size_t) length,png); png=(unsigned char *) RelinquishMagickMemory(png); } else { /* Initialize ICON raster file header. */ (void) TransformImageColorspace(next,sRGBColorspace,exception); icon_info.file_size=14+12+28; icon_info.offset_bits=icon_info.file_size; icon_info.compression=BI_RGB; if ((next->storage_class != DirectClass) && (next->colors > 256)) (void) SetImageStorageClass(next,DirectClass,exception); if (next->storage_class == DirectClass) { /* Full color ICON raster. */ icon_info.number_colors=0; icon_info.bits_per_pixel=32; icon_info.compression=(size_t) BI_RGB; } else { size_t one; /* Colormapped ICON raster. */ icon_info.bits_per_pixel=8; if (next->colors <= 256) icon_info.bits_per_pixel=8; if (next->colors <= 16) icon_info.bits_per_pixel=4; if (next->colors <= 2) icon_info.bits_per_pixel=1; one=1; icon_info.number_colors=one << icon_info.bits_per_pixel; if (icon_info.number_colors < next->colors) { (void) SetImageStorageClass(next,DirectClass,exception); icon_info.number_colors=0; icon_info.bits_per_pixel=(unsigned short) 24; icon_info.compression=(size_t) BI_RGB; } else { size_t one; one=1; icon_info.file_size+=3*(one << icon_info.bits_per_pixel); icon_info.offset_bits+=3*(one << icon_info.bits_per_pixel); icon_info.file_size+=(one << icon_info.bits_per_pixel); icon_info.offset_bits+=(one << icon_info.bits_per_pixel); } } bytes_per_line=(((next->columns*icon_info.bits_per_pixel)+31) & ~31) >> 3; icon_info.ba_offset=0; icon_info.width=(ssize_t) next->columns; icon_info.height=(ssize_t) next->rows; icon_info.planes=1; icon_info.image_size=bytes_per_line*next->rows; icon_info.size=40; icon_info.size+=(4*icon_info.number_colors); icon_info.size+=icon_info.image_size; icon_info.size+=(((icon_info.width+31) & ~31) >> 3)*icon_info.height; icon_info.file_size+=icon_info.image_size; icon_info.x_pixels=0; icon_info.y_pixels=0; switch (next->units) { case UndefinedResolution: case PixelsPerInchResolution: { icon_info.x_pixels=(size_t) (100.0*next->resolution.x/2.54); icon_info.y_pixels=(size_t) (100.0*next->resolution.y/2.54); break; } case PixelsPerCentimeterResolution: { icon_info.x_pixels=(size_t) (100.0*next->resolution.x); icon_info.y_pixels=(size_t) (100.0*next->resolution.y); break; } } icon_info.colors_important=icon_info.number_colors; /* Convert MIFF to ICON raster pixels. */ pixels=(unsigned char *) AcquireQuantumMemory((size_t) icon_info.image_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { images=DestroyImageList(images); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) ResetMagickMemory(pixels,0,(size_t) icon_info.image_size); switch (icon_info.bits_per_pixel) { case 1: { size_t bit, byte; /* Convert PseudoClass image to a ICON monochrome image. */ for (y=0; y < (ssize_t) next->rows; y++) { p=GetVirtualPixels(next,0,y,next->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(next->rows-y-1)*bytes_per_line; bit=0; byte=0; for (x=0; x < (ssize_t) next->columns; x++) { byte<<=1; byte|=GetPixelIndex(next,p) != 0 ? 0x01 : 0x00; bit++; if (bit == 8) { *q++=(unsigned char) byte; bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) *q++=(unsigned char) (byte << (8-bit)); if (next->previous == (Image *) NULL) { status=SetImageProgress(next,SaveImageTag,y,next->rows); if (status == MagickFalse) break; } } break; } case 4: { size_t nibble, byte; /* Convert PseudoClass image to a ICON monochrome image. */ for (y=0; y < (ssize_t) next->rows; y++) { p=GetVirtualPixels(next,0,y,next->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(next->rows-y-1)*bytes_per_line; nibble=0; byte=0; for (x=0; x < (ssize_t) next->columns; x++) { byte<<=4; byte|=((size_t) GetPixelIndex(next,p) & 0x0f); nibble++; if (nibble == 2) { *q++=(unsigned char) byte; nibble=0; byte=0; } p+=GetPixelChannels(image); } if (nibble != 0) *q++=(unsigned char) (byte << 4); if (next->previous == (Image *) NULL) { status=SetImageProgress(next,SaveImageTag,y,next->rows); if (status == MagickFalse) break; } } break; } case 8: { /* Convert PseudoClass packet to ICON pixel. */ for (y=0; y < (ssize_t) next->rows; y++) { p=GetVirtualPixels(next,0,y,next->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(next->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) next->columns; x++) { *q++=(unsigned char) GetPixelIndex(next,p); p+=GetPixelChannels(image); } if (next->previous == (Image *) NULL) { status=SetImageProgress(next,SaveImageTag,y,next->rows); if (status == MagickFalse) break; } } break; } case 24: case 32: { /* Convert DirectClass packet to ICON BGR888 or BGRA8888 pixel. */ for (y=0; y < (ssize_t) next->rows; y++) { p=GetVirtualPixels(next,0,y,next->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels+(next->rows-y-1)*bytes_per_line; for (x=0; x < (ssize_t) next->columns; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(next,p)); *q++=ScaleQuantumToChar(GetPixelGreen(next,p)); *q++=ScaleQuantumToChar(GetPixelRed(next,p)); if (next->alpha_trait == UndefinedPixelTrait) *q++=ScaleQuantumToChar(QuantumRange); else *q++=ScaleQuantumToChar(GetPixelAlpha(next,p)); p+=GetPixelChannels(next); } if (icon_info.bits_per_pixel == 24) for (x=3L*(ssize_t) next->columns; x < (ssize_t) bytes_per_line; x++) *q++=0x00; if (next->previous == (Image *) NULL) { status=SetImageProgress(next,SaveImageTag,y,next->rows); if (status == MagickFalse) break; } } break; } } /* Write 40-byte version 3+ bitmap header. */ icon_file.directory[scene].width=(unsigned char) icon_info.width; icon_file.directory[scene].height=(unsigned char) icon_info.height; icon_file.directory[scene].colors=(unsigned char) icon_info.number_colors; icon_file.directory[scene].reserved=0; icon_file.directory[scene].planes=icon_info.planes; icon_file.directory[scene].bits_per_pixel=icon_info.bits_per_pixel; icon_file.directory[scene].size=icon_info.size; icon_file.directory[scene].offset=(size_t) TellBlob(image); (void) WriteBlobLSBLong(image,(unsigned int) 40); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.width); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.height*2); (void) WriteBlobLSBShort(image,icon_info.planes); (void) WriteBlobLSBShort(image,icon_info.bits_per_pixel); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.compression); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.image_size); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.x_pixels); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.y_pixels); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.number_colors); (void) WriteBlobLSBLong(image,(unsigned int) icon_info.colors_important); if (next->storage_class == PseudoClass) { unsigned char *icon_colormap; /* Dump colormap to file. */ icon_colormap=(unsigned char *) AcquireQuantumMemory((size_t) (1UL << icon_info.bits_per_pixel),4UL*sizeof(*icon_colormap)); if (icon_colormap == (unsigned char *) NULL) { images=DestroyImageList(images); ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed"); } q=icon_colormap; for (i=0; i < (ssize_t) next->colors; i++) { *q++=ScaleQuantumToChar(next->colormap[i].blue); *q++=ScaleQuantumToChar(next->colormap[i].green); *q++=ScaleQuantumToChar(next->colormap[i].red); *q++=(unsigned char) 0x0; } for ( ; i < (ssize_t) (1UL << icon_info.bits_per_pixel); i++) { *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; *q++=(unsigned char) 0x00; } (void) WriteBlob(image,(size_t) (4UL*(1UL << icon_info.bits_per_pixel)),icon_colormap); icon_colormap=(unsigned char *) RelinquishMagickMemory( icon_colormap); } (void) WriteBlob(image,(size_t) icon_info.image_size,pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); /* Write matte mask. */ scanline_pad=(((next->columns+31) & ~31)-next->columns) >> 3; for (y=((ssize_t) next->rows - 1); y >= 0; y--) { p=GetVirtualPixels(next,0,y,next->columns,1,exception); if (p == (const Quantum *) NULL) break; bit=0; byte=0; for (x=0; x < (ssize_t) next->columns; x++) { byte<<=1; if ((next->alpha_trait != UndefinedPixelTrait) && (GetPixelAlpha(next,p) == (Quantum) TransparentAlpha)) byte|=0x01; bit++; if (bit == 8) { (void) WriteBlobByte(image,(unsigned char) byte); bit=0; byte=0; } p+=GetPixelChannels(next); } if (bit != 0) (void) WriteBlobByte(image,(unsigned char) (byte << (8-bit))); for (i=0; i < (ssize_t) scanline_pad; i++) (void) WriteBlobByte(image,(unsigned char) 0); } } if (GetNextImageInList(next) == (Image *) NULL) break; status=SetImageProgress(next,SaveImagesTag,scene++, GetImageListLength(next)); if (status == MagickFalse) break; next=SyncNextImageInList(next); } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); offset=SeekBlob(image,0,SEEK_SET); (void) offset; (void) WriteBlobLSBShort(image,0); (void) WriteBlobLSBShort(image,1); (void) WriteBlobLSBShort(image,(unsigned short) (scene+1)); scene=0; next=(images != (Image *) NULL) ? images : image; do { (void) WriteBlobByte(image,icon_file.directory[scene].width); (void) WriteBlobByte(image,icon_file.directory[scene].height); (void) WriteBlobByte(image,icon_file.directory[scene].colors); (void) WriteBlobByte(image,icon_file.directory[scene].reserved); (void) WriteBlobLSBShort(image,icon_file.directory[scene].planes); (void) WriteBlobLSBShort(image,icon_file.directory[scene].bits_per_pixel); (void) WriteBlobLSBLong(image,(unsigned int) icon_file.directory[scene].size); (void) WriteBlobLSBLong(image,(unsigned int) icon_file.directory[scene].offset); scene++; next=SyncNextImageInList(next); } while ((next != (Image *) NULL) && (image_info->adjoin != MagickFalse)); (void) CloseBlob(image); images=DestroyImageList(images); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1834_5
crossvul-cpp_data_good_400_0
/* * Description: network buf manager * History: yang@haipo.me, 2016/03/16, create */ # include <errno.h> # include <string.h> # include "nw_buf.h" # define NW_BUF_POOL_INIT_SIZE 64 # define NW_BUF_POOL_MAX_SIZE 65535 # define NW_CACHE_INIT_SIZE 64 # define NW_CACHE_MAX_SIZE 65535 size_t nw_buf_size(nw_buf *buf) { return buf->wpos - buf->rpos; } size_t nw_buf_avail(nw_buf *buf) { return buf->size - buf->wpos; } size_t nw_buf_write(nw_buf *buf, const void *data, size_t len) { size_t available = buf->size - buf->wpos; size_t wlen = len > available ? available : len; memcpy(buf->data + buf->wpos, data, wlen); buf->wpos += wlen; return wlen; } void nw_buf_shift(nw_buf *buf) { if (buf->rpos == buf->wpos) { buf->rpos = buf->wpos = 0; } else if (buf->rpos != 0) { memmove(buf->data, buf->data + buf->rpos, buf->wpos - buf->rpos); buf->wpos -= buf->rpos; buf->rpos = 0; } } nw_buf_pool *nw_buf_pool_create(uint32_t size) { nw_buf_pool *pool = malloc(sizeof(nw_buf_pool)); if (pool == NULL) return NULL; pool->size = size; pool->used = 0; pool->free = 0; pool->free_total = NW_BUF_POOL_INIT_SIZE; pool->free_arr = malloc(pool->free_total * sizeof(nw_buf *)); if (pool->free_arr == NULL) { free(pool); return NULL; } return pool; } nw_buf *nw_buf_alloc(nw_buf_pool *pool) { if (pool->free) { nw_buf *buf = pool->free_arr[--pool->free]; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } nw_buf *buf = malloc(sizeof(nw_buf) + pool->size); if (buf == NULL) return NULL; buf->size = pool->size; buf->rpos = 0; buf->wpos = 0; buf->next = NULL; return buf; } void nw_buf_free(nw_buf_pool *pool, nw_buf *buf) { if (pool->free < pool->free_total) { pool->free_arr[pool->free++] = buf; } else if (pool->free_total < NW_BUF_POOL_MAX_SIZE) { uint32_t new_free_total = pool->free_total * 2; void *new_arr = realloc(pool->free_arr, new_free_total * sizeof(nw_buf *)); if (new_arr) { pool->free_total = new_free_total; pool->free_arr = new_arr; pool->free_arr[pool->free++] = buf; } else { free(buf); } } else { free(buf); } } void nw_buf_pool_release(nw_buf_pool *pool) { for (uint32_t i = 0; i < pool->free; ++i) { free(pool->free_arr[i]); } free(pool->free_arr); free(pool); } nw_buf_list *nw_buf_list_create(nw_buf_pool *pool, uint32_t limit) { nw_buf_list *list = malloc(sizeof(nw_buf_list)); if (list == NULL) return NULL; list->pool = pool; list->count = 0; list->limit = limit; list->head = NULL; list->tail = NULL; return list; } size_t nw_buf_list_write(nw_buf_list *list, const void *data, size_t len) { const void *pos = data; size_t left = len; if (list->tail && nw_buf_avail(list->tail)) { size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } while (left) { if (list->limit && list->count >= list->limit) return len - left; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return len - left; if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; size_t ret = nw_buf_write(list->tail, pos, left); left -= ret; pos += ret; } return len; } size_t nw_buf_list_append(nw_buf_list *list, const void *data, size_t len) { if (list->limit && list->count >= list->limit) return 0; nw_buf *buf = nw_buf_alloc(list->pool); if (buf == NULL) return 0; if (len > buf->size) { nw_buf_free(list->pool, buf); return 0; } nw_buf_write(buf, data, len); if (list->head == NULL) list->head = buf; if (list->tail != NULL) list->tail->next = buf; list->tail = buf; list->count++; return len; } void nw_buf_list_shift(nw_buf_list *list) { if (list->head) { nw_buf *tmp = list->head; list->head = tmp->next; if (list->head == NULL) { list->tail = NULL; } list->count--; nw_buf_free(list->pool, tmp); } } void nw_buf_list_release(nw_buf_list *list) { nw_buf *curr = list->head; nw_buf *next = NULL; while (curr) { next = curr->next; nw_buf_free(list->pool, curr); curr = next; } free(list); } nw_cache *nw_cache_create(uint32_t size) { nw_cache *cache = malloc(sizeof(nw_cache)); if (cache == NULL) return NULL; cache->size = size; cache->used = 0; cache->free = 0; cache->free_total = NW_CACHE_INIT_SIZE; cache->free_arr = malloc(cache->free_total * sizeof(void *)); if (cache->free_arr == NULL) { free(cache); return NULL; } return cache; } void *nw_cache_alloc(nw_cache *cache) { if (cache->free) return cache->free_arr[--cache->free]; return malloc(cache->size); } void nw_cache_free(nw_cache *cache, void *obj) { if (cache->free < cache->free_total) { cache->free_arr[cache->free++] = obj; } else if (cache->free_total < NW_CACHE_MAX_SIZE) { uint32_t new_free_total = cache->free_total * 2; void *new_arr = realloc(cache->free_arr, new_free_total * sizeof(void *)); if (new_arr) { cache->free_total = new_free_total; cache->free_arr = new_arr; cache->free_arr[cache->free++] = obj; } else { free(obj); } } else { free(obj); } } void nw_cache_release(nw_cache *cache) { for (uint32_t i = 0; i < cache->free; ++i) { free(cache->free_arr[i]); } free(cache->free_arr); free(cache); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_400_0
crossvul-cpp_data_bad_444_1
/* * uriparser - RFC 3986 URI parsing library * * Copyright (C) 2007, Weijia Song <songweijia@gmail.com> * Copyright (C) 2007, Sebastian Pipping <sebastian@pipping.org> * All rights reserved. * * 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 <ORGANIZATION> 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. */ /* What encodings are enabled? */ #include <uriparser/UriDefsConfig.h> #if (!defined(URI_PASS_ANSI) && !defined(URI_PASS_UNICODE)) /* Include SELF twice */ # ifdef URI_ENABLE_ANSI # define URI_PASS_ANSI 1 # include "UriQuery.c" # undef URI_PASS_ANSI # endif # ifdef URI_ENABLE_UNICODE # define URI_PASS_UNICODE 1 # include "UriQuery.c" # undef URI_PASS_UNICODE # endif #else # ifdef URI_PASS_ANSI # include <uriparser/UriDefsAnsi.h> # else # include <uriparser/UriDefsUnicode.h> # include <wchar.h> # endif #ifndef URI_DOXYGEN # include <uriparser/Uri.h> # include "UriCommon.h" #endif static int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks); static UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion); int URI_FUNC(ComposeQueryCharsRequired)(const URI_TYPE(QueryList) * queryList, int * charsRequired) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryCharsRequiredEx)(const URI_TYPE(QueryList) * queryList, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((queryList == NULL) || (charsRequired == NULL)) { return URI_ERROR_NULL; } return URI_FUNC(ComposeQueryEngine)(NULL, queryList, 0, NULL, charsRequired, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQuery)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryEx)(dest, queryList, maxChars, charsWritten, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryEx)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, UriBool spaceToPlus, UriBool normalizeBreaks) { if ((dest == NULL) || (queryList == NULL)) { return URI_ERROR_NULL; } if (maxChars < 1) { return URI_ERROR_OUTPUT_TOO_LARGE; } return URI_FUNC(ComposeQueryEngine)(dest, queryList, maxChars, charsWritten, NULL, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMalloc)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList) { const UriBool spaceToPlus = URI_TRUE; const UriBool normalizeBreaks = URI_TRUE; return URI_FUNC(ComposeQueryMallocEx)(dest, queryList, spaceToPlus, normalizeBreaks); } int URI_FUNC(ComposeQueryMallocEx)(URI_CHAR ** dest, const URI_TYPE(QueryList) * queryList, UriBool spaceToPlus, UriBool normalizeBreaks) { int charsRequired; int res; URI_CHAR * queryString; if (dest == NULL) { return URI_ERROR_NULL; } /* Calculate space */ res = URI_FUNC(ComposeQueryCharsRequiredEx)(queryList, &charsRequired, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { return res; } charsRequired++; /* Allocate space */ queryString = malloc(charsRequired * sizeof(URI_CHAR)); if (queryString == NULL) { return URI_ERROR_MALLOC; } /* Put query in */ res = URI_FUNC(ComposeQueryEx)(queryString, queryList, charsRequired, NULL, spaceToPlus, normalizeBreaks); if (res != URI_SUCCESS) { free(queryString); return res; } *dest = queryString; return URI_SUCCESS; } int URI_FUNC(ComposeQueryEngine)(URI_CHAR * dest, const URI_TYPE(QueryList) * queryList, int maxChars, int * charsWritten, int * charsRequired, UriBool spaceToPlus, UriBool normalizeBreaks) { UriBool firstItem = URI_TRUE; int ampersandLen = 0; /* increased to 1 from second item on */ URI_CHAR * write = dest; /* Subtract terminator */ if (dest == NULL) { *charsRequired = 0; } else { maxChars--; } while (queryList != NULL) { const URI_CHAR * const key = queryList->key; const URI_CHAR * const value = queryList->value; const int worstCase = (normalizeBreaks == URI_TRUE ? 6 : 3); const int keyLen = (key == NULL) ? 0 : (int)URI_STRLEN(key); const int keyRequiredChars = worstCase * keyLen; const int valueLen = (value == NULL) ? 0 : (int)URI_STRLEN(value); const int valueRequiredChars = worstCase * valueLen; if (dest == NULL) { (*charsRequired) += ampersandLen + keyRequiredChars + ((value == NULL) ? 0 : 1 + valueRequiredChars); if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } } else { if ((write - dest) + ampersandLen + keyRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy key */ if (firstItem == URI_TRUE) { ampersandLen = 1; firstItem = URI_FALSE; } else { write[0] = _UT('&'); write++; } write = URI_FUNC(EscapeEx)(key, key + keyLen, write, spaceToPlus, normalizeBreaks); if (value != NULL) { if ((write - dest) + 1 + valueRequiredChars > maxChars) { return URI_ERROR_OUTPUT_TOO_LARGE; } /* Copy value */ write[0] = _UT('='); write++; write = URI_FUNC(EscapeEx)(value, value + valueLen, write, spaceToPlus, normalizeBreaks); } } queryList = queryList->next; } if (dest != NULL) { write[0] = _UT('\0'); if (charsWritten != NULL) { *charsWritten = (int)(write - dest) + 1; /* .. for terminator */ } } return URI_SUCCESS; } UriBool URI_FUNC(AppendQueryItem)(URI_TYPE(QueryList) ** prevNext, int * itemCount, const URI_CHAR * keyFirst, const URI_CHAR * keyAfter, const URI_CHAR * valueFirst, const URI_CHAR * valueAfter, UriBool plusToSpace, UriBreakConversion breakConversion) { const int keyLen = (int)(keyAfter - keyFirst); const int valueLen = (int)(valueAfter - valueFirst); URI_CHAR * key; URI_CHAR * value; if ((prevNext == NULL) || (itemCount == NULL) || (keyFirst == NULL) || (keyAfter == NULL) || (keyFirst > keyAfter) || (valueFirst > valueAfter) || ((keyFirst == keyAfter) && (valueFirst == NULL) && (valueAfter == NULL))) { return URI_TRUE; } /* Append new empty item */ *prevNext = malloc(1 * sizeof(URI_TYPE(QueryList))); if (*prevNext == NULL) { return URI_FALSE; /* Raises malloc error */ } (*prevNext)->next = NULL; /* Fill key */ key = malloc((keyLen + 1) * sizeof(URI_CHAR)); if (key == NULL) { free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } key[keyLen] = _UT('\0'); if (keyLen > 0) { /* Copy 1:1 */ memcpy(key, keyFirst, keyLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(key, plusToSpace, breakConversion); } (*prevNext)->key = key; /* Fill value */ if (valueFirst != NULL) { value = malloc((valueLen + 1) * sizeof(URI_CHAR)); if (value == NULL) { free(key); free(*prevNext); *prevNext = NULL; return URI_FALSE; /* Raises malloc error */ } value[valueLen] = _UT('\0'); if (valueLen > 0) { /* Copy 1:1 */ memcpy(value, valueFirst, valueLen * sizeof(URI_CHAR)); /* Unescape */ URI_FUNC(UnescapeInPlaceEx)(value, plusToSpace, breakConversion); } (*prevNext)->value = value; } else { value = NULL; } (*prevNext)->value = value; (*itemCount)++; return URI_TRUE; } void URI_FUNC(FreeQueryList)(URI_TYPE(QueryList) * queryList) { while (queryList != NULL) { URI_TYPE(QueryList) * nextBackup = queryList->next; free((URI_CHAR *)queryList->key); /* const cast */ free((URI_CHAR *)queryList->value); /* const cast */ free(queryList); queryList = nextBackup; } } int URI_FUNC(DissectQueryMalloc)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast) { const UriBool plusToSpace = URI_TRUE; const UriBreakConversion breakConversion = URI_BR_DONT_TOUCH; return URI_FUNC(DissectQueryMallocEx)(dest, itemCount, first, afterLast, plusToSpace, breakConversion); } int URI_FUNC(DissectQueryMallocEx)(URI_TYPE(QueryList) ** dest, int * itemCount, const URI_CHAR * first, const URI_CHAR * afterLast, UriBool plusToSpace, UriBreakConversion breakConversion) { const URI_CHAR * walk = first; const URI_CHAR * keyFirst = first; const URI_CHAR * keyAfter = NULL; const URI_CHAR * valueFirst = NULL; const URI_CHAR * valueAfter = NULL; URI_TYPE(QueryList) ** prevNext = dest; int nullCounter; int * itemsAppended = (itemCount == NULL) ? &nullCounter : itemCount; if ((dest == NULL) || (first == NULL) || (afterLast == NULL)) { return URI_ERROR_NULL; } if (first > afterLast) { return URI_ERROR_RANGE_INVALID; } *dest = NULL; *itemsAppended = 0; /* Parse query string */ for (; walk < afterLast; walk++) { switch (*walk) { case _UT('&'): if (valueFirst != NULL) { valueAfter = walk; } else { keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } /* Make future items children of the current */ if ((prevNext != NULL) && (*prevNext != NULL)) { prevNext = &((*prevNext)->next); } if (walk + 1 < afterLast) { keyFirst = walk + 1; } else { keyFirst = NULL; } keyAfter = NULL; valueFirst = NULL; valueAfter = NULL; break; case _UT('='): /* NOTE: WE treat the first '=' as a separator, */ /* all following go into the value part */ if (keyAfter == NULL) { keyAfter = walk; if (walk + 1 <= afterLast) { valueFirst = walk + 1; valueAfter = walk + 1; } } break; default: break; } } if (valueFirst != NULL) { /* Must be key/value pair */ valueAfter = walk; } else { /* Must be key only */ keyAfter = walk; } if (URI_FUNC(AppendQueryItem)(prevNext, itemsAppended, keyFirst, keyAfter, valueFirst, valueAfter, plusToSpace, breakConversion) == URI_FALSE) { /* Free list we built */ *itemsAppended = 0; URI_FUNC(FreeQueryList)(*dest); return URI_ERROR_MALLOC; } return URI_SUCCESS; } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/bad_444_1
crossvul-cpp_data_bad_4852_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Tier-2 Coding Library * * $Id$ */ #include "jasper/jas_math.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" #include "jpc_cs.h" #include "jpc_t2cod.h" #include "jpc_math.h" static int jpc_pi_nextlrcp(jpc_pi_t *pi); static int jpc_pi_nextrlcp(jpc_pi_t *pi); static int jpc_pi_nextrpcl(jpc_pi_t *pi); static int jpc_pi_nextpcrl(jpc_pi_t *pi); static int jpc_pi_nextcprl(jpc_pi_t *pi); int jpc_pi_next(jpc_pi_t *pi) { jpc_pchg_t *pchg; int ret; for (;;) { pi->valid = false; if (!pi->pchg) { ++pi->pchgno; pi->compno = 0; pi->rlvlno = 0; pi->prcno = 0; pi->lyrno = 0; pi->prgvolfirst = true; if (pi->pchgno < jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = jpc_pchglist_get(pi->pchglist, pi->pchgno); } else if (pi->pchgno == jpc_pchglist_numpchgs(pi->pchglist)) { pi->pchg = &pi->defaultpchg; } else { return 1; } } pchg = pi->pchg; switch (pchg->prgord) { case JPC_COD_LRCPPRG: ret = jpc_pi_nextlrcp(pi); break; case JPC_COD_RLCPPRG: ret = jpc_pi_nextrlcp(pi); break; case JPC_COD_RPCLPRG: ret = jpc_pi_nextrpcl(pi); break; case JPC_COD_PCRLPRG: ret = jpc_pi_nextpcrl(pi); break; case JPC_COD_CPRLPRG: ret = jpc_pi_nextcprl(pi); break; default: ret = -1; break; } if (!ret) { pi->valid = true; ++pi->pktno; return 0; } pi->pchg = 0; } } static int jpc_pi_nextlrcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = false; } for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrlcp(register jpc_pi_t *pi) { jpc_pchg_t *pchg; int *prclyrno; pchg = pi->pchg; if (!pi->prgvolfirst) { assert(pi->prcno < pi->pirlvl->numprcs); prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; goto skip; } else { pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pi->maxrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno) { for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; for (pi->prcno = 0, prclyrno = pi->pirlvl->prclyrnos; pi->prcno < pi->pirlvl->numprcs; ++pi->prcno, ++prclyrno) { if (pi->lyrno >= *prclyrno) { *prclyrno = pi->lyrno; ++(*prclyrno); return 0; } skip: ; } } } } return 1; } static int jpc_pi_nextrpcl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; uint_fast32_t trx0; uint_fast32_t try0; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->rlvlno = pchg->rlvlnostart; pi->rlvlno < pchg->rlvlnoend && pi->rlvlno < pi->maxrlvls; ++pi->rlvlno) { for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { if (pi->rlvlno >= pi->picomp->numrlvls) { continue; } pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (1 << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (1 << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextpcrl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; int compno; jpc_picomp_t *picomp; int xstep; int ystep; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->xstep = 0; pi->ystep = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { xstep = picomp->hsamp * (1 << (pirlvl->prcwidthexpn + picomp->numrlvls - rlvlno - 1)); ystep = picomp->vsamp * (1 << (pirlvl->prcheightexpn + picomp->numrlvls - rlvlno - 1)); pi->xstep = (!pi->xstep) ? xstep : JAS_MIN(pi->xstep, xstep); pi->ystep = (!pi->ystep) ? ystep : JAS_MIN(pi->ystep, ystep); } } pi->prgvolfirst = 0; } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < pi->numcomps && pi->compno < JAS_CAST(int, pchg->compnoend); ++pi->compno, ++pi->picomp) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static int jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } static void pirlvl_destroy(jpc_pirlvl_t *rlvl) { if (rlvl->prclyrnos) { jas_free(rlvl->prclyrnos); } } static void jpc_picomp_destroy(jpc_picomp_t *picomp) { int rlvlno; jpc_pirlvl_t *pirlvl; if (picomp->pirlvls) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { pirlvl_destroy(pirlvl); } jas_free(picomp->pirlvls); } } void jpc_pi_destroy(jpc_pi_t *pi) { jpc_picomp_t *picomp; int compno; if (pi->picomps) { for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { jpc_picomp_destroy(picomp); } jas_free(pi->picomps); } if (pi->pchglist) { jpc_pchglist_destroy(pi->pchglist); } jas_free(pi); } jpc_pi_t *jpc_pi_create0() { jpc_pi_t *pi; if (!(pi = jas_malloc(sizeof(jpc_pi_t)))) { return 0; } pi->picomps = 0; pi->pchgno = 0; if (!(pi->pchglist = jpc_pchglist_create())) { jas_free(pi); return 0; } return pi; } int jpc_pi_addpchg(jpc_pi_t *pi, jpc_pocpchg_t *pchg) { return jpc_pchglist_insert(pi->pchglist, -1, pchg); } jpc_pchglist_t *jpc_pchglist_create() { jpc_pchglist_t *pchglist; if (!(pchglist = jas_malloc(sizeof(jpc_pchglist_t)))) { return 0; } pchglist->numpchgs = 0; pchglist->maxpchgs = 0; pchglist->pchgs = 0; return pchglist; } int jpc_pchglist_insert(jpc_pchglist_t *pchglist, int pchgno, jpc_pchg_t *pchg) { int i; int newmaxpchgs; jpc_pchg_t **newpchgs; if (pchgno < 0) { pchgno = pchglist->numpchgs; } if (pchglist->numpchgs >= pchglist->maxpchgs) { newmaxpchgs = pchglist->maxpchgs + 128; if (!(newpchgs = jas_realloc2(pchglist->pchgs, newmaxpchgs, sizeof(jpc_pchg_t *)))) { return -1; } pchglist->maxpchgs = newmaxpchgs; pchglist->pchgs = newpchgs; } for (i = pchglist->numpchgs; i > pchgno; --i) { pchglist->pchgs[i] = pchglist->pchgs[i - 1]; } pchglist->pchgs[pchgno] = pchg; ++pchglist->numpchgs; return 0; } jpc_pchg_t *jpc_pchglist_remove(jpc_pchglist_t *pchglist, int pchgno) { int i; jpc_pchg_t *pchg; assert(pchgno < pchglist->numpchgs); pchg = pchglist->pchgs[pchgno]; for (i = pchgno + 1; i < pchglist->numpchgs; ++i) { pchglist->pchgs[i - 1] = pchglist->pchgs[i]; } --pchglist->numpchgs; return pchg; } jpc_pchg_t *jpc_pchg_copy(jpc_pchg_t *pchg) { jpc_pchg_t *newpchg; if (!(newpchg = jas_malloc(sizeof(jpc_pchg_t)))) { return 0; } *newpchg = *pchg; return newpchg; } jpc_pchglist_t *jpc_pchglist_copy(jpc_pchglist_t *pchglist) { jpc_pchglist_t *newpchglist; jpc_pchg_t *newpchg; int pchgno; if (!(newpchglist = jpc_pchglist_create())) { return 0; } for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { if (!(newpchg = jpc_pchg_copy(pchglist->pchgs[pchgno])) || jpc_pchglist_insert(newpchglist, -1, newpchg)) { jpc_pchglist_destroy(newpchglist); return 0; } } return newpchglist; } void jpc_pchglist_destroy(jpc_pchglist_t *pchglist) { int pchgno; if (pchglist->pchgs) { for (pchgno = 0; pchgno < pchglist->numpchgs; ++pchgno) { jpc_pchg_destroy(pchglist->pchgs[pchgno]); } jas_free(pchglist->pchgs); } jas_free(pchglist); } void jpc_pchg_destroy(jpc_pchg_t *pchg) { jas_free(pchg); } jpc_pchg_t *jpc_pchglist_get(jpc_pchglist_t *pchglist, int pchgno) { return pchglist->pchgs[pchgno]; } int jpc_pchglist_numpchgs(jpc_pchglist_t *pchglist) { return pchglist->numpchgs; } int jpc_pi_init(jpc_pi_t *pi) { int compno; int rlvlno; int prcno; jpc_picomp_t *picomp; jpc_pirlvl_t *pirlvl; int *prclyrno; pi->prgvolfirst = 0; pi->valid = 0; pi->pktno = -1; pi->pchgno = -1; pi->pchg = 0; for (compno = 0, picomp = pi->picomps; compno < pi->numcomps; ++compno, ++picomp) { for (rlvlno = 0, pirlvl = picomp->pirlvls; rlvlno < picomp->numrlvls; ++rlvlno, ++pirlvl) { for (prcno = 0, prclyrno = pirlvl->prclyrnos; prcno < pirlvl->numprcs; ++prcno, ++prclyrno) { *prclyrno = 0; } } } return 0; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_4852_0
crossvul-cpp_data_good_4015_0
// SPDX-License-Identifier: GPL-2.0-only /* * linux/fs/exec.c * * Copyright (C) 1991, 1992 Linus Torvalds */ /* * #!-checking implemented by tytso. */ /* * Demand-loading implemented 01.12.91 - no need to read anything but * the header into memory. The inode of the executable is put into * "current->executable", and page faults do the actual loading. Clean. * * Once more I can proudly say that linux stood up to being changed: it * was less than 2 hours work to get demand-loading completely implemented. * * Demand loading changed July 1993 by Eric Youngdale. Use mmap instead, * current->executable is only used by the procfs. This allows a dispatch * table to check for several different types of binary formats. We keep * trying until we recognize the file or we run out of supported binary * formats. */ #include <linux/slab.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/mm.h> #include <linux/vmacache.h> #include <linux/stat.h> #include <linux/fcntl.h> #include <linux/swap.h> #include <linux/string.h> #include <linux/init.h> #include <linux/sched/mm.h> #include <linux/sched/coredump.h> #include <linux/sched/signal.h> #include <linux/sched/numa_balancing.h> #include <linux/sched/task.h> #include <linux/pagemap.h> #include <linux/perf_event.h> #include <linux/highmem.h> #include <linux/spinlock.h> #include <linux/key.h> #include <linux/personality.h> #include <linux/binfmts.h> #include <linux/utsname.h> #include <linux/pid_namespace.h> #include <linux/module.h> #include <linux/namei.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/tsacct_kern.h> #include <linux/cn_proc.h> #include <linux/audit.h> #include <linux/tracehook.h> #include <linux/kmod.h> #include <linux/fsnotify.h> #include <linux/fs_struct.h> #include <linux/oom.h> #include <linux/compat.h> #include <linux/vmalloc.h> #include <linux/uaccess.h> #include <asm/mmu_context.h> #include <asm/tlb.h> #include <trace/events/task.h> #include "internal.h" #include <trace/events/sched.h> int suid_dumpable = 0; static LIST_HEAD(formats); static DEFINE_RWLOCK(binfmt_lock); void __register_binfmt(struct linux_binfmt * fmt, int insert) { BUG_ON(!fmt); if (WARN_ON(!fmt->load_binary)) return; write_lock(&binfmt_lock); insert ? list_add(&fmt->lh, &formats) : list_add_tail(&fmt->lh, &formats); write_unlock(&binfmt_lock); } EXPORT_SYMBOL(__register_binfmt); void unregister_binfmt(struct linux_binfmt * fmt) { write_lock(&binfmt_lock); list_del(&fmt->lh); write_unlock(&binfmt_lock); } EXPORT_SYMBOL(unregister_binfmt); static inline void put_binfmt(struct linux_binfmt * fmt) { module_put(fmt->module); } bool path_noexec(const struct path *path) { return (path->mnt->mnt_flags & MNT_NOEXEC) || (path->mnt->mnt_sb->s_iflags & SB_I_NOEXEC); } #ifdef CONFIG_USELIB /* * Note that a shared library must be both readable and executable due to * security reasons. * * Also note that we take the address to load from from the file itself. */ SYSCALL_DEFINE1(uselib, const char __user *, library) { struct linux_binfmt *fmt; struct file *file; struct filename *tmp = getname(library); int error = PTR_ERR(tmp); static const struct open_flags uselib_flags = { .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, .acc_mode = MAY_READ | MAY_EXEC, .intent = LOOKUP_OPEN, .lookup_flags = LOOKUP_FOLLOW, }; if (IS_ERR(tmp)) goto out; file = do_filp_open(AT_FDCWD, tmp, &uselib_flags); putname(tmp); error = PTR_ERR(file); if (IS_ERR(file)) goto out; error = -EINVAL; if (!S_ISREG(file_inode(file)->i_mode)) goto exit; error = -EACCES; if (path_noexec(&file->f_path)) goto exit; fsnotify_open(file); error = -ENOEXEC; read_lock(&binfmt_lock); list_for_each_entry(fmt, &formats, lh) { if (!fmt->load_shlib) continue; if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); error = fmt->load_shlib(file); read_lock(&binfmt_lock); put_binfmt(fmt); if (error != -ENOEXEC) break; } read_unlock(&binfmt_lock); exit: fput(file); out: return error; } #endif /* #ifdef CONFIG_USELIB */ #ifdef CONFIG_MMU /* * The nascent bprm->mm is not visible until exec_mmap() but it can * use a lot of memory, account these pages in current->mm temporary * for oom_badness()->get_mm_rss(). Once exec succeeds or fails, we * change the counter back via acct_arg_size(0). */ static void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) { struct mm_struct *mm = current->mm; long diff = (long)(pages - bprm->vma_pages); if (!mm || !diff) return; bprm->vma_pages = pages; add_mm_counter(mm, MM_ANONPAGES, diff); } static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, int write) { struct page *page; int ret; unsigned int gup_flags = FOLL_FORCE; #ifdef CONFIG_STACK_GROWSUP if (write) { ret = expand_downwards(bprm->vma, pos); if (ret < 0) return NULL; } #endif if (write) gup_flags |= FOLL_WRITE; /* * We are doing an exec(). 'current' is the process * doing the exec and bprm->mm is the new process's mm. */ ret = get_user_pages_remote(current, bprm->mm, pos, 1, gup_flags, &page, NULL, NULL); if (ret <= 0) return NULL; if (write) acct_arg_size(bprm, vma_pages(bprm->vma)); return page; } static void put_arg_page(struct page *page) { put_page(page); } static void free_arg_pages(struct linux_binprm *bprm) { } static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, struct page *page) { flush_cache_page(bprm->vma, pos, page_to_pfn(page)); } static int __bprm_mm_init(struct linux_binprm *bprm) { int err; struct vm_area_struct *vma = NULL; struct mm_struct *mm = bprm->mm; bprm->vma = vma = vm_area_alloc(mm); if (!vma) return -ENOMEM; vma_set_anonymous(vma); if (down_write_killable(&mm->mmap_sem)) { err = -EINTR; goto err_free; } /* * Place the stack at the largest stack address the architecture * supports. Later, we'll move this to an appropriate place. We don't * use STACK_TOP because that can depend on attributes which aren't * configured yet. */ BUILD_BUG_ON(VM_STACK_FLAGS & VM_STACK_INCOMPLETE_SETUP); vma->vm_end = STACK_TOP_MAX; vma->vm_start = vma->vm_end - PAGE_SIZE; vma->vm_flags = VM_SOFTDIRTY | VM_STACK_FLAGS | VM_STACK_INCOMPLETE_SETUP; vma->vm_page_prot = vm_get_page_prot(vma->vm_flags); err = insert_vm_struct(mm, vma); if (err) goto err; mm->stack_vm = mm->total_vm = 1; up_write(&mm->mmap_sem); bprm->p = vma->vm_end - sizeof(void *); return 0; err: up_write(&mm->mmap_sem); err_free: bprm->vma = NULL; vm_area_free(vma); return err; } static bool valid_arg_len(struct linux_binprm *bprm, long len) { return len <= MAX_ARG_STRLEN; } #else static inline void acct_arg_size(struct linux_binprm *bprm, unsigned long pages) { } static struct page *get_arg_page(struct linux_binprm *bprm, unsigned long pos, int write) { struct page *page; page = bprm->page[pos / PAGE_SIZE]; if (!page && write) { page = alloc_page(GFP_HIGHUSER|__GFP_ZERO); if (!page) return NULL; bprm->page[pos / PAGE_SIZE] = page; } return page; } static void put_arg_page(struct page *page) { } static void free_arg_page(struct linux_binprm *bprm, int i) { if (bprm->page[i]) { __free_page(bprm->page[i]); bprm->page[i] = NULL; } } static void free_arg_pages(struct linux_binprm *bprm) { int i; for (i = 0; i < MAX_ARG_PAGES; i++) free_arg_page(bprm, i); } static void flush_arg_page(struct linux_binprm *bprm, unsigned long pos, struct page *page) { } static int __bprm_mm_init(struct linux_binprm *bprm) { bprm->p = PAGE_SIZE * MAX_ARG_PAGES - sizeof(void *); return 0; } static bool valid_arg_len(struct linux_binprm *bprm, long len) { return len <= bprm->p; } #endif /* CONFIG_MMU */ /* * Create a new mm_struct and populate it with a temporary stack * vm_area_struct. We don't have enough context at this point to set the stack * flags, permissions, and offset, so we use temporary values. We'll update * them later in setup_arg_pages(). */ static int bprm_mm_init(struct linux_binprm *bprm) { int err; struct mm_struct *mm = NULL; bprm->mm = mm = mm_alloc(); err = -ENOMEM; if (!mm) goto err; /* Save current stack limit for all calculations made during exec. */ task_lock(current->group_leader); bprm->rlim_stack = current->signal->rlim[RLIMIT_STACK]; task_unlock(current->group_leader); err = __bprm_mm_init(bprm); if (err) goto err; return 0; err: if (mm) { bprm->mm = NULL; mmdrop(mm); } return err; } struct user_arg_ptr { #ifdef CONFIG_COMPAT bool is_compat; #endif union { const char __user *const __user *native; #ifdef CONFIG_COMPAT const compat_uptr_t __user *compat; #endif } ptr; }; static const char __user *get_user_arg_ptr(struct user_arg_ptr argv, int nr) { const char __user *native; #ifdef CONFIG_COMPAT if (unlikely(argv.is_compat)) { compat_uptr_t compat; if (get_user(compat, argv.ptr.compat + nr)) return ERR_PTR(-EFAULT); return compat_ptr(compat); } #endif if (get_user(native, argv.ptr.native + nr)) return ERR_PTR(-EFAULT); return native; } /* * count() counts the number of strings in array ARGV. */ static int count(struct user_arg_ptr argv, int max) { int i = 0; if (argv.ptr.native != NULL) { for (;;) { const char __user *p = get_user_arg_ptr(argv, i); if (!p) break; if (IS_ERR(p)) return -EFAULT; if (i >= max) return -E2BIG; ++i; if (fatal_signal_pending(current)) return -ERESTARTNOHAND; cond_resched(); } } return i; } static int prepare_arg_pages(struct linux_binprm *bprm, struct user_arg_ptr argv, struct user_arg_ptr envp) { unsigned long limit, ptr_size; bprm->argc = count(argv, MAX_ARG_STRINGS); if (bprm->argc < 0) return bprm->argc; bprm->envc = count(envp, MAX_ARG_STRINGS); if (bprm->envc < 0) return bprm->envc; /* * Limit to 1/4 of the max stack size or 3/4 of _STK_LIM * (whichever is smaller) for the argv+env strings. * This ensures that: * - the remaining binfmt code will not run out of stack space, * - the program will have a reasonable amount of stack left * to work from. */ limit = _STK_LIM / 4 * 3; limit = min(limit, bprm->rlim_stack.rlim_cur / 4); /* * We've historically supported up to 32 pages (ARG_MAX) * of argument strings even with small stacks */ limit = max_t(unsigned long, limit, ARG_MAX); /* * We must account for the size of all the argv and envp pointers to * the argv and envp strings, since they will also take up space in * the stack. They aren't stored until much later when we can't * signal to the parent that the child has run out of stack space. * Instead, calculate it here so it's possible to fail gracefully. */ ptr_size = (bprm->argc + bprm->envc) * sizeof(void *); if (limit <= ptr_size) return -E2BIG; limit -= ptr_size; bprm->argmin = bprm->p - limit; return 0; } /* * 'copy_strings()' copies argument/environment strings from the old * processes's memory to the new process's stack. The call to get_user_pages() * ensures the destination page is created and not swapped out. */ static int copy_strings(int argc, struct user_arg_ptr argv, struct linux_binprm *bprm) { struct page *kmapped_page = NULL; char *kaddr = NULL; unsigned long kpos = 0; int ret; while (argc-- > 0) { const char __user *str; int len; unsigned long pos; ret = -EFAULT; str = get_user_arg_ptr(argv, argc); if (IS_ERR(str)) goto out; len = strnlen_user(str, MAX_ARG_STRLEN); if (!len) goto out; ret = -E2BIG; if (!valid_arg_len(bprm, len)) goto out; /* We're going to work our way backwords. */ pos = bprm->p; str += len; bprm->p -= len; #ifdef CONFIG_MMU if (bprm->p < bprm->argmin) goto out; #endif while (len > 0) { int offset, bytes_to_copy; if (fatal_signal_pending(current)) { ret = -ERESTARTNOHAND; goto out; } cond_resched(); offset = pos % PAGE_SIZE; if (offset == 0) offset = PAGE_SIZE; bytes_to_copy = offset; if (bytes_to_copy > len) bytes_to_copy = len; offset -= bytes_to_copy; pos -= bytes_to_copy; str -= bytes_to_copy; len -= bytes_to_copy; if (!kmapped_page || kpos != (pos & PAGE_MASK)) { struct page *page; page = get_arg_page(bprm, pos, 1); if (!page) { ret = -E2BIG; goto out; } if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_arg_page(kmapped_page); } kmapped_page = page; kaddr = kmap(kmapped_page); kpos = pos & PAGE_MASK; flush_arg_page(bprm, kpos, kmapped_page); } if (copy_from_user(kaddr+offset, str, bytes_to_copy)) { ret = -EFAULT; goto out; } } } ret = 0; out: if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_arg_page(kmapped_page); } return ret; } /* * Like copy_strings, but get argv and its values from kernel memory. */ int copy_strings_kernel(int argc, const char *const *__argv, struct linux_binprm *bprm) { int r; mm_segment_t oldfs = get_fs(); struct user_arg_ptr argv = { .ptr.native = (const char __user *const __user *)__argv, }; set_fs(KERNEL_DS); r = copy_strings(argc, argv, bprm); set_fs(oldfs); return r; } EXPORT_SYMBOL(copy_strings_kernel); #ifdef CONFIG_MMU /* * During bprm_mm_init(), we create a temporary stack at STACK_TOP_MAX. Once * the binfmt code determines where the new stack should reside, we shift it to * its final location. The process proceeds as follows: * * 1) Use shift to calculate the new vma endpoints. * 2) Extend vma to cover both the old and new ranges. This ensures the * arguments passed to subsequent functions are consistent. * 3) Move vma's page tables to the new range. * 4) Free up any cleared pgd range. * 5) Shrink the vma to cover only the new range. */ static int shift_arg_pages(struct vm_area_struct *vma, unsigned long shift) { struct mm_struct *mm = vma->vm_mm; unsigned long old_start = vma->vm_start; unsigned long old_end = vma->vm_end; unsigned long length = old_end - old_start; unsigned long new_start = old_start - shift; unsigned long new_end = old_end - shift; struct mmu_gather tlb; BUG_ON(new_start > new_end); /* * ensure there are no vmas between where we want to go * and where we are */ if (vma != find_vma(mm, new_start)) return -EFAULT; /* * cover the whole range: [new_start, old_end) */ if (vma_adjust(vma, new_start, old_end, vma->vm_pgoff, NULL)) return -ENOMEM; /* * move the page tables downwards, on failure we rely on * process cleanup to remove whatever mess we made. */ if (length != move_page_tables(vma, old_start, vma, new_start, length, false)) return -ENOMEM; lru_add_drain(); tlb_gather_mmu(&tlb, mm, old_start, old_end); if (new_end > old_start) { /* * when the old and new regions overlap clear from new_end. */ free_pgd_range(&tlb, new_end, old_end, new_end, vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING); } else { /* * otherwise, clean from old_start; this is done to not touch * the address space in [new_end, old_start) some architectures * have constraints on va-space that make this illegal (IA64) - * for the others its just a little faster. */ free_pgd_range(&tlb, old_start, old_end, new_end, vma->vm_next ? vma->vm_next->vm_start : USER_PGTABLES_CEILING); } tlb_finish_mmu(&tlb, old_start, old_end); /* * Shrink the vma to just the new range. Always succeeds. */ vma_adjust(vma, new_start, new_end, vma->vm_pgoff, NULL); return 0; } /* * Finalizes the stack vm_area_struct. The flags and permissions are updated, * the stack is optionally relocated, and some extra space is added. */ int setup_arg_pages(struct linux_binprm *bprm, unsigned long stack_top, int executable_stack) { unsigned long ret; unsigned long stack_shift; struct mm_struct *mm = current->mm; struct vm_area_struct *vma = bprm->vma; struct vm_area_struct *prev = NULL; unsigned long vm_flags; unsigned long stack_base; unsigned long stack_size; unsigned long stack_expand; unsigned long rlim_stack; #ifdef CONFIG_STACK_GROWSUP /* Limit stack size */ stack_base = bprm->rlim_stack.rlim_max; if (stack_base > STACK_SIZE_MAX) stack_base = STACK_SIZE_MAX; /* Add space for stack randomization. */ stack_base += (STACK_RND_MASK << PAGE_SHIFT); /* Make sure we didn't let the argument array grow too large. */ if (vma->vm_end - vma->vm_start > stack_base) return -ENOMEM; stack_base = PAGE_ALIGN(stack_top - stack_base); stack_shift = vma->vm_start - stack_base; mm->arg_start = bprm->p - stack_shift; bprm->p = vma->vm_end - stack_shift; #else stack_top = arch_align_stack(stack_top); stack_top = PAGE_ALIGN(stack_top); if (unlikely(stack_top < mmap_min_addr) || unlikely(vma->vm_end - vma->vm_start >= stack_top - mmap_min_addr)) return -ENOMEM; stack_shift = vma->vm_end - stack_top; bprm->p -= stack_shift; mm->arg_start = bprm->p; #endif if (bprm->loader) bprm->loader -= stack_shift; bprm->exec -= stack_shift; if (down_write_killable(&mm->mmap_sem)) return -EINTR; vm_flags = VM_STACK_FLAGS; /* * Adjust stack execute permissions; explicitly enable for * EXSTACK_ENABLE_X, disable for EXSTACK_DISABLE_X and leave alone * (arch default) otherwise. */ if (unlikely(executable_stack == EXSTACK_ENABLE_X)) vm_flags |= VM_EXEC; else if (executable_stack == EXSTACK_DISABLE_X) vm_flags &= ~VM_EXEC; vm_flags |= mm->def_flags; vm_flags |= VM_STACK_INCOMPLETE_SETUP; ret = mprotect_fixup(vma, &prev, vma->vm_start, vma->vm_end, vm_flags); if (ret) goto out_unlock; BUG_ON(prev != vma); if (unlikely(vm_flags & VM_EXEC)) { pr_warn_once("process '%pD4' started with executable stack\n", bprm->file); } /* Move stack pages down in memory. */ if (stack_shift) { ret = shift_arg_pages(vma, stack_shift); if (ret) goto out_unlock; } /* mprotect_fixup is overkill to remove the temporary stack flags */ vma->vm_flags &= ~VM_STACK_INCOMPLETE_SETUP; stack_expand = 131072UL; /* randomly 32*4k (or 2*64k) pages */ stack_size = vma->vm_end - vma->vm_start; /* * Align this down to a page boundary as expand_stack * will align it up. */ rlim_stack = bprm->rlim_stack.rlim_cur & PAGE_MASK; #ifdef CONFIG_STACK_GROWSUP if (stack_size + stack_expand > rlim_stack) stack_base = vma->vm_start + rlim_stack; else stack_base = vma->vm_end + stack_expand; #else if (stack_size + stack_expand > rlim_stack) stack_base = vma->vm_end - rlim_stack; else stack_base = vma->vm_start - stack_expand; #endif current->mm->start_stack = bprm->p; ret = expand_stack(vma, stack_base); if (ret) ret = -EFAULT; out_unlock: up_write(&mm->mmap_sem); return ret; } EXPORT_SYMBOL(setup_arg_pages); #else /* * Transfer the program arguments and environment from the holding pages * onto the stack. The provided stack pointer is adjusted accordingly. */ int transfer_args_to_stack(struct linux_binprm *bprm, unsigned long *sp_location) { unsigned long index, stop, sp; int ret = 0; stop = bprm->p >> PAGE_SHIFT; sp = *sp_location; for (index = MAX_ARG_PAGES - 1; index >= stop; index--) { unsigned int offset = index == stop ? bprm->p & ~PAGE_MASK : 0; char *src = kmap(bprm->page[index]) + offset; sp -= PAGE_SIZE - offset; if (copy_to_user((void *) sp, src, PAGE_SIZE - offset) != 0) ret = -EFAULT; kunmap(bprm->page[index]); if (ret) goto out; } *sp_location = sp; out: return ret; } EXPORT_SYMBOL(transfer_args_to_stack); #endif /* CONFIG_MMU */ static struct file *do_open_execat(int fd, struct filename *name, int flags) { struct file *file; int err; struct open_flags open_exec_flags = { .open_flag = O_LARGEFILE | O_RDONLY | __FMODE_EXEC, .acc_mode = MAY_EXEC, .intent = LOOKUP_OPEN, .lookup_flags = LOOKUP_FOLLOW, }; if ((flags & ~(AT_SYMLINK_NOFOLLOW | AT_EMPTY_PATH)) != 0) return ERR_PTR(-EINVAL); if (flags & AT_SYMLINK_NOFOLLOW) open_exec_flags.lookup_flags &= ~LOOKUP_FOLLOW; if (flags & AT_EMPTY_PATH) open_exec_flags.lookup_flags |= LOOKUP_EMPTY; file = do_filp_open(fd, name, &open_exec_flags); if (IS_ERR(file)) goto out; err = -EACCES; if (!S_ISREG(file_inode(file)->i_mode)) goto exit; if (path_noexec(&file->f_path)) goto exit; err = deny_write_access(file); if (err) goto exit; if (name->name[0] != '\0') fsnotify_open(file); out: return file; exit: fput(file); return ERR_PTR(err); } struct file *open_exec(const char *name) { struct filename *filename = getname_kernel(name); struct file *f = ERR_CAST(filename); if (!IS_ERR(filename)) { f = do_open_execat(AT_FDCWD, filename, 0); putname(filename); } return f; } EXPORT_SYMBOL(open_exec); int kernel_read_file(struct file *file, void **buf, loff_t *size, loff_t max_size, enum kernel_read_file_id id) { loff_t i_size, pos; ssize_t bytes = 0; int ret; if (!S_ISREG(file_inode(file)->i_mode) || max_size < 0) return -EINVAL; ret = deny_write_access(file); if (ret) return ret; ret = security_kernel_read_file(file, id); if (ret) goto out; i_size = i_size_read(file_inode(file)); if (i_size <= 0) { ret = -EINVAL; goto out; } if (i_size > SIZE_MAX || (max_size > 0 && i_size > max_size)) { ret = -EFBIG; goto out; } if (id != READING_FIRMWARE_PREALLOC_BUFFER) *buf = vmalloc(i_size); if (!*buf) { ret = -ENOMEM; goto out; } pos = 0; while (pos < i_size) { bytes = kernel_read(file, *buf + pos, i_size - pos, &pos); if (bytes < 0) { ret = bytes; goto out_free; } if (bytes == 0) break; } if (pos != i_size) { ret = -EIO; goto out_free; } ret = security_kernel_post_read_file(file, *buf, i_size, id); if (!ret) *size = pos; out_free: if (ret < 0) { if (id != READING_FIRMWARE_PREALLOC_BUFFER) { vfree(*buf); *buf = NULL; } } out: allow_write_access(file); return ret; } EXPORT_SYMBOL_GPL(kernel_read_file); int kernel_read_file_from_path(const char *path, void **buf, loff_t *size, loff_t max_size, enum kernel_read_file_id id) { struct file *file; int ret; if (!path || !*path) return -EINVAL; file = filp_open(path, O_RDONLY, 0); if (IS_ERR(file)) return PTR_ERR(file); ret = kernel_read_file(file, buf, size, max_size, id); fput(file); return ret; } EXPORT_SYMBOL_GPL(kernel_read_file_from_path); int kernel_read_file_from_fd(int fd, void **buf, loff_t *size, loff_t max_size, enum kernel_read_file_id id) { struct fd f = fdget(fd); int ret = -EBADF; if (!f.file) goto out; ret = kernel_read_file(f.file, buf, size, max_size, id); out: fdput(f); return ret; } EXPORT_SYMBOL_GPL(kernel_read_file_from_fd); ssize_t read_code(struct file *file, unsigned long addr, loff_t pos, size_t len) { ssize_t res = vfs_read(file, (void __user *)addr, len, &pos); if (res > 0) flush_icache_range(addr, addr + len); return res; } EXPORT_SYMBOL(read_code); static int exec_mmap(struct mm_struct *mm) { struct task_struct *tsk; struct mm_struct *old_mm, *active_mm; /* Notify parent that we're no longer interested in the old VM */ tsk = current; old_mm = current->mm; exec_mm_release(tsk, old_mm); if (old_mm) { sync_mm_rss(old_mm); /* * Make sure that if there is a core dump in progress * for the old mm, we get out and die instead of going * through with the exec. We must hold mmap_sem around * checking core_state and changing tsk->mm. */ down_read(&old_mm->mmap_sem); if (unlikely(old_mm->core_state)) { up_read(&old_mm->mmap_sem); return -EINTR; } } task_lock(tsk); active_mm = tsk->active_mm; membarrier_exec_mmap(mm); tsk->mm = mm; tsk->active_mm = mm; activate_mm(active_mm, mm); tsk->mm->vmacache_seqnum = 0; vmacache_flush(tsk); task_unlock(tsk); if (old_mm) { up_read(&old_mm->mmap_sem); BUG_ON(active_mm != old_mm); setmax_mm_hiwater_rss(&tsk->signal->maxrss, old_mm); mm_update_next_owner(old_mm); mmput(old_mm); return 0; } mmdrop(active_mm); return 0; } /* * This function makes sure the current process has its own signal table, * so that flush_signal_handlers can later reset the handlers without * disturbing other processes. (Other processes might share the signal * table via the CLONE_SIGHAND option to clone().) */ static int de_thread(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; struct sighand_struct *oldsighand = tsk->sighand; spinlock_t *lock = &oldsighand->siglock; if (thread_group_empty(tsk)) goto no_thread_group; /* * Kill all other threads in the thread group. */ spin_lock_irq(lock); if (signal_group_exit(sig)) { /* * Another group action in progress, just * return so that the signal is processed. */ spin_unlock_irq(lock); return -EAGAIN; } sig->group_exit_task = tsk; sig->notify_count = zap_other_threads(tsk); if (!thread_group_leader(tsk)) sig->notify_count--; while (sig->notify_count) { __set_current_state(TASK_KILLABLE); spin_unlock_irq(lock); schedule(); if (__fatal_signal_pending(tsk)) goto killed; spin_lock_irq(lock); } spin_unlock_irq(lock); /* * At this point all other threads have exited, all we have to * do is to wait for the thread group leader to become inactive, * and to assume its PID: */ if (!thread_group_leader(tsk)) { struct task_struct *leader = tsk->group_leader; for (;;) { cgroup_threadgroup_change_begin(tsk); write_lock_irq(&tasklist_lock); /* * Do this under tasklist_lock to ensure that * exit_notify() can't miss ->group_exit_task */ sig->notify_count = -1; if (likely(leader->exit_state)) break; __set_current_state(TASK_KILLABLE); write_unlock_irq(&tasklist_lock); cgroup_threadgroup_change_end(tsk); schedule(); if (__fatal_signal_pending(tsk)) goto killed; } /* * The only record we have of the real-time age of a * process, regardless of execs it's done, is start_time. * All the past CPU time is accumulated in signal_struct * from sister threads now dead. But in this non-leader * exec, nothing survives from the original leader thread, * whose birth marks the true age of this process now. * When we take on its identity by switching to its PID, we * also take its birthdate (always earlier than our own). */ tsk->start_time = leader->start_time; tsk->start_boottime = leader->start_boottime; BUG_ON(!same_thread_group(leader, tsk)); BUG_ON(has_group_leader_pid(tsk)); /* * An exec() starts a new thread group with the * TGID of the previous thread group. Rehash the * two threads with a switched PID, and release * the former thread group leader: */ /* Become a process group leader with the old leader's pid. * The old leader becomes a thread of the this thread group. * Note: The old leader also uses this pid until release_task * is called. Odd but simple and correct. */ tsk->pid = leader->pid; change_pid(tsk, PIDTYPE_PID, task_pid(leader)); transfer_pid(leader, tsk, PIDTYPE_TGID); transfer_pid(leader, tsk, PIDTYPE_PGID); transfer_pid(leader, tsk, PIDTYPE_SID); list_replace_rcu(&leader->tasks, &tsk->tasks); list_replace_init(&leader->sibling, &tsk->sibling); tsk->group_leader = tsk; leader->group_leader = tsk; tsk->exit_signal = SIGCHLD; leader->exit_signal = -1; BUG_ON(leader->exit_state != EXIT_ZOMBIE); leader->exit_state = EXIT_DEAD; /* * We are going to release_task()->ptrace_unlink() silently, * the tracer can sleep in do_wait(). EXIT_DEAD guarantees * the tracer wont't block again waiting for this thread. */ if (unlikely(leader->ptrace)) __wake_up_parent(leader, leader->parent); write_unlock_irq(&tasklist_lock); cgroup_threadgroup_change_end(tsk); release_task(leader); } sig->group_exit_task = NULL; sig->notify_count = 0; no_thread_group: /* we have changed execution domain */ tsk->exit_signal = SIGCHLD; #ifdef CONFIG_POSIX_TIMERS exit_itimers(sig); flush_itimer_signals(); #endif if (refcount_read(&oldsighand->count) != 1) { struct sighand_struct *newsighand; /* * This ->sighand is shared with the CLONE_SIGHAND * but not CLONE_THREAD task, switch to the new one. */ newsighand = kmem_cache_alloc(sighand_cachep, GFP_KERNEL); if (!newsighand) return -ENOMEM; refcount_set(&newsighand->count, 1); memcpy(newsighand->action, oldsighand->action, sizeof(newsighand->action)); write_lock_irq(&tasklist_lock); spin_lock(&oldsighand->siglock); rcu_assign_pointer(tsk->sighand, newsighand); spin_unlock(&oldsighand->siglock); write_unlock_irq(&tasklist_lock); __cleanup_sighand(oldsighand); } BUG_ON(!thread_group_leader(tsk)); return 0; killed: /* protects against exit_notify() and __exit_signal() */ read_lock(&tasklist_lock); sig->group_exit_task = NULL; sig->notify_count = 0; read_unlock(&tasklist_lock); return -EAGAIN; } char *__get_task_comm(char *buf, size_t buf_size, struct task_struct *tsk) { task_lock(tsk); strncpy(buf, tsk->comm, buf_size); task_unlock(tsk); return buf; } EXPORT_SYMBOL_GPL(__get_task_comm); /* * These functions flushes out all traces of the currently running executable * so that a new one can be started */ void __set_task_comm(struct task_struct *tsk, const char *buf, bool exec) { task_lock(tsk); trace_task_rename(tsk, buf); strlcpy(tsk->comm, buf, sizeof(tsk->comm)); task_unlock(tsk); perf_event_comm(tsk, exec); } /* * Calling this is the point of no return. None of the failures will be * seen by userspace since either the process is already taking a fatal * signal (via de_thread() or coredump), or will have SEGV raised * (after exec_mmap()) by search_binary_handlers (see below). */ int flush_old_exec(struct linux_binprm * bprm) { int retval; /* * Make sure we have a private signal table and that * we are unassociated from the previous thread group. */ retval = de_thread(current); if (retval) goto out; /* * Must be called _before_ exec_mmap() as bprm->mm is * not visibile until then. This also enables the update * to be lockless. */ set_mm_exe_file(bprm->mm, bprm->file); /* * Release all of the old mmap stuff */ acct_arg_size(bprm, 0); retval = exec_mmap(bprm->mm); if (retval) goto out; /* * After clearing bprm->mm (to mark that current is using the * prepared mm now), we have nothing left of the original * process. If anything from here on returns an error, the check * in search_binary_handler() will SEGV current. */ bprm->mm = NULL; set_fs(USER_DS); current->flags &= ~(PF_RANDOMIZE | PF_FORKNOEXEC | PF_KTHREAD | PF_NOFREEZE | PF_NO_SETAFFINITY); flush_thread(); current->personality &= ~bprm->per_clear; /* * We have to apply CLOEXEC before we change whether the process is * dumpable (in setup_new_exec) to avoid a race with a process in userspace * trying to access the should-be-closed file descriptors of a process * undergoing exec(2). */ do_close_on_exec(current->files); return 0; out: return retval; } EXPORT_SYMBOL(flush_old_exec); void would_dump(struct linux_binprm *bprm, struct file *file) { struct inode *inode = file_inode(file); if (inode_permission(inode, MAY_READ) < 0) { struct user_namespace *old, *user_ns; bprm->interp_flags |= BINPRM_FLAGS_ENFORCE_NONDUMP; /* Ensure mm->user_ns contains the executable */ user_ns = old = bprm->mm->user_ns; while ((user_ns != &init_user_ns) && !privileged_wrt_inode_uidgid(user_ns, inode)) user_ns = user_ns->parent; if (old != user_ns) { bprm->mm->user_ns = get_user_ns(user_ns); put_user_ns(old); } } } EXPORT_SYMBOL(would_dump); void setup_new_exec(struct linux_binprm * bprm) { /* * Once here, prepare_binrpm() will not be called any more, so * the final state of setuid/setgid/fscaps can be merged into the * secureexec flag. */ bprm->secureexec |= bprm->cap_elevated; if (bprm->secureexec) { /* Make sure parent cannot signal privileged process. */ current->pdeath_signal = 0; /* * For secureexec, reset the stack limit to sane default to * avoid bad behavior from the prior rlimits. This has to * happen before arch_pick_mmap_layout(), which examines * RLIMIT_STACK, but after the point of no return to avoid * needing to clean up the change on failure. */ if (bprm->rlim_stack.rlim_cur > _STK_LIM) bprm->rlim_stack.rlim_cur = _STK_LIM; } arch_pick_mmap_layout(current->mm, &bprm->rlim_stack); current->sas_ss_sp = current->sas_ss_size = 0; /* * Figure out dumpability. Note that this checking only of current * is wrong, but userspace depends on it. This should be testing * bprm->secureexec instead. */ if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP || !(uid_eq(current_euid(), current_uid()) && gid_eq(current_egid(), current_gid()))) set_dumpable(current->mm, suid_dumpable); else set_dumpable(current->mm, SUID_DUMP_USER); arch_setup_new_exec(); perf_event_exec(); __set_task_comm(current, kbasename(bprm->filename), true); /* Set the new mm task size. We have to do that late because it may * depend on TIF_32BIT which is only updated in flush_thread() on * some architectures like powerpc */ current->mm->task_size = TASK_SIZE; /* An exec changes our domain. We are no longer part of the thread group */ WRITE_ONCE(current->self_exec_id, current->self_exec_id + 1); flush_signal_handlers(current, 0); } EXPORT_SYMBOL(setup_new_exec); /* Runs immediately before start_thread() takes over. */ void finalize_exec(struct linux_binprm *bprm) { /* Store any stack rlimit changes before starting thread. */ task_lock(current->group_leader); current->signal->rlim[RLIMIT_STACK] = bprm->rlim_stack; task_unlock(current->group_leader); } EXPORT_SYMBOL(finalize_exec); /* * Prepare credentials and lock ->cred_guard_mutex. * install_exec_creds() commits the new creds and drops the lock. * Or, if exec fails before, free_bprm() should release ->cred and * and unlock. */ static int prepare_bprm_creds(struct linux_binprm *bprm) { if (mutex_lock_interruptible(&current->signal->cred_guard_mutex)) return -ERESTARTNOINTR; bprm->cred = prepare_exec_creds(); if (likely(bprm->cred)) return 0; mutex_unlock(&current->signal->cred_guard_mutex); return -ENOMEM; } static void free_bprm(struct linux_binprm *bprm) { free_arg_pages(bprm); if (bprm->cred) { mutex_unlock(&current->signal->cred_guard_mutex); abort_creds(bprm->cred); } if (bprm->file) { allow_write_access(bprm->file); fput(bprm->file); } /* If a binfmt changed the interp, free it. */ if (bprm->interp != bprm->filename) kfree(bprm->interp); kfree(bprm); } int bprm_change_interp(const char *interp, struct linux_binprm *bprm) { /* If a binfmt changed the interp, free it first. */ if (bprm->interp != bprm->filename) kfree(bprm->interp); bprm->interp = kstrdup(interp, GFP_KERNEL); if (!bprm->interp) return -ENOMEM; return 0; } EXPORT_SYMBOL(bprm_change_interp); /* * install the new credentials for this executable */ void install_exec_creds(struct linux_binprm *bprm) { security_bprm_committing_creds(bprm); commit_creds(bprm->cred); bprm->cred = NULL; /* * Disable monitoring for regular users * when executing setuid binaries. Must * wait until new credentials are committed * by commit_creds() above */ if (get_dumpable(current->mm) != SUID_DUMP_USER) perf_event_exit_task(current); /* * cred_guard_mutex must be held at least to this point to prevent * ptrace_attach() from altering our determination of the task's * credentials; any time after this it may be unlocked. */ security_bprm_committed_creds(bprm); mutex_unlock(&current->signal->cred_guard_mutex); } EXPORT_SYMBOL(install_exec_creds); /* * determine how safe it is to execute the proposed program * - the caller must hold ->cred_guard_mutex to protect against * PTRACE_ATTACH or seccomp thread-sync */ static void check_unsafe_exec(struct linux_binprm *bprm) { struct task_struct *p = current, *t; unsigned n_fs; if (p->ptrace) bprm->unsafe |= LSM_UNSAFE_PTRACE; /* * This isn't strictly necessary, but it makes it harder for LSMs to * mess up. */ if (task_no_new_privs(current)) bprm->unsafe |= LSM_UNSAFE_NO_NEW_PRIVS; t = p; n_fs = 1; spin_lock(&p->fs->lock); rcu_read_lock(); while_each_thread(p, t) { if (t->fs == p->fs) n_fs++; } rcu_read_unlock(); if (p->fs->users > n_fs) bprm->unsafe |= LSM_UNSAFE_SHARE; else p->fs->in_exec = 1; spin_unlock(&p->fs->lock); } static void bprm_fill_uid(struct linux_binprm *bprm) { struct inode *inode; unsigned int mode; kuid_t uid; kgid_t gid; /* * Since this can be called multiple times (via prepare_binprm), * we must clear any previous work done when setting set[ug]id * bits from any earlier bprm->file uses (for example when run * first for a setuid script then again for its interpreter). */ bprm->cred->euid = current_euid(); bprm->cred->egid = current_egid(); if (!mnt_may_suid(bprm->file->f_path.mnt)) return; if (task_no_new_privs(current)) return; inode = bprm->file->f_path.dentry->d_inode; mode = READ_ONCE(inode->i_mode); if (!(mode & (S_ISUID|S_ISGID))) return; /* Be careful if suid/sgid is set */ inode_lock(inode); /* reload atomically mode/uid/gid now that lock held */ mode = inode->i_mode; uid = inode->i_uid; gid = inode->i_gid; inode_unlock(inode); /* We ignore suid/sgid if there are no mappings for them in the ns */ if (!kuid_has_mapping(bprm->cred->user_ns, uid) || !kgid_has_mapping(bprm->cred->user_ns, gid)) return; if (mode & S_ISUID) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->euid = uid; } if ((mode & (S_ISGID | S_IXGRP)) == (S_ISGID | S_IXGRP)) { bprm->per_clear |= PER_CLEAR_ON_SETID; bprm->cred->egid = gid; } } /* * Fill the binprm structure from the inode. * Check permissions, then read the first BINPRM_BUF_SIZE bytes * * This may be called multiple times for binary chains (scripts for example). */ int prepare_binprm(struct linux_binprm *bprm) { int retval; loff_t pos = 0; bprm_fill_uid(bprm); /* fill in binprm security blob */ retval = security_bprm_set_creds(bprm); if (retval) return retval; bprm->called_set_creds = 1; memset(bprm->buf, 0, BINPRM_BUF_SIZE); return kernel_read(bprm->file, bprm->buf, BINPRM_BUF_SIZE, &pos); } EXPORT_SYMBOL(prepare_binprm); /* * Arguments are '\0' separated strings found at the location bprm->p * points to; chop off the first by relocating brpm->p to right after * the first '\0' encountered. */ int remove_arg_zero(struct linux_binprm *bprm) { int ret = 0; unsigned long offset; char *kaddr; struct page *page; if (!bprm->argc) return 0; do { offset = bprm->p & ~PAGE_MASK; page = get_arg_page(bprm, bprm->p, 0); if (!page) { ret = -EFAULT; goto out; } kaddr = kmap_atomic(page); for (; offset < PAGE_SIZE && kaddr[offset]; offset++, bprm->p++) ; kunmap_atomic(kaddr); put_arg_page(page); } while (offset == PAGE_SIZE); bprm->p++; bprm->argc--; ret = 0; out: return ret; } EXPORT_SYMBOL(remove_arg_zero); #define printable(c) (((c)=='\t') || ((c)=='\n') || (0x20<=(c) && (c)<=0x7e)) /* * cycle the list of binary formats handler, until one recognizes the image */ int search_binary_handler(struct linux_binprm *bprm) { bool need_retry = IS_ENABLED(CONFIG_MODULES); struct linux_binfmt *fmt; int retval; /* This allows 4 levels of binfmt rewrites before failing hard. */ if (bprm->recursion_depth > 5) return -ELOOP; retval = security_bprm_check(bprm); if (retval) return retval; retval = -ENOENT; retry: read_lock(&binfmt_lock); list_for_each_entry(fmt, &formats, lh) { if (!try_module_get(fmt->module)) continue; read_unlock(&binfmt_lock); bprm->recursion_depth++; retval = fmt->load_binary(bprm); bprm->recursion_depth--; read_lock(&binfmt_lock); put_binfmt(fmt); if (retval < 0 && !bprm->mm) { /* we got to flush_old_exec() and failed after it */ read_unlock(&binfmt_lock); force_sigsegv(SIGSEGV); return retval; } if (retval != -ENOEXEC || !bprm->file) { read_unlock(&binfmt_lock); return retval; } } read_unlock(&binfmt_lock); if (need_retry) { if (printable(bprm->buf[0]) && printable(bprm->buf[1]) && printable(bprm->buf[2]) && printable(bprm->buf[3])) return retval; if (request_module("binfmt-%04x", *(ushort *)(bprm->buf + 2)) < 0) return retval; need_retry = false; goto retry; } return retval; } EXPORT_SYMBOL(search_binary_handler); static int exec_binprm(struct linux_binprm *bprm) { pid_t old_pid, old_vpid; int ret; /* Need to fetch pid before load_binary changes it */ old_pid = current->pid; rcu_read_lock(); old_vpid = task_pid_nr_ns(current, task_active_pid_ns(current->parent)); rcu_read_unlock(); ret = search_binary_handler(bprm); if (ret >= 0) { audit_bprm(bprm); trace_sched_process_exec(current, old_pid, bprm); ptrace_event(PTRACE_EVENT_EXEC, old_vpid); proc_exec_connector(current); } return ret; } /* * sys_execve() executes a new program. */ static int __do_execve_file(int fd, struct filename *filename, struct user_arg_ptr argv, struct user_arg_ptr envp, int flags, struct file *file) { char *pathbuf = NULL; struct linux_binprm *bprm; struct files_struct *displaced; int retval; if (IS_ERR(filename)) return PTR_ERR(filename); /* * We move the actual failure in case of RLIMIT_NPROC excess from * set*uid() to execve() because too many poorly written programs * don't check setuid() return code. Here we additionally recheck * whether NPROC limit is still exceeded. */ if ((current->flags & PF_NPROC_EXCEEDED) && atomic_read(&current_user()->processes) > rlimit(RLIMIT_NPROC)) { retval = -EAGAIN; goto out_ret; } /* We're below the limit (still or again), so we don't want to make * further execve() calls fail. */ current->flags &= ~PF_NPROC_EXCEEDED; retval = unshare_files(&displaced); if (retval) goto out_ret; retval = -ENOMEM; bprm = kzalloc(sizeof(*bprm), GFP_KERNEL); if (!bprm) goto out_files; retval = prepare_bprm_creds(bprm); if (retval) goto out_free; check_unsafe_exec(bprm); current->in_execve = 1; if (!file) file = do_open_execat(fd, filename, flags); retval = PTR_ERR(file); if (IS_ERR(file)) goto out_unmark; sched_exec(); bprm->file = file; if (!filename) { bprm->filename = "none"; } else if (fd == AT_FDCWD || filename->name[0] == '/') { bprm->filename = filename->name; } else { if (filename->name[0] == '\0') pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d", fd); else pathbuf = kasprintf(GFP_KERNEL, "/dev/fd/%d/%s", fd, filename->name); if (!pathbuf) { retval = -ENOMEM; goto out_unmark; } /* * Record that a name derived from an O_CLOEXEC fd will be * inaccessible after exec. Relies on having exclusive access to * current->files (due to unshare_files above). */ if (close_on_exec(fd, rcu_dereference_raw(current->files->fdt))) bprm->interp_flags |= BINPRM_FLAGS_PATH_INACCESSIBLE; bprm->filename = pathbuf; } bprm->interp = bprm->filename; retval = bprm_mm_init(bprm); if (retval) goto out_unmark; retval = prepare_arg_pages(bprm, argv, envp); if (retval < 0) goto out; retval = prepare_binprm(bprm); if (retval < 0) goto out; retval = copy_strings_kernel(1, &bprm->filename, bprm); if (retval < 0) goto out; bprm->exec = bprm->p; retval = copy_strings(bprm->envc, envp, bprm); if (retval < 0) goto out; retval = copy_strings(bprm->argc, argv, bprm); if (retval < 0) goto out; would_dump(bprm, bprm->file); retval = exec_binprm(bprm); if (retval < 0) goto out; /* execve succeeded */ current->fs->in_exec = 0; current->in_execve = 0; rseq_execve(current); acct_update_integrals(current); task_numa_free(current, false); free_bprm(bprm); kfree(pathbuf); if (filename) putname(filename); if (displaced) put_files_struct(displaced); return retval; out: if (bprm->mm) { acct_arg_size(bprm, 0); mmput(bprm->mm); } out_unmark: current->fs->in_exec = 0; current->in_execve = 0; out_free: free_bprm(bprm); kfree(pathbuf); out_files: if (displaced) reset_files_struct(displaced); out_ret: if (filename) putname(filename); return retval; } static int do_execveat_common(int fd, struct filename *filename, struct user_arg_ptr argv, struct user_arg_ptr envp, int flags) { return __do_execve_file(fd, filename, argv, envp, flags, NULL); } int do_execve_file(struct file *file, void *__argv, void *__envp) { struct user_arg_ptr argv = { .ptr.native = __argv }; struct user_arg_ptr envp = { .ptr.native = __envp }; return __do_execve_file(AT_FDCWD, NULL, argv, envp, 0, file); } int do_execve(struct filename *filename, const char __user *const __user *__argv, const char __user *const __user *__envp) { struct user_arg_ptr argv = { .ptr.native = __argv }; struct user_arg_ptr envp = { .ptr.native = __envp }; return do_execveat_common(AT_FDCWD, filename, argv, envp, 0); } int do_execveat(int fd, struct filename *filename, const char __user *const __user *__argv, const char __user *const __user *__envp, int flags) { struct user_arg_ptr argv = { .ptr.native = __argv }; struct user_arg_ptr envp = { .ptr.native = __envp }; return do_execveat_common(fd, filename, argv, envp, flags); } #ifdef CONFIG_COMPAT static int compat_do_execve(struct filename *filename, const compat_uptr_t __user *__argv, const compat_uptr_t __user *__envp) { struct user_arg_ptr argv = { .is_compat = true, .ptr.compat = __argv, }; struct user_arg_ptr envp = { .is_compat = true, .ptr.compat = __envp, }; return do_execveat_common(AT_FDCWD, filename, argv, envp, 0); } static int compat_do_execveat(int fd, struct filename *filename, const compat_uptr_t __user *__argv, const compat_uptr_t __user *__envp, int flags) { struct user_arg_ptr argv = { .is_compat = true, .ptr.compat = __argv, }; struct user_arg_ptr envp = { .is_compat = true, .ptr.compat = __envp, }; return do_execveat_common(fd, filename, argv, envp, flags); } #endif void set_binfmt(struct linux_binfmt *new) { struct mm_struct *mm = current->mm; if (mm->binfmt) module_put(mm->binfmt->module); mm->binfmt = new; if (new) __module_get(new->module); } EXPORT_SYMBOL(set_binfmt); /* * set_dumpable stores three-value SUID_DUMP_* into mm->flags. */ void set_dumpable(struct mm_struct *mm, int value) { if (WARN_ON((unsigned)value > SUID_DUMP_ROOT)) return; set_mask_bits(&mm->flags, MMF_DUMPABLE_MASK, value); } SYSCALL_DEFINE3(execve, const char __user *, filename, const char __user *const __user *, argv, const char __user *const __user *, envp) { return do_execve(getname(filename), argv, envp); } SYSCALL_DEFINE5(execveat, int, fd, const char __user *, filename, const char __user *const __user *, argv, const char __user *const __user *, envp, int, flags) { int lookup_flags = (flags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0; return do_execveat(fd, getname_flags(filename, lookup_flags, NULL), argv, envp, flags); } #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE3(execve, const char __user *, filename, const compat_uptr_t __user *, argv, const compat_uptr_t __user *, envp) { return compat_do_execve(getname(filename), argv, envp); } COMPAT_SYSCALL_DEFINE5(execveat, int, fd, const char __user *, filename, const compat_uptr_t __user *, argv, const compat_uptr_t __user *, envp, int, flags) { int lookup_flags = (flags & AT_EMPTY_PATH) ? LOOKUP_EMPTY : 0; return compat_do_execveat(fd, getname_flags(filename, lookup_flags, NULL), argv, envp, flags); } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_4015_0
crossvul-cpp_data_bad_111_0
/* * 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. */ #include "delta.h" /* maximum hash entry list for the same hash bucket */ #define HASH_LIMIT 64 #define RABIN_SHIFT 23 #define RABIN_WINDOW 16 static const unsigned int T[256] = { 0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344, 0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259, 0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85, 0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2, 0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a, 0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db, 0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753, 0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964, 0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8, 0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5, 0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81, 0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6, 0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e, 0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77, 0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff, 0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8, 0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc, 0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1, 0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d, 0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a, 0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2, 0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02, 0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a, 0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd, 0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61, 0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c, 0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08, 0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f, 0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7, 0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe, 0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76, 0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141, 0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65, 0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78, 0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4, 0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93, 0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b, 0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa, 0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872, 0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645, 0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99, 0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84, 0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811 }; static const unsigned int U[256] = { 0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a, 0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48, 0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511, 0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d, 0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8, 0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe, 0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb, 0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937, 0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e, 0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c, 0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d, 0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1, 0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4, 0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa, 0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef, 0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263, 0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302, 0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000, 0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59, 0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5, 0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90, 0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7, 0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2, 0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e, 0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467, 0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765, 0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604, 0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88, 0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd, 0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3, 0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996, 0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a, 0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b, 0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609, 0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50, 0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc, 0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99, 0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf, 0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa, 0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176, 0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f, 0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d, 0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a }; struct index_entry { const unsigned char *ptr; unsigned int val; struct index_entry *next; }; struct git_delta_index { unsigned long memsize; const void *src_buf; size_t src_size; unsigned int hash_mask; struct index_entry *hash[GIT_FLEX_ARRAY]; }; static int lookup_index_alloc( void **out, unsigned long *out_len, size_t entries, size_t hash_count) { size_t entries_len, hash_len, index_len; GITERR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry)); GITERR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *)); GITERR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len); GITERR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len); if (!git__is_ulong(index_len)) { giterr_set(GITERR_NOMEMORY, "overly large delta"); return -1; } *out = git__malloc(index_len); GITERR_CHECK_ALLOC(*out); *out_len = index_len; return 0; } int git_delta_index_init( git_delta_index **out, const void *buf, size_t bufsize) { unsigned int i, hsize, hmask, entries, prev_val, *hash_count; const unsigned char *data, *buffer = buf; struct git_delta_index *index; struct index_entry *entry, **hash; void *mem; unsigned long memsize; *out = NULL; if (!buf || !bufsize) return 0; /* Determine index hash size. Note that indexing skips the first byte to allow for optimizing the rabin polynomial initialization in create_delta(). */ entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW; if (bufsize >= 0xffffffffUL) { /* * Current delta format can't encode offsets into * reference buffer with more than 32 bits. */ entries = 0xfffffffeU / RABIN_WINDOW; } hsize = entries / 4; for (i = 4; i < 31 && (1u << i) < hsize; i++); hsize = 1 << i; hmask = hsize - 1; if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0) return -1; index = mem; mem = index->hash; hash = mem; mem = hash + hsize; entry = mem; index->memsize = memsize; index->src_buf = buf; index->src_size = bufsize; index->hash_mask = hmask; memset(hash, 0, hsize * sizeof(*hash)); /* allocate an array to count hash entries */ hash_count = git__calloc(hsize, sizeof(*hash_count)); if (!hash_count) { git__free(index); return -1; } /* then populate the index */ prev_val = ~0; for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW; data >= buffer; data -= RABIN_WINDOW) { unsigned int val = 0; for (i = 1; i <= RABIN_WINDOW; i++) val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT]; if (val == prev_val) { /* keep the lowest of consecutive identical blocks */ entry[-1].ptr = data + RABIN_WINDOW; } else { prev_val = val; i = val & hmask; entry->ptr = data + RABIN_WINDOW; entry->val = val; entry->next = hash[i]; hash[i] = entry++; hash_count[i]++; } } /* * Determine a limit on the number of entries in the same hash * bucket. This guard us against patological data sets causing * really bad hash distribution with most entries in the same hash * bucket that would bring us to O(m*n) computing costs (m and n * corresponding to reference and target buffer sizes). * * Make sure none of the hash buckets has more entries than * we're willing to test. Otherwise we cull the entry list * uniformly to still preserve a good repartition across * the reference buffer. */ for (i = 0; i < hsize; i++) { if (hash_count[i] < HASH_LIMIT) continue; entry = hash[i]; do { struct index_entry *keep = entry; int skip = hash_count[i] / HASH_LIMIT / 2; do { entry = entry->next; } while(--skip && entry); keep->next = entry; } while (entry); } git__free(hash_count); *out = index; return 0; } void git_delta_index_free(git_delta_index *index) { git__free(index); } size_t git_delta_index_size(git_delta_index *index) { assert(index); return index->memsize; } /* * The maximum size for any opcode sequence, including the initial header * plus rabin window plus biggest copy. */ #define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7) int git_delta_create_from_index( void **out, size_t *out_len, const struct git_delta_index *index, const void *trg_buf, size_t trg_size, size_t max_size) { unsigned int i, bufpos, bufsize, moff, msize, val; int inscnt; const unsigned char *ref_data, *ref_top, *data, *top; unsigned char *buf; *out = NULL; *out_len = 0; if (!trg_buf || !trg_size) return 0; bufpos = 0; bufsize = 8192; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); buf = git__malloc(bufsize); GITERR_CHECK_ALLOC(buf); /* store reference buffer size */ i = index->src_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; /* store target buffer size */ i = trg_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; ref_data = index->src_buf; ref_top = ref_data + index->src_size; data = trg_buf; top = (const unsigned char *) trg_buf + trg_size; bufpos++; val = 0; for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) { buf[bufpos++] = *data; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; } inscnt = i; moff = 0; msize = 0; while (data < top) { if (msize < 4096) { struct index_entry *entry; val ^= U[data[-RABIN_WINDOW]]; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; i = val & index->hash_mask; for (entry = index->hash[i]; entry; entry = entry->next) { const unsigned char *ref = entry->ptr; const unsigned char *src = data; unsigned int ref_size = (unsigned int)(ref_top - ref); if (entry->val != val) continue; if (ref_size > (unsigned int)(top - src)) ref_size = (unsigned int)(top - src); if (ref_size <= msize) break; while (ref_size-- && *src++ == *ref) ref++; if (msize < (unsigned int)(ref - entry->ptr)) { /* this is our best match so far */ msize = (unsigned int)(ref - entry->ptr); moff = (unsigned int)(entry->ptr - ref_data); if (msize >= 4096) /* good enough */ break; } } } if (msize < 4) { if (!inscnt) bufpos++; buf[bufpos++] = *data++; inscnt++; if (inscnt == 0x7f) { buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } msize = 0; } else { unsigned int left; unsigned char *op; if (inscnt) { while (moff && ref_data[moff-1] == data[-1]) { /* we can match one byte back */ msize++; moff--; data--; bufpos--; if (--inscnt) continue; bufpos--; /* remove count slot */ inscnt--; /* make it -1 */ break; } buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } /* A copy op is currently limited to 64KB (pack v2) */ left = (msize < 0x10000) ? 0 : (msize - 0x10000); msize -= left; op = buf + bufpos++; i = 0x80; if (moff & 0x000000ff) buf[bufpos++] = moff >> 0, i |= 0x01; if (moff & 0x0000ff00) buf[bufpos++] = moff >> 8, i |= 0x02; if (moff & 0x00ff0000) buf[bufpos++] = moff >> 16, i |= 0x04; if (moff & 0xff000000) buf[bufpos++] = moff >> 24, i |= 0x08; if (msize & 0x00ff) buf[bufpos++] = msize >> 0, i |= 0x10; if (msize & 0xff00) buf[bufpos++] = msize >> 8, i |= 0x20; *op = i; data += msize; moff += msize; msize = left; if (msize < 4096) { int j; val = 0; for (j = -RABIN_WINDOW; j < 0; j++) val = ((val << 8) | data[j]) ^ T[val >> RABIN_SHIFT]; } } if (bufpos >= bufsize - MAX_OP_SIZE) { void *tmp = buf; bufsize = bufsize * 3 / 2; if (max_size && bufsize >= max_size) bufsize = max_size + MAX_OP_SIZE + 1; if (max_size && bufpos > max_size) break; buf = git__realloc(buf, bufsize); if (!buf) { git__free(tmp); return -1; } } } if (inscnt) buf[bufpos - inscnt - 1] = inscnt; if (max_size && bufpos > max_size) { giterr_set(GITERR_NOMEMORY, "delta would be larger than maximum size"); git__free(buf); return GIT_EBUFS; } *out_len = bufpos; *out = buf; return 0; } /* * Delta application was heavily cribbed from BinaryDelta.java in JGit, which * itself was heavily cribbed from <code>patch-delta.c</code> in the * GIT project. The original delta patching code was written by * Nicolas Pitre <nico@cam.org>. */ static int hdr_sz( size_t *size, const unsigned char **delta, const unsigned char *end) { const unsigned char *d = *delta; size_t r = 0; unsigned int c, shift = 0; do { if (d == end) { giterr_set(GITERR_INVALID, "truncated delta"); return -1; } c = *d++; r |= (c & 0x7f) << shift; shift += 7; } while (c & 0x80); *delta = d; *size = r; return 0; } int git_delta_read_header( size_t *base_out, size_t *result_out, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; if ((hdr_sz(base_out, &delta, delta_end) < 0) || (hdr_sz(result_out, &delta, delta_end) < 0)) return -1; return 0; } #define DELTA_HEADER_BUFFER_LEN 16 int git_delta_read_header_fromstream( size_t *base_sz, size_t *res_sz, git_packfile_stream *stream) { static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN; unsigned char buffer[DELTA_HEADER_BUFFER_LEN]; const unsigned char *delta, *delta_end; size_t len; ssize_t read; len = read = 0; while (len < buffer_len) { read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len); if (read == 0) break; if (read == GIT_EBUFS) continue; len += read; } delta = buffer; delta_end = delta + len; if ((hdr_sz(base_sz, &delta, delta_end) < 0) || (hdr_sz(res_sz, &delta, delta_end) < 0)) return -1; return 0; } int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; if (cmd & 0x01) off = *delta++; if (cmd & 0x02) off |= *delta++ << 8UL; if (cmd & 0x04) off |= *delta++ << 16UL; if (cmd & 0x08) off |= *delta++ << 24UL; if (cmd & 0x10) len = *delta++; if (cmd & 0x20) len |= *delta++ << 8UL; if (cmd & 0x40) len |= *delta++ << 16UL; if (!len) len = 0x10000; if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_111_0
crossvul-cpp_data_bad_2492_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-190/c/bad_2492_0
crossvul-cpp_data_good_5375_1
/* * VFIO PCI interrupt handling * * Copyright (C) 2012 Red Hat, Inc. All rights reserved. * Author: Alex Williamson <alex.williamson@redhat.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Derived from original vfio: * Copyright 2010 Cisco Systems, Inc. All rights reserved. * Author: Tom Lyon, pugs@cisco.com */ #include <linux/device.h> #include <linux/interrupt.h> #include <linux/eventfd.h> #include <linux/msi.h> #include <linux/pci.h> #include <linux/file.h> #include <linux/vfio.h> #include <linux/wait.h> #include <linux/slab.h> #include "vfio_pci_private.h" /* * INTx */ static void vfio_send_intx_eventfd(void *opaque, void *unused) { struct vfio_pci_device *vdev = opaque; if (likely(is_intx(vdev) && !vdev->virq_disabled)) eventfd_signal(vdev->ctx[0].trigger, 1); } void vfio_pci_intx_mask(struct vfio_pci_device *vdev) { struct pci_dev *pdev = vdev->pdev; unsigned long flags; spin_lock_irqsave(&vdev->irqlock, flags); /* * Masking can come from interrupt, ioctl, or config space * via INTx disable. The latter means this can get called * even when not using intx delivery. In this case, just * try to have the physical bit follow the virtual bit. */ if (unlikely(!is_intx(vdev))) { if (vdev->pci_2_3) pci_intx(pdev, 0); } else if (!vdev->ctx[0].masked) { /* * Can't use check_and_mask here because we always want to * mask, not just when something is pending. */ if (vdev->pci_2_3) pci_intx(pdev, 0); else disable_irq_nosync(pdev->irq); vdev->ctx[0].masked = true; } spin_unlock_irqrestore(&vdev->irqlock, flags); } /* * If this is triggered by an eventfd, we can't call eventfd_signal * or else we'll deadlock on the eventfd wait queue. Return >0 when * a signal is necessary, which can then be handled via a work queue * or directly depending on the caller. */ static int vfio_pci_intx_unmask_handler(void *opaque, void *unused) { struct vfio_pci_device *vdev = opaque; struct pci_dev *pdev = vdev->pdev; unsigned long flags; int ret = 0; spin_lock_irqsave(&vdev->irqlock, flags); /* * Unmasking comes from ioctl or config, so again, have the * physical bit follow the virtual even when not using INTx. */ if (unlikely(!is_intx(vdev))) { if (vdev->pci_2_3) pci_intx(pdev, 1); } else if (vdev->ctx[0].masked && !vdev->virq_disabled) { /* * A pending interrupt here would immediately trigger, * but we can avoid that overhead by just re-sending * the interrupt to the user. */ if (vdev->pci_2_3) { if (!pci_check_and_unmask_intx(pdev)) ret = 1; } else enable_irq(pdev->irq); vdev->ctx[0].masked = (ret > 0); } spin_unlock_irqrestore(&vdev->irqlock, flags); return ret; } void vfio_pci_intx_unmask(struct vfio_pci_device *vdev) { if (vfio_pci_intx_unmask_handler(vdev, NULL) > 0) vfio_send_intx_eventfd(vdev, NULL); } static irqreturn_t vfio_intx_handler(int irq, void *dev_id) { struct vfio_pci_device *vdev = dev_id; unsigned long flags; int ret = IRQ_NONE; spin_lock_irqsave(&vdev->irqlock, flags); if (!vdev->pci_2_3) { disable_irq_nosync(vdev->pdev->irq); vdev->ctx[0].masked = true; ret = IRQ_HANDLED; } else if (!vdev->ctx[0].masked && /* may be shared */ pci_check_and_mask_intx(vdev->pdev)) { vdev->ctx[0].masked = true; ret = IRQ_HANDLED; } spin_unlock_irqrestore(&vdev->irqlock, flags); if (ret == IRQ_HANDLED) vfio_send_intx_eventfd(vdev, NULL); return ret; } static int vfio_intx_enable(struct vfio_pci_device *vdev) { if (!is_irq_none(vdev)) return -EINVAL; if (!vdev->pdev->irq) return -ENODEV; vdev->ctx = kzalloc(sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; vdev->num_ctx = 1; /* * If the virtual interrupt is masked, restore it. Devices * supporting DisINTx can be masked at the hardware level * here, non-PCI-2.3 devices will have to wait until the * interrupt is enabled. */ vdev->ctx[0].masked = vdev->virq_disabled; if (vdev->pci_2_3) pci_intx(vdev->pdev, !vdev->ctx[0].masked); vdev->irq_type = VFIO_PCI_INTX_IRQ_INDEX; return 0; } static int vfio_intx_set_signal(struct vfio_pci_device *vdev, int fd) { struct pci_dev *pdev = vdev->pdev; unsigned long irqflags = IRQF_SHARED; struct eventfd_ctx *trigger; unsigned long flags; int ret; if (vdev->ctx[0].trigger) { free_irq(pdev->irq, vdev); kfree(vdev->ctx[0].name); eventfd_ctx_put(vdev->ctx[0].trigger); vdev->ctx[0].trigger = NULL; } if (fd < 0) /* Disable only */ return 0; vdev->ctx[0].name = kasprintf(GFP_KERNEL, "vfio-intx(%s)", pci_name(pdev)); if (!vdev->ctx[0].name) return -ENOMEM; trigger = eventfd_ctx_fdget(fd); if (IS_ERR(trigger)) { kfree(vdev->ctx[0].name); return PTR_ERR(trigger); } vdev->ctx[0].trigger = trigger; if (!vdev->pci_2_3) irqflags = 0; ret = request_irq(pdev->irq, vfio_intx_handler, irqflags, vdev->ctx[0].name, vdev); if (ret) { vdev->ctx[0].trigger = NULL; kfree(vdev->ctx[0].name); eventfd_ctx_put(trigger); return ret; } /* * INTx disable will stick across the new irq setup, * disable_irq won't. */ spin_lock_irqsave(&vdev->irqlock, flags); if (!vdev->pci_2_3 && vdev->ctx[0].masked) disable_irq_nosync(pdev->irq); spin_unlock_irqrestore(&vdev->irqlock, flags); return 0; } static void vfio_intx_disable(struct vfio_pci_device *vdev) { vfio_virqfd_disable(&vdev->ctx[0].unmask); vfio_virqfd_disable(&vdev->ctx[0].mask); vfio_intx_set_signal(vdev, -1); vdev->irq_type = VFIO_PCI_NUM_IRQS; vdev->num_ctx = 0; kfree(vdev->ctx); } /* * MSI/MSI-X */ static irqreturn_t vfio_msihandler(int irq, void *arg) { struct eventfd_ctx *trigger = arg; eventfd_signal(trigger, 1); return IRQ_HANDLED; } static int vfio_msi_enable(struct vfio_pci_device *vdev, int nvec, bool msix) { struct pci_dev *pdev = vdev->pdev; unsigned int flag = msix ? PCI_IRQ_MSIX : PCI_IRQ_MSI; int ret; if (!is_irq_none(vdev)) return -EINVAL; vdev->ctx = kcalloc(nvec, sizeof(struct vfio_pci_irq_ctx), GFP_KERNEL); if (!vdev->ctx) return -ENOMEM; /* return the number of supported vectors if we can't get all: */ ret = pci_alloc_irq_vectors(pdev, 1, nvec, flag); if (ret < nvec) { if (ret > 0) pci_free_irq_vectors(pdev); kfree(vdev->ctx); return ret; } vdev->num_ctx = nvec; vdev->irq_type = msix ? VFIO_PCI_MSIX_IRQ_INDEX : VFIO_PCI_MSI_IRQ_INDEX; if (!msix) { /* * Compute the virtual hardware field for max msi vectors - * it is the log base 2 of the number of vectors. */ vdev->msi_qmax = fls(nvec * 2 - 1) - 1; } return 0; } static int vfio_msi_set_vector_signal(struct vfio_pci_device *vdev, int vector, int fd, bool msix) { struct pci_dev *pdev = vdev->pdev; struct eventfd_ctx *trigger; int irq, ret; if (vector < 0 || vector >= vdev->num_ctx) return -EINVAL; irq = pci_irq_vector(pdev, vector); if (vdev->ctx[vector].trigger) { free_irq(irq, vdev->ctx[vector].trigger); irq_bypass_unregister_producer(&vdev->ctx[vector].producer); kfree(vdev->ctx[vector].name); eventfd_ctx_put(vdev->ctx[vector].trigger); vdev->ctx[vector].trigger = NULL; } if (fd < 0) return 0; vdev->ctx[vector].name = kasprintf(GFP_KERNEL, "vfio-msi%s[%d](%s)", msix ? "x" : "", vector, pci_name(pdev)); if (!vdev->ctx[vector].name) return -ENOMEM; trigger = eventfd_ctx_fdget(fd); if (IS_ERR(trigger)) { kfree(vdev->ctx[vector].name); return PTR_ERR(trigger); } /* * The MSIx vector table resides in device memory which may be cleared * via backdoor resets. We don't allow direct access to the vector * table so even if a userspace driver attempts to save/restore around * such a reset it would be unsuccessful. To avoid this, restore the * cached value of the message prior to enabling. */ if (msix) { struct msi_msg msg; get_cached_msi_msg(irq, &msg); pci_write_msi_msg(irq, &msg); } ret = request_irq(irq, vfio_msihandler, 0, vdev->ctx[vector].name, trigger); if (ret) { kfree(vdev->ctx[vector].name); eventfd_ctx_put(trigger); return ret; } vdev->ctx[vector].producer.token = trigger; vdev->ctx[vector].producer.irq = irq; ret = irq_bypass_register_producer(&vdev->ctx[vector].producer); if (unlikely(ret)) dev_info(&pdev->dev, "irq bypass producer (token %p) registration fails: %d\n", vdev->ctx[vector].producer.token, ret); vdev->ctx[vector].trigger = trigger; return 0; } static int vfio_msi_set_block(struct vfio_pci_device *vdev, unsigned start, unsigned count, int32_t *fds, bool msix) { int i, j, ret = 0; if (start >= vdev->num_ctx || start + count > vdev->num_ctx) return -EINVAL; for (i = 0, j = start; i < count && !ret; i++, j++) { int fd = fds ? fds[i] : -1; ret = vfio_msi_set_vector_signal(vdev, j, fd, msix); } if (ret) { for (--j; j >= (int)start; j--) vfio_msi_set_vector_signal(vdev, j, -1, msix); } return ret; } static void vfio_msi_disable(struct vfio_pci_device *vdev, bool msix) { struct pci_dev *pdev = vdev->pdev; int i; for (i = 0; i < vdev->num_ctx; i++) { vfio_virqfd_disable(&vdev->ctx[i].unmask); vfio_virqfd_disable(&vdev->ctx[i].mask); } vfio_msi_set_block(vdev, 0, vdev->num_ctx, NULL, msix); pci_free_irq_vectors(pdev); /* * Both disable paths above use pci_intx_for_msi() to clear DisINTx * via their shutdown paths. Restore for NoINTx devices. */ if (vdev->nointx) pci_intx(pdev, 0); vdev->irq_type = VFIO_PCI_NUM_IRQS; vdev->num_ctx = 0; kfree(vdev->ctx); } /* * IOCTL support */ static int vfio_pci_set_intx_unmask(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { if (!is_intx(vdev) || start != 0 || count != 1) return -EINVAL; if (flags & VFIO_IRQ_SET_DATA_NONE) { vfio_pci_intx_unmask(vdev); } else if (flags & VFIO_IRQ_SET_DATA_BOOL) { uint8_t unmask = *(uint8_t *)data; if (unmask) vfio_pci_intx_unmask(vdev); } else if (flags & VFIO_IRQ_SET_DATA_EVENTFD) { int32_t fd = *(int32_t *)data; if (fd >= 0) return vfio_virqfd_enable((void *) vdev, vfio_pci_intx_unmask_handler, vfio_send_intx_eventfd, NULL, &vdev->ctx[0].unmask, fd); vfio_virqfd_disable(&vdev->ctx[0].unmask); } return 0; } static int vfio_pci_set_intx_mask(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { if (!is_intx(vdev) || start != 0 || count != 1) return -EINVAL; if (flags & VFIO_IRQ_SET_DATA_NONE) { vfio_pci_intx_mask(vdev); } else if (flags & VFIO_IRQ_SET_DATA_BOOL) { uint8_t mask = *(uint8_t *)data; if (mask) vfio_pci_intx_mask(vdev); } else if (flags & VFIO_IRQ_SET_DATA_EVENTFD) { return -ENOTTY; /* XXX implement me */ } return 0; } static int vfio_pci_set_intx_trigger(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { if (is_intx(vdev) && !count && (flags & VFIO_IRQ_SET_DATA_NONE)) { vfio_intx_disable(vdev); return 0; } if (!(is_intx(vdev) || is_irq_none(vdev)) || start != 0 || count != 1) return -EINVAL; if (flags & VFIO_IRQ_SET_DATA_EVENTFD) { int32_t fd = *(int32_t *)data; int ret; if (is_intx(vdev)) return vfio_intx_set_signal(vdev, fd); ret = vfio_intx_enable(vdev); if (ret) return ret; ret = vfio_intx_set_signal(vdev, fd); if (ret) vfio_intx_disable(vdev); return ret; } if (!is_intx(vdev)) return -EINVAL; if (flags & VFIO_IRQ_SET_DATA_NONE) { vfio_send_intx_eventfd(vdev, NULL); } else if (flags & VFIO_IRQ_SET_DATA_BOOL) { uint8_t trigger = *(uint8_t *)data; if (trigger) vfio_send_intx_eventfd(vdev, NULL); } return 0; } static int vfio_pci_set_msi_trigger(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { int i; bool msix = (index == VFIO_PCI_MSIX_IRQ_INDEX) ? true : false; if (irq_is(vdev, index) && !count && (flags & VFIO_IRQ_SET_DATA_NONE)) { vfio_msi_disable(vdev, msix); return 0; } if (!(irq_is(vdev, index) || is_irq_none(vdev))) return -EINVAL; if (flags & VFIO_IRQ_SET_DATA_EVENTFD) { int32_t *fds = data; int ret; if (vdev->irq_type == index) return vfio_msi_set_block(vdev, start, count, fds, msix); ret = vfio_msi_enable(vdev, start + count, msix); if (ret) return ret; ret = vfio_msi_set_block(vdev, start, count, fds, msix); if (ret) vfio_msi_disable(vdev, msix); return ret; } if (!irq_is(vdev, index) || start + count > vdev->num_ctx) return -EINVAL; for (i = start; i < start + count; i++) { if (!vdev->ctx[i].trigger) continue; if (flags & VFIO_IRQ_SET_DATA_NONE) { eventfd_signal(vdev->ctx[i].trigger, 1); } else if (flags & VFIO_IRQ_SET_DATA_BOOL) { uint8_t *bools = data; if (bools[i - start]) eventfd_signal(vdev->ctx[i].trigger, 1); } } return 0; } static int vfio_pci_set_ctx_trigger_single(struct eventfd_ctx **ctx, unsigned int count, uint32_t flags, void *data) { /* DATA_NONE/DATA_BOOL enables loopback testing */ if (flags & VFIO_IRQ_SET_DATA_NONE) { if (*ctx) { if (count) { eventfd_signal(*ctx, 1); } else { eventfd_ctx_put(*ctx); *ctx = NULL; } return 0; } } else if (flags & VFIO_IRQ_SET_DATA_BOOL) { uint8_t trigger; if (!count) return -EINVAL; trigger = *(uint8_t *)data; if (trigger && *ctx) eventfd_signal(*ctx, 1); return 0; } else if (flags & VFIO_IRQ_SET_DATA_EVENTFD) { int32_t fd; if (!count) return -EINVAL; fd = *(int32_t *)data; if (fd == -1) { if (*ctx) eventfd_ctx_put(*ctx); *ctx = NULL; } else if (fd >= 0) { struct eventfd_ctx *efdctx; efdctx = eventfd_ctx_fdget(fd); if (IS_ERR(efdctx)) return PTR_ERR(efdctx); if (*ctx) eventfd_ctx_put(*ctx); *ctx = efdctx; } return 0; } return -EINVAL; } static int vfio_pci_set_err_trigger(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { if (index != VFIO_PCI_ERR_IRQ_INDEX || start != 0 || count > 1) return -EINVAL; return vfio_pci_set_ctx_trigger_single(&vdev->err_trigger, count, flags, data); } static int vfio_pci_set_req_trigger(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) { if (index != VFIO_PCI_REQ_IRQ_INDEX || start != 0 || count > 1) return -EINVAL; return vfio_pci_set_ctx_trigger_single(&vdev->req_trigger, count, flags, data); } int vfio_pci_set_irqs_ioctl(struct vfio_pci_device *vdev, uint32_t flags, unsigned index, unsigned start, unsigned count, void *data) { int (*func)(struct vfio_pci_device *vdev, unsigned index, unsigned start, unsigned count, uint32_t flags, void *data) = NULL; switch (index) { case VFIO_PCI_INTX_IRQ_INDEX: switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) { case VFIO_IRQ_SET_ACTION_MASK: func = vfio_pci_set_intx_mask; break; case VFIO_IRQ_SET_ACTION_UNMASK: func = vfio_pci_set_intx_unmask; break; case VFIO_IRQ_SET_ACTION_TRIGGER: func = vfio_pci_set_intx_trigger; break; } break; case VFIO_PCI_MSI_IRQ_INDEX: case VFIO_PCI_MSIX_IRQ_INDEX: switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) { case VFIO_IRQ_SET_ACTION_MASK: case VFIO_IRQ_SET_ACTION_UNMASK: /* XXX Need masking support exported */ break; case VFIO_IRQ_SET_ACTION_TRIGGER: func = vfio_pci_set_msi_trigger; break; } break; case VFIO_PCI_ERR_IRQ_INDEX: switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) { case VFIO_IRQ_SET_ACTION_TRIGGER: if (pci_is_pcie(vdev->pdev)) func = vfio_pci_set_err_trigger; break; } break; case VFIO_PCI_REQ_IRQ_INDEX: switch (flags & VFIO_IRQ_SET_ACTION_TYPE_MASK) { case VFIO_IRQ_SET_ACTION_TRIGGER: func = vfio_pci_set_req_trigger; break; } break; } if (!func) return -ENOTTY; return func(vdev, index, start, count, flags, data); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_5375_1
crossvul-cpp_data_good_4052_0
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.7 2018/05/11 22:04:31 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size 'n' (default is size of int) ** cn - sequence of 'n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1); luaL_argcheck(L, pos > 0, 3, "offset must be 1 or greater"); pos--; /* Lua indexes are 1-based, but here we want 0-based for C * pointer math. */ int n = 0; /* number of results */ defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); /* stack space for item + next position */ luaL_checkstack(L, 2, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); n++; break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); n++; break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); n++; break; } case 'c': { if (size == 0) { if (n == 0 || !lua_isnumber(L, -1)) luaL_error(L, "format 'c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); n--; luaL_argcheck(L, size <= ld && pos <= ld - size, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); n++; break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); n++; break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); /* next position */ return n + 1; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2018 Lua.org, PUC-Rio. 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. ******************************************************************************/
./CrossVul/dataset_final_sorted/CWE-190/c/good_4052_0
crossvul-cpp_data_good_5177_1
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO PPPP EEEEE RRRR TTTTT Y Y % % P P R R O O P P E R R T Y Y % % PPPP RRRR O O PPPP EEE RRRR T Y % % P R R O O P E R R T Y % % P R R OOO P EEEEE R R T Y % % % % % % MagickCore Property Methods % % % % Software Design % % Cristy % % March 2000 % % % % % % Copyright 1999-2016 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/compare.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/fx-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/layer.h" #include "MagickCore/locale-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/montage.h" #include "MagickCore/option.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/signature.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/token.h" #include "MagickCore/token-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/xml-tree.h" #include "MagickCore/xml-tree-private.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS2_LCMS2_H) #include <lcms2/lcms2.h> #elif defined(MAGICKCORE_HAVE_LCMS2_H) #include "lcms2.h" #elif defined(MAGICKCORE_HAVE_LCMS_LCMS_H) #include <lcms/lcms.h> #else #include "lcms.h" #endif #endif /* Define declarations. */ #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProperties() clones all the image properties to another image. % % The format of the CloneImageProperties method is: % % MagickBooleanType CloneImageProperties(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProperties(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", clone_image->filename); (void) CopyMagickString(image->filename,clone_image->filename,MagickPathExtent); (void) CopyMagickString(image->magick_filename,clone_image->magick_filename, MagickPathExtent); image->compression=clone_image->compression; image->quality=clone_image->quality; image->depth=clone_image->depth; image->alpha_color=clone_image->alpha_color; image->background_color=clone_image->background_color; image->border_color=clone_image->border_color; image->transparent_color=clone_image->transparent_color; image->gamma=clone_image->gamma; image->chromaticity=clone_image->chromaticity; image->rendering_intent=clone_image->rendering_intent; image->black_point_compensation=clone_image->black_point_compensation; image->units=clone_image->units; image->montage=(char *) NULL; image->directory=(char *) NULL; (void) CloneString(&image->geometry,clone_image->geometry); image->offset=clone_image->offset; image->resolution.x=clone_image->resolution.x; image->resolution.y=clone_image->resolution.y; image->page=clone_image->page; image->tile_offset=clone_image->tile_offset; image->extract_info=clone_image->extract_info; image->filter=clone_image->filter; image->fuzz=clone_image->fuzz; image->intensity=clone_image->intensity; image->interlace=clone_image->interlace; image->interpolate=clone_image->interpolate; image->endian=clone_image->endian; image->gravity=clone_image->gravity; image->compose=clone_image->compose; image->orientation=clone_image->orientation; image->scene=clone_image->scene; image->dispose=clone_image->dispose; image->delay=clone_image->delay; image->ticks_per_second=clone_image->ticks_per_second; image->iterations=clone_image->iterations; image->total_colors=clone_image->total_colors; image->taint=clone_image->taint; image->progress_monitor=clone_image->progress_monitor; image->client_data=clone_image->client_data; image->start_loop=clone_image->start_loop; image->error=clone_image->error; image->signature=clone_image->signature; if (clone_image->properties != (void *) NULL) { if (image->properties != (void *) NULL) DestroyImageProperties(image); image->properties=CloneSplayTree((SplayTreeInfo *) clone_image->properties,(void *(*)(void *)) ConstantString, (void *(*)(void *)) ConstantString); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e f i n e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageProperty() associates an assignment string of the form % "key=value" with an artifact or options. It is equivelent to % SetImageProperty() % % The format of the DefineImageProperty method is: % % MagickBooleanType DefineImageProperty(Image *image,const char *property, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType DefineImageProperty(Image *image, const char *property,ExceptionInfo *exception) { char key[MagickPathExtent], value[MagickPathExtent]; register char *p; assert(image != (Image *) NULL); assert(property != (const char *) NULL); (void) CopyMagickString(key,property,MagickPathExtent-1); for (p=key; *p != '\0'; p++) if (*p == '=') break; *value='\0'; if (*p == '=') (void) CopyMagickString(value,p+1,MagickPathExtent); *p='\0'; return(SetImageProperty(image,key,value,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProperty() deletes an image property. % % The format of the DeleteImageProperty method is: % % MagickBooleanType DeleteImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport MagickBooleanType DeleteImageProperty(Image *image, const char *property) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return(MagickFalse); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->properties,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProperties() destroys all properties and associated memory % attached to the given image. % % The format of the DestroyDefines method is: % % void DestroyImageProperties(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProperties(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties != (void *) NULL) image->properties=(void *) DestroySplayTree((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r m a t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FormatImageProperty() permits formatted property/value pairs to be saved as % an image property. % % The format of the FormatImageProperty method is: % % MagickBooleanType FormatImageProperty(Image *image,const char *property, % const char *format,...) % % A description of each parameter follows. % % o image: The image. % % o property: The attribute property. % % o format: A string describing the format to use to write the remaining % arguments. % */ MagickExport MagickBooleanType FormatImageProperty(Image *image, const char *property,const char *format,...) { char value[MagickPathExtent]; ExceptionInfo *exception; MagickBooleanType status; ssize_t n; va_list operands; va_start(operands,format); n=FormatLocaleStringList(value,MagickPathExtent,format,operands); (void) n; va_end(operands); exception=AcquireExceptionInfo(); status=SetImageProperty(image,property,value,exception); exception=DestroyExceptionInfo(exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProperty() gets a value associated with an image property. % % This includes, profile prefixes, such as "exif:", "iptc:" and "8bim:" % It does not handle non-prifile prefixes, such as "fx:", "option:", or % "artifact:". % % The returned string is stored as a properity of the same name for faster % lookup later. It should NOT be freed by the caller. % % The format of the GetImageProperty method is: % % const char *GetImageProperty(const Image *image,const char *key, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static char *TracePSClippath(const unsigned char *,size_t), *TraceSVGClippath(const unsigned char *,size_t,const size_t, const size_t); static MagickBooleanType GetIPTCProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, *message; const StringInfo *profile; long count, dataset, record; register ssize_t i; size_t length; profile=GetImageProfile(image,"iptc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=sscanf(key,"IPTC:%ld:%ld",&dataset,&record); if (count != 2) return(MagickFalse); attribute=(char *) NULL; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=(ssize_t) length) { length=1; if ((ssize_t) GetStringInfoDatum(profile)[i] != 0x1c) continue; length=(size_t) (GetStringInfoDatum(profile)[i+3] << 8); length|=GetStringInfoDatum(profile)[i+4]; if (((long) GetStringInfoDatum(profile)[i+1] == dataset) && ((long) GetStringInfoDatum(profile)[i+2] == record)) { message=(char *) NULL; if (~length >= 1) message=(char *) AcquireQuantumMemory(length+1UL,sizeof(*message)); if (message != (char *) NULL) { (void) CopyMagickString(message,(char *) GetStringInfoDatum( profile)+i+5,length+1); (void) ConcatenateString(&attribute,message); (void) ConcatenateString(&attribute,";"); message=DestroyString(message); } } i+=5; } if ((attribute == (char *) NULL) || (*attribute == ';')) { if (attribute != (char *) NULL) attribute=DestroyString(attribute); return(MagickFalse); } attribute[strlen(attribute)-1]='\0'; (void) SetImageProperty((Image *) image,key,(const char *) attribute, exception); attribute=DestroyString(attribute); return(MagickTrue); } static inline int ReadPropertyByte(const unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed int ReadPropertyMSBLong(const unsigned char **p, size_t *length) { union { unsigned int unsigned_value; signed int signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[4]; unsigned int value; if (*length < 4) return(-1); for (i=0; i < 4; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed short ReadPropertyMSBShort(const unsigned char **p, size_t *length) { union { unsigned short unsigned_value; signed short signed_value; } quantum; int c; register ssize_t i; unsigned char buffer[2]; unsigned short value; if (*length < 2) return((unsigned short) ~0); for (i=0; i < 2; i++) { c=(int) (*(*p)++); (*length)--; buffer[i]=(unsigned char) c; } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static MagickBooleanType Get8BIMProperty(const Image *image,const char *key, ExceptionInfo *exception) { char *attribute, format[MagickPathExtent], name[MagickPathExtent], *resource; const StringInfo *profile; const unsigned char *info; long start, stop; MagickBooleanType status; register ssize_t i; ssize_t count, id, sub_number; size_t length; /* There are no newlines in path names, so it's safe as terminator. */ profile=GetImageProfile(image,"8bim"); if (profile == (StringInfo *) NULL) return(MagickFalse); count=(ssize_t) sscanf(key,"8BIM:%ld,%ld:%1024[^\n]\n%1024[^\n]",&start,&stop, name,format); if ((count != 2) && (count != 3) && (count != 4)) return(MagickFalse); if (count < 4) (void) CopyMagickString(format,"SVG",MagickPathExtent); if (count < 3) *name='\0'; sub_number=1; if (*name == '#') sub_number=(ssize_t) StringToLong(&name[1]); sub_number=MagickMax(sub_number,1L); resource=(char *) NULL; status=MagickFalse; length=GetStringInfoLength(profile); info=GetStringInfoDatum(profile); while ((length > 0) && (status == MagickFalse)) { if (ReadPropertyByte(&info,&length) != (unsigned char) '8') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'B') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'I') continue; if (ReadPropertyByte(&info,&length) != (unsigned char) 'M') continue; id=(ssize_t) ReadPropertyMSBShort(&info,&length); if (id < (ssize_t) start) continue; if (id > (ssize_t) stop) continue; if (resource != (char *) NULL) resource=DestroyString(resource); count=(ssize_t) ReadPropertyByte(&info,&length); if ((count != 0) && ((size_t) count <= length)) { resource=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) resource=(char *) AcquireQuantumMemory((size_t) count+ MagickPathExtent,sizeof(*resource)); if (resource != (char *) NULL) { for (i=0; i < (ssize_t) count; i++) resource[i]=(char) ReadPropertyByte(&info,&length); resource[count]='\0'; } } if ((count & 0x01) == 0) (void) ReadPropertyByte(&info,&length); count=(ssize_t) ReadPropertyMSBLong(&info,&length); if ((*name != '\0') && (*name != '#')) if ((resource == (char *) NULL) || (LocaleCompare(name,resource) != 0)) { /* No name match, scroll forward and try next. */ info+=count; length-=MagickMin(count,(ssize_t) length); continue; } if ((*name == '#') && (sub_number != 1)) { /* No numbered match, scroll forward and try next. */ sub_number--; info+=count; length-=MagickMin(count,(ssize_t) length); continue; } /* We have the resource of interest. */ attribute=(char *) NULL; if (~((size_t) count) >= (MagickPathExtent-1)) attribute=(char *) AcquireQuantumMemory((size_t) count+MagickPathExtent, sizeof(*attribute)); if (attribute != (char *) NULL) { (void) CopyMagickMemory(attribute,(char *) info,(size_t) count); attribute[count]='\0'; info+=count; length-=MagickMin(count,(ssize_t) length); if ((id <= 1999) || (id >= 2999)) (void) SetImageProperty((Image *) image,key,(const char *) attribute,exception); else { char *path; if (LocaleCompare(format,"svg") == 0) path=TraceSVGClippath((unsigned char *) attribute,(size_t) count, image->columns,image->rows); else path=TracePSClippath((unsigned char *) attribute,(size_t) count); (void) SetImageProperty((Image *) image,key,(const char *) path, exception); path=DestroyString(path); } attribute=DestroyString(attribute); status=MagickTrue; } } if (resource != (char *) NULL) resource=DestroyString(resource); return(status); } static inline signed int ReadPropertySignedLong(const EndianType endian, const unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline unsigned int ReadPropertyUnsignedLong(const EndianType endian, const unsigned char *buffer) { unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; return(value & 0xffffffff); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; return(value & 0xffffffff); } static inline signed short ReadPropertySignedShort(const EndianType endian, const unsigned char *buffer) { union { unsigned short unsigned_value; signed short signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian, const unsigned char *buffer) { unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; return(value & 0xffff); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; return(value & 0xffff); } static MagickBooleanType GetEXIFProperty(const Image *image, const char *property,ExceptionInfo *exception) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define EXIF_FMT_BYTE 1 #define EXIF_FMT_STRING 2 #define EXIF_FMT_USHORT 3 #define EXIF_FMT_ULONG 4 #define EXIF_FMT_URATIONAL 5 #define EXIF_FMT_SBYTE 6 #define EXIF_FMT_UNDEFINED 7 #define EXIF_FMT_SSHORT 8 #define EXIF_FMT_SLONG 9 #define EXIF_FMT_SRATIONAL 10 #define EXIF_FMT_SINGLE 11 #define EXIF_FMT_DOUBLE 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_GPS_OFFSET 0x8825 #define TAG_INTEROP_OFFSET 0xa005 #define EXIFMultipleValues(size,format,arg) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",arg); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } #define EXIFMultipleFractions(size,format,arg1,arg2) \ { \ ssize_t \ component; \ \ size_t \ length; \ \ unsigned char \ *p1; \ \ length=0; \ p1=p; \ for (component=0; component < components; component++) \ { \ length+=FormatLocaleString(buffer+length,MagickPathExtent-length, \ format", ",(arg1),(arg2)); \ if (length >= (MagickPathExtent-1)) \ length=MagickPathExtent-1; \ p1+=size; \ } \ if (length > 1) \ buffer[length-2]='\0'; \ value=AcquireString(buffer); \ } typedef struct _DirectoryInfo { const unsigned char *directory; size_t entry; ssize_t offset; } DirectoryInfo; typedef struct _TagInfo { size_t tag; const char *description; } TagInfo; static TagInfo EXIFTag[] = { { 0x001, "exif:InteroperabilityIndex" }, { 0x002, "exif:InteroperabilityVersion" }, { 0x100, "exif:ImageWidth" }, { 0x101, "exif:ImageLength" }, { 0x102, "exif:BitsPerSample" }, { 0x103, "exif:Compression" }, { 0x106, "exif:PhotometricInterpretation" }, { 0x10a, "exif:FillOrder" }, { 0x10d, "exif:DocumentName" }, { 0x10e, "exif:ImageDescription" }, { 0x10f, "exif:Make" }, { 0x110, "exif:Model" }, { 0x111, "exif:StripOffsets" }, { 0x112, "exif:Orientation" }, { 0x115, "exif:SamplesPerPixel" }, { 0x116, "exif:RowsPerStrip" }, { 0x117, "exif:StripByteCounts" }, { 0x11a, "exif:XResolution" }, { 0x11b, "exif:YResolution" }, { 0x11c, "exif:PlanarConfiguration" }, { 0x11d, "exif:PageName" }, { 0x11e, "exif:XPosition" }, { 0x11f, "exif:YPosition" }, { 0x118, "exif:MinSampleValue" }, { 0x119, "exif:MaxSampleValue" }, { 0x120, "exif:FreeOffsets" }, { 0x121, "exif:FreeByteCounts" }, { 0x122, "exif:GrayResponseUnit" }, { 0x123, "exif:GrayResponseCurve" }, { 0x124, "exif:T4Options" }, { 0x125, "exif:T6Options" }, { 0x128, "exif:ResolutionUnit" }, { 0x12d, "exif:TransferFunction" }, { 0x131, "exif:Software" }, { 0x132, "exif:DateTime" }, { 0x13b, "exif:Artist" }, { 0x13e, "exif:WhitePoint" }, { 0x13f, "exif:PrimaryChromaticities" }, { 0x140, "exif:ColorMap" }, { 0x141, "exif:HalfToneHints" }, { 0x142, "exif:TileWidth" }, { 0x143, "exif:TileLength" }, { 0x144, "exif:TileOffsets" }, { 0x145, "exif:TileByteCounts" }, { 0x14a, "exif:SubIFD" }, { 0x14c, "exif:InkSet" }, { 0x14d, "exif:InkNames" }, { 0x14e, "exif:NumberOfInks" }, { 0x150, "exif:DotRange" }, { 0x151, "exif:TargetPrinter" }, { 0x152, "exif:ExtraSample" }, { 0x153, "exif:SampleFormat" }, { 0x154, "exif:SMinSampleValue" }, { 0x155, "exif:SMaxSampleValue" }, { 0x156, "exif:TransferRange" }, { 0x157, "exif:ClipPath" }, { 0x158, "exif:XClipPathUnits" }, { 0x159, "exif:YClipPathUnits" }, { 0x15a, "exif:Indexed" }, { 0x15b, "exif:JPEGTables" }, { 0x15f, "exif:OPIProxy" }, { 0x200, "exif:JPEGProc" }, { 0x201, "exif:JPEGInterchangeFormat" }, { 0x202, "exif:JPEGInterchangeFormatLength" }, { 0x203, "exif:JPEGRestartInterval" }, { 0x205, "exif:JPEGLosslessPredictors" }, { 0x206, "exif:JPEGPointTransforms" }, { 0x207, "exif:JPEGQTables" }, { 0x208, "exif:JPEGDCTables" }, { 0x209, "exif:JPEGACTables" }, { 0x211, "exif:YCbCrCoefficients" }, { 0x212, "exif:YCbCrSubSampling" }, { 0x213, "exif:YCbCrPositioning" }, { 0x214, "exif:ReferenceBlackWhite" }, { 0x2bc, "exif:ExtensibleMetadataPlatform" }, { 0x301, "exif:Gamma" }, { 0x302, "exif:ICCProfileDescriptor" }, { 0x303, "exif:SRGBRenderingIntent" }, { 0x320, "exif:ImageTitle" }, { 0x5001, "exif:ResolutionXUnit" }, { 0x5002, "exif:ResolutionYUnit" }, { 0x5003, "exif:ResolutionXLengthUnit" }, { 0x5004, "exif:ResolutionYLengthUnit" }, { 0x5005, "exif:PrintFlags" }, { 0x5006, "exif:PrintFlagsVersion" }, { 0x5007, "exif:PrintFlagsCrop" }, { 0x5008, "exif:PrintFlagsBleedWidth" }, { 0x5009, "exif:PrintFlagsBleedWidthScale" }, { 0x500A, "exif:HalftoneLPI" }, { 0x500B, "exif:HalftoneLPIUnit" }, { 0x500C, "exif:HalftoneDegree" }, { 0x500D, "exif:HalftoneShape" }, { 0x500E, "exif:HalftoneMisc" }, { 0x500F, "exif:HalftoneScreen" }, { 0x5010, "exif:JPEGQuality" }, { 0x5011, "exif:GridSize" }, { 0x5012, "exif:ThumbnailFormat" }, { 0x5013, "exif:ThumbnailWidth" }, { 0x5014, "exif:ThumbnailHeight" }, { 0x5015, "exif:ThumbnailColorDepth" }, { 0x5016, "exif:ThumbnailPlanes" }, { 0x5017, "exif:ThumbnailRawBytes" }, { 0x5018, "exif:ThumbnailSize" }, { 0x5019, "exif:ThumbnailCompressedSize" }, { 0x501a, "exif:ColorTransferFunction" }, { 0x501b, "exif:ThumbnailData" }, { 0x5020, "exif:ThumbnailImageWidth" }, { 0x5021, "exif:ThumbnailImageHeight" }, { 0x5022, "exif:ThumbnailBitsPerSample" }, { 0x5023, "exif:ThumbnailCompression" }, { 0x5024, "exif:ThumbnailPhotometricInterp" }, { 0x5025, "exif:ThumbnailImageDescription" }, { 0x5026, "exif:ThumbnailEquipMake" }, { 0x5027, "exif:ThumbnailEquipModel" }, { 0x5028, "exif:ThumbnailStripOffsets" }, { 0x5029, "exif:ThumbnailOrientation" }, { 0x502a, "exif:ThumbnailSamplesPerPixel" }, { 0x502b, "exif:ThumbnailRowsPerStrip" }, { 0x502c, "exif:ThumbnailStripBytesCount" }, { 0x502d, "exif:ThumbnailResolutionX" }, { 0x502e, "exif:ThumbnailResolutionY" }, { 0x502f, "exif:ThumbnailPlanarConfig" }, { 0x5030, "exif:ThumbnailResolutionUnit" }, { 0x5031, "exif:ThumbnailTransferFunction" }, { 0x5032, "exif:ThumbnailSoftwareUsed" }, { 0x5033, "exif:ThumbnailDateTime" }, { 0x5034, "exif:ThumbnailArtist" }, { 0x5035, "exif:ThumbnailWhitePoint" }, { 0x5036, "exif:ThumbnailPrimaryChromaticities" }, { 0x5037, "exif:ThumbnailYCbCrCoefficients" }, { 0x5038, "exif:ThumbnailYCbCrSubsampling" }, { 0x5039, "exif:ThumbnailYCbCrPositioning" }, { 0x503A, "exif:ThumbnailRefBlackWhite" }, { 0x503B, "exif:ThumbnailCopyRight" }, { 0x5090, "exif:LuminanceTable" }, { 0x5091, "exif:ChrominanceTable" }, { 0x5100, "exif:FrameDelay" }, { 0x5101, "exif:LoopCount" }, { 0x5110, "exif:PixelUnit" }, { 0x5111, "exif:PixelPerUnitX" }, { 0x5112, "exif:PixelPerUnitY" }, { 0x5113, "exif:PaletteHistogram" }, { 0x1000, "exif:RelatedImageFileFormat" }, { 0x1001, "exif:RelatedImageLength" }, { 0x1002, "exif:RelatedImageWidth" }, { 0x800d, "exif:ImageID" }, { 0x80e3, "exif:Matteing" }, { 0x80e4, "exif:DataType" }, { 0x80e5, "exif:ImageDepth" }, { 0x80e6, "exif:TileDepth" }, { 0x828d, "exif:CFARepeatPatternDim" }, { 0x828e, "exif:CFAPattern2" }, { 0x828f, "exif:BatteryLevel" }, { 0x8298, "exif:Copyright" }, { 0x829a, "exif:ExposureTime" }, { 0x829d, "exif:FNumber" }, { 0x83bb, "exif:IPTC/NAA" }, { 0x84e3, "exif:IT8RasterPadding" }, { 0x84e5, "exif:IT8ColorTable" }, { 0x8649, "exif:ImageResourceInformation" }, { 0x8769, "exif:ExifOffset" }, { 0x8773, "exif:InterColorProfile" }, { 0x8822, "exif:ExposureProgram" }, { 0x8824, "exif:SpectralSensitivity" }, { 0x8825, "exif:GPSInfo" }, { 0x8827, "exif:ISOSpeedRatings" }, { 0x8828, "exif:OECF" }, { 0x8829, "exif:Interlace" }, { 0x882a, "exif:TimeZoneOffset" }, { 0x882b, "exif:SelfTimerMode" }, { 0x9000, "exif:ExifVersion" }, { 0x9003, "exif:DateTimeOriginal" }, { 0x9004, "exif:DateTimeDigitized" }, { 0x9101, "exif:ComponentsConfiguration" }, { 0x9102, "exif:CompressedBitsPerPixel" }, { 0x9201, "exif:ShutterSpeedValue" }, { 0x9202, "exif:ApertureValue" }, { 0x9203, "exif:BrightnessValue" }, { 0x9204, "exif:ExposureBiasValue" }, { 0x9205, "exif:MaxApertureValue" }, { 0x9206, "exif:SubjectDistance" }, { 0x9207, "exif:MeteringMode" }, { 0x9208, "exif:LightSource" }, { 0x9209, "exif:Flash" }, { 0x920a, "exif:FocalLength" }, { 0x920b, "exif:FlashEnergy" }, { 0x920c, "exif:SpatialFrequencyResponse" }, { 0x920d, "exif:Noise" }, { 0x9211, "exif:ImageNumber" }, { 0x9212, "exif:SecurityClassification" }, { 0x9213, "exif:ImageHistory" }, { 0x9214, "exif:SubjectArea" }, { 0x9215, "exif:ExposureIndex" }, { 0x9216, "exif:TIFF-EPStandardID" }, { 0x927c, "exif:MakerNote" }, { 0x9C9b, "exif:WinXP-Title" }, { 0x9C9c, "exif:WinXP-Comments" }, { 0x9C9d, "exif:WinXP-Author" }, { 0x9C9e, "exif:WinXP-Keywords" }, { 0x9C9f, "exif:WinXP-Subject" }, { 0x9286, "exif:UserComment" }, { 0x9290, "exif:SubSecTime" }, { 0x9291, "exif:SubSecTimeOriginal" }, { 0x9292, "exif:SubSecTimeDigitized" }, { 0xa000, "exif:FlashPixVersion" }, { 0xa001, "exif:ColorSpace" }, { 0xa002, "exif:ExifImageWidth" }, { 0xa003, "exif:ExifImageLength" }, { 0xa004, "exif:RelatedSoundFile" }, { 0xa005, "exif:InteroperabilityOffset" }, { 0xa20b, "exif:FlashEnergy" }, { 0xa20c, "exif:SpatialFrequencyResponse" }, { 0xa20d, "exif:Noise" }, { 0xa20e, "exif:FocalPlaneXResolution" }, { 0xa20f, "exif:FocalPlaneYResolution" }, { 0xa210, "exif:FocalPlaneResolutionUnit" }, { 0xa214, "exif:SubjectLocation" }, { 0xa215, "exif:ExposureIndex" }, { 0xa216, "exif:TIFF/EPStandardID" }, { 0xa217, "exif:SensingMethod" }, { 0xa300, "exif:FileSource" }, { 0xa301, "exif:SceneType" }, { 0xa302, "exif:CFAPattern" }, { 0xa401, "exif:CustomRendered" }, { 0xa402, "exif:ExposureMode" }, { 0xa403, "exif:WhiteBalance" }, { 0xa404, "exif:DigitalZoomRatio" }, { 0xa405, "exif:FocalLengthIn35mmFilm" }, { 0xa406, "exif:SceneCaptureType" }, { 0xa407, "exif:GainControl" }, { 0xa408, "exif:Contrast" }, { 0xa409, "exif:Saturation" }, { 0xa40a, "exif:Sharpness" }, { 0xa40b, "exif:DeviceSettingDescription" }, { 0xa40c, "exif:SubjectDistanceRange" }, { 0xa420, "exif:ImageUniqueID" }, { 0xc4a5, "exif:PrintImageMatching" }, { 0xa500, "exif:Gamma" }, { 0xc640, "exif:CR2Slice" }, { 0x10000, "exif:GPSVersionID" }, { 0x10001, "exif:GPSLatitudeRef" }, { 0x10002, "exif:GPSLatitude" }, { 0x10003, "exif:GPSLongitudeRef" }, { 0x10004, "exif:GPSLongitude" }, { 0x10005, "exif:GPSAltitudeRef" }, { 0x10006, "exif:GPSAltitude" }, { 0x10007, "exif:GPSTimeStamp" }, { 0x10008, "exif:GPSSatellites" }, { 0x10009, "exif:GPSStatus" }, { 0x1000a, "exif:GPSMeasureMode" }, { 0x1000b, "exif:GPSDop" }, { 0x1000c, "exif:GPSSpeedRef" }, { 0x1000d, "exif:GPSSpeed" }, { 0x1000e, "exif:GPSTrackRef" }, { 0x1000f, "exif:GPSTrack" }, { 0x10010, "exif:GPSImgDirectionRef" }, { 0x10011, "exif:GPSImgDirection" }, { 0x10012, "exif:GPSMapDatum" }, { 0x10013, "exif:GPSDestLatitudeRef" }, { 0x10014, "exif:GPSDestLatitude" }, { 0x10015, "exif:GPSDestLongitudeRef" }, { 0x10016, "exif:GPSDestLongitude" }, { 0x10017, "exif:GPSDestBearingRef" }, { 0x10018, "exif:GPSDestBearing" }, { 0x10019, "exif:GPSDestDistanceRef" }, { 0x1001a, "exif:GPSDestDistance" }, { 0x1001b, "exif:GPSProcessingMethod" }, { 0x1001c, "exif:GPSAreaInformation" }, { 0x1001d, "exif:GPSDateStamp" }, { 0x1001e, "exif:GPSDifferential" }, { 0x00000, (const char *) NULL } }; const StringInfo *profile; const unsigned char *directory, *exif; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; MagickBooleanType status; register ssize_t i; size_t entry, length, number_entries, tag, tag_value; SplayTreeInfo *exif_resources; ssize_t all, id, level, offset, tag_offset; static int tag_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; /* If EXIF data exists, then try to parse the request for a tag. */ profile=GetImageProfile(image,"exif"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); while (isspace((int) ((unsigned char) *property)) != 0) property++; if (strlen(property) <= 5) return(MagickFalse); all=0; tag=(~0UL); switch (*(property+5)) { case '*': { /* Caller has asked for all the tags in the EXIF data. */ tag=0; all=1; /* return the data in description=value format */ break; } case '!': { tag=0; all=2; /* return the data in tagid=value format */ break; } case '#': case '@': { int c; size_t n; /* Check for a hex based tag specification first. */ tag=(*(property+5) == '@') ? 1UL : 0UL; property+=6; n=strlen(property); if (n != 4) return(MagickFalse); /* Parse tag specification as a hex number. */ n/=4; do { for (i=(ssize_t) n-1L; i >= 0; i--) { c=(*property++); tag<<=4; if ((c >= '0') && (c <= '9')) tag|=(c-'0'); else if ((c >= 'A') && (c <= 'F')) tag|=(c-('A'-10)); else if ((c >= 'a') && (c <= 'f')) tag|=(c-('a'-10)); else return(MagickFalse); } } while (*property != '\0'); break; } default: { /* Try to match the text with a tag name instead. */ for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (LocaleCompare(EXIFTag[i].description,property) == 0) { tag=(size_t) EXIFTag[i].tag; break; } } break; } } if (tag == (~0UL)) return(MagickFalse); length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); while (length != 0) { if (ReadPropertyByte(&exif,&length) != 0x45) continue; if (ReadPropertyByte(&exif,&length) != 0x78) continue; if (ReadPropertyByte(&exif,&length) != 0x69) continue; if (ReadPropertyByte(&exif,&length) != 0x66) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; if (ReadPropertyByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadPropertySignedShort(LSBEndian,exif); endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadPropertyUnsignedShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadPropertySignedLong(endian,exif+4); if ((offset < 0) || (size_t) offset >= length) return(MagickFalse); /* Set the pointer to the first IFD and follow it were it leads. */ status=MagickFalse; directory=exif+offset; level=0; entry=0; tag_offset=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { /* If there is anything on the stack then pop it off. */ if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; tag_offset=directory_stack[level].offset; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=(size_t) ReadPropertyUnsignedShort(endian,directory); for ( ; entry < number_entries; entry++) { register unsigned char *p, *q; size_t format; ssize_t number_bytes, components; q=(unsigned char *) (directory+(12*entry)+2); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(size_t) ReadPropertyUnsignedShort(endian,q)+tag_offset; format=(size_t) ReadPropertyUnsignedShort(endian,q+2); if (format >= (sizeof(tag_bytes)/sizeof(*tag_bytes))) break; components=(ssize_t) ReadPropertySignedLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*tag_bytes[format]; if (number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { ssize_t offset; /* The directory entry contains an offset. */ offset=(ssize_t) ReadPropertySignedLong(endian,q+8); if ((offset < 0) || (size_t) offset >= length) continue; if ((ssize_t) (offset+number_bytes) < offset) continue; /* prevent overflow */ if ((size_t) (offset+number_bytes) > length) continue; p=(unsigned char *) (exif+offset); } if ((all != 0) || (tag == (size_t) tag_value)) { char buffer[MagickPathExtent], *value; value=(char *) NULL; *buffer='\0'; switch (format) { case EXIF_FMT_BYTE: case EXIF_FMT_UNDEFINED: { EXIFMultipleValues(1,"%.20g",(double) (*(unsigned char *) p1)); break; } case EXIF_FMT_SBYTE: { EXIFMultipleValues(1,"%.20g",(double) (*(signed char *) p1)); break; } case EXIF_FMT_SSHORT: { EXIFMultipleValues(2,"%hd",ReadPropertySignedShort(endian,p1)); break; } case EXIF_FMT_USHORT: { EXIFMultipleValues(2,"%hu",ReadPropertyUnsignedShort(endian,p1)); break; } case EXIF_FMT_ULONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertyUnsignedLong(endian,p1)); break; } case EXIF_FMT_SLONG: { EXIFMultipleValues(4,"%.20g",(double) ReadPropertySignedLong(endian,p1)); break; } case EXIF_FMT_URATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertyUnsignedLong(endian,p1),(double) ReadPropertyUnsignedLong(endian,p1+4)); break; } case EXIF_FMT_SRATIONAL: { EXIFMultipleFractions(8,"%.20g/%.20g",(double) ReadPropertySignedLong(endian,p1),(double) ReadPropertySignedLong(endian,p1+4)); break; } case EXIF_FMT_SINGLE: { EXIFMultipleValues(4,"%f",(double) *(float *) p1); break; } case EXIF_FMT_DOUBLE: { EXIFMultipleValues(8,"%f",*(double *) p1); break; } default: case EXIF_FMT_STRING: { value=(char *) NULL; if (~((size_t) number_bytes) >= 1) value=(char *) AcquireQuantumMemory((size_t) number_bytes+1UL, sizeof(*value)); if (value != (char *) NULL) { register ssize_t i; for (i=0; i < (ssize_t) number_bytes; i++) { value[i]='.'; if ((isprint((int) p[i]) != 0) || (p[i] == '\0')) value[i]=(char) p[i]; } value[i]='\0'; } break; } } if (value != (char *) NULL) { char *key; register const char *p; key=AcquireString(property); switch (all) { case 1: { const char *description; register ssize_t i; description="unknown"; for (i=0; ; i++) { if (EXIFTag[i].tag == 0) break; if (EXIFTag[i].tag == tag_value) { description=EXIFTag[i].description; break; } } (void) FormatLocaleString(key,MagickPathExtent,"%s", description); if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); break; } case 2: { if (tag_value < 0x10000) (void) FormatLocaleString(key,MagickPathExtent,"#%04lx", (unsigned long) tag_value); else if (tag_value < 0x20000) (void) FormatLocaleString(key,MagickPathExtent,"@%04lx", (unsigned long) (tag_value & 0xffff)); else (void) FormatLocaleString(key,MagickPathExtent,"unknown"); break; } default: { if (level == 2) (void) SubstituteString(&key,"exif:","exif:thumbnail:"); } } p=(const char *) NULL; if (image->properties != (void *) NULL) p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,key); if (p == (const char *) NULL) (void) SetImageProperty((Image *) image,key,value,exception); value=DestroyString(value); key=DestroyString(key); status=MagickTrue; } } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET) || (tag_value == TAG_GPS_OFFSET)) { ssize_t offset; offset=(ssize_t) ReadPropertySignedLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { ssize_t tag_offset1; tag_offset1=(ssize_t) ((tag_value == TAG_GPS_OFFSET) ? 0x10000 : 0); directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; directory_stack[level].offset=tag_offset; level++; directory_stack[level].directory=exif+offset; directory_stack[level].offset=tag_offset1; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadPropertySignedLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; directory_stack[level].offset=tag_offset1; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(status); } static MagickBooleanType GetICCProperty(const Image *image,const char *property, ExceptionInfo *exception) { const StringInfo *profile; magick_unreferenced(property); profile=GetImageProfile(image,"icc"); if (profile == (StringInfo *) NULL) profile=GetImageProfile(image,"icm"); if (profile == (StringInfo *) NULL) return(MagickFalse); if (GetStringInfoLength(profile) < 128) return(MagickFalse); /* minimum ICC profile length */ #if defined(MAGICKCORE_LCMS_DELEGATE) { cmsHPROFILE icc_profile; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) const char *name; name=cmsTakeProductName(icc_profile); if (name != (const char *) NULL) (void) SetImageProperty((Image *) image,"icc:name",name,exception); #else char info[MagickPathExtent]; (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:description",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoManufacturer, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:manufacturer",info, exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoModel,"en", "US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:model",info,exception); (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoCopyright, "en","US",info,MagickPathExtent); (void) SetImageProperty((Image *) image,"icc:copyright",info,exception); #endif (void) cmsCloseProfile(icc_profile); } } #endif return(MagickTrue); } static MagickBooleanType SkipXMPValue(const char *value) { if (value == (const char*) NULL) return(MagickTrue); while (*value != '\0') { if (isspace((int) ((unsigned char) *value)) == 0) return(MagickFalse); value++; } return(MagickTrue); } static MagickBooleanType GetXMPProperty(const Image *image,const char *property) { char *xmp_profile; const char *content; const StringInfo *profile; ExceptionInfo *exception; MagickBooleanType status; register const char *p; XMLTreeInfo *child, *description, *node, *rdf, *xmp; profile=GetImageProfile(image,"xmp"); if (profile == (StringInfo *) NULL) return(MagickFalse); if ((property == (const char *) NULL) || (*property == '\0')) return(MagickFalse); xmp_profile=StringInfoToString(profile); if (xmp_profile == (char *) NULL) return(MagickFalse); for (p=xmp_profile; *p != '\0'; p++) if ((*p == '<') && (*(p+1) == 'x')) break; exception=AcquireExceptionInfo(); xmp=NewXMLTree((char *) p,exception); xmp_profile=DestroyString(xmp_profile); exception=DestroyExceptionInfo(exception); if (xmp == (XMLTreeInfo *) NULL) return(MagickFalse); status=MagickFalse; rdf=GetXMLTreeChild(xmp,"rdf:RDF"); if (rdf != (XMLTreeInfo *) NULL) { if (image->properties == (void *) NULL) ((Image *) image)->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); description=GetXMLTreeChild(rdf,"rdf:Description"); while (description != (XMLTreeInfo *) NULL) { node=GetXMLTreeChild(description,(const char *) NULL); while (node != (XMLTreeInfo *) NULL) { child=GetXMLTreeChild(node,(const char *) NULL); content=GetXMLTreeContent(node); if ((child == (XMLTreeInfo *) NULL) && (SkipXMPValue(content) == MagickFalse)) (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(GetXMLTreeTag(node)),ConstantString(content)); while (child != (XMLTreeInfo *) NULL) { content=GetXMLTreeContent(child); if (SkipXMPValue(content) == MagickFalse) (void) AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(GetXMLTreeTag(child)),ConstantString(content)); child=GetXMLTreeSibling(child); } node=GetXMLTreeSibling(node); } description=GetNextXMLTreeTag(description); } } xmp=DestroyXMLTree(xmp); return(status); } static char *TracePSClippath(const unsigned char *blob,size_t length) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i, x; ssize_t knot_count, selector, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent,"/ClipImage\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"{\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /c {curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /l {lineto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," /m {moveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /v {currentpoint 6 2 roll curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /y {2 copy curveto} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent, " /z {closepath} bind def\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent," newpath\n"); (void) ConcatenateString(&path,message); /* The clipping path format is defined in "Adobe Photoshop File Formats Specification" version 6.0 downloadable from adobe.com. */ (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length > 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { size_t xx, yy; yy=(size_t) ReadPropertyMSBLong(&blob,&length); xx=(size_t) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x/4096/4096; point[i].y=1.0-(double) y/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent," %g %g m\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l\n",point[1].x,point[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v\n",point[0].x,point[0].y, point[1].x,point[1].y); else if ((point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y\n",last[2].x,last[2].y, point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g l z\n",first[1].x,first[1].y); else if ((last[1].x == last[2].x) && (last[1].y == last[2].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g v z\n",first[0].x,first[0].y, first[1].x,first[1].y); else if ((first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g y z\n",last[2].x,last[2].y, first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, " %g %g %g %g %g %g c z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Returns an empty PS path if the path has no knots. */ (void) FormatLocaleString(message,MagickPathExtent," eoclip\n"); (void) ConcatenateString(&path,message); (void) FormatLocaleString(message,MagickPathExtent,"} bind def"); (void) ConcatenateString(&path,message); message=DestroyString(message); return(path); } static char *TraceSVGClippath(const unsigned char *blob,size_t length, const size_t columns,const size_t rows) { char *path, *message; MagickBooleanType in_subpath; PointInfo first[3], last[3], point[3]; register ssize_t i; ssize_t knot_count, selector, x, y; path=AcquireString((char *) NULL); if (path == (char *) NULL) return((char *) NULL); message=AcquireString((char *) NULL); (void) FormatLocaleString(message,MagickPathExtent, ("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\n" "<svg xmlns=\"http://www.w3.org/2000/svg\"" " width=\"%.20g\" height=\"%.20g\">\n" "<g>\n" "<path fill-rule=\"evenodd\" style=\"fill:#00000000;stroke:#00000000;" "stroke-width:0;stroke-antialiasing:false\" d=\"\n"), (double) columns,(double) rows); (void) ConcatenateString(&path,message); (void) ResetMagickMemory(point,0,sizeof(point)); (void) ResetMagickMemory(first,0,sizeof(first)); (void) ResetMagickMemory(last,0,sizeof(last)); knot_count=0; in_subpath=MagickFalse; while (length != 0) { selector=(ssize_t) ReadPropertyMSBShort(&blob,&length); switch (selector) { case 0: case 3: { if (knot_count != 0) { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Expected subpath length record. */ knot_count=(ssize_t) ReadPropertyMSBShort(&blob,&length); blob+=22; length-=MagickMin(22,(ssize_t) length); break; } case 1: case 2: case 4: case 5: { if (knot_count == 0) { /* Unexpected subpath knot. */ blob+=24; length-=MagickMin(24,(ssize_t) length); break; } /* Add sub-path knot */ for (i=0; i < 3; i++) { unsigned int xx, yy; yy=(unsigned int) ReadPropertyMSBLong(&blob,&length); xx=(unsigned int) ReadPropertyMSBLong(&blob,&length); x=(ssize_t) xx; if (xx > 2147483647) x=(ssize_t) xx-4294967295U-1; y=(ssize_t) yy; if (yy > 2147483647) y=(ssize_t) yy-4294967295U-1; point[i].x=(double) x*columns/4096/4096; point[i].y=(double) y*rows/4096/4096; } if (in_subpath == MagickFalse) { (void) FormatLocaleString(message,MagickPathExtent,"M %g %g\n", point[1].x,point[1].y); for (i=0; i < 3; i++) { first[i]=point[i]; last[i]=point[i]; } } else { /* Handle special cases when Bezier curves are used to describe corners and straight lines. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (point[0].x == point[1].x) && (point[0].y == point[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g\n",point[1].x,point[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g\n",last[2].x, last[2].y,point[0].x,point[0].y,point[1].x,point[1].y); for (i=0; i < 3; i++) last[i]=point[i]; } (void) ConcatenateString(&path,message); in_subpath=MagickTrue; knot_count--; /* Close the subpath if there are no more knots. */ if (knot_count == 0) { /* Same special handling as above except we compare to the first point in the path and close the path. */ if ((last[1].x == last[2].x) && (last[1].y == last[2].y) && (first[0].x == first[1].x) && (first[0].y == first[1].y)) (void) FormatLocaleString(message,MagickPathExtent, "L %g %g Z\n",first[1].x,first[1].y); else (void) FormatLocaleString(message,MagickPathExtent, "C %g %g %g %g %g %g Z\n",last[2].x, last[2].y,first[0].x,first[0].y,first[1].x,first[1].y); (void) ConcatenateString(&path,message); in_subpath=MagickFalse; } break; } case 6: case 7: case 8: default: { blob+=24; length-=MagickMin(24,(ssize_t) length); break; } } } /* Return an empty SVG image if the path does not have knots. */ (void) ConcatenateString(&path,"\"/>\n</g>\n</svg>\n"); message=DestroyString(message); return(path); } MagickExport const char *GetImageProperty(const Image *image, const char *property,ExceptionInfo *exception) { register const char *p; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); p=(const char *) NULL; if (image->properties != (void *) NULL) { if (property == (const char *) NULL) { ResetSplayTreeIterator((SplayTreeInfo *) image->properties); p=(const char *) GetNextValueInSplayTree((SplayTreeInfo *) image->properties); return(p); } p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); if (p != (const char *) NULL) return(p); } if ((property == (const char *) NULL) || (strchr(property,':') == (char *) NULL)) return(p); switch (*property) { case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) Get8BIMProperty(image,property,exception); break; } break; } case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) GetEXIFProperty(image,property,exception); break; } break; } case 'I': case 'i': { if ((LocaleNCompare("icc:",property,4) == 0) || (LocaleNCompare("icm:",property,4) == 0)) { (void) GetICCProperty(image,property,exception); break; } if (LocaleNCompare("iptc:",property,5) == 0) { (void) GetIPTCProperty(image,property,exception); break; } break; } case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) GetXMPProperty(image,property); break; } break; } default: break; } if (image->properties != (void *) NULL) { p=(const char *) GetValueFromSplayTree((SplayTreeInfo *) image->properties,property); return(p); } return((const char *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t M a g i c k P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickProperty() gets attributes or calculated values that is associated % with a fixed known property name, or single letter property. It may be % called if no image is defined (IMv7), in which case only global image_info % values are available: % % \n newline % \r carriage return % < less-than character. % > greater-than character. % & ampersand character. % %% a percent sign % %b file size of image read in % %c comment meta-data property % %d directory component of path % %e filename extension or suffix % %f filename (including suffix) % %g layer canvas page geometry (equivalent to "%Wx%H%X%Y") % %h current image height in pixels % %i image filename (note: becomes output filename for "info:") % %k CALCULATED: number of unique colors % %l label meta-data property % %m image file format (file magic) % %n number of images in current image sequence % %o output filename (used for delegates) % %p index of image in current image list % %q quantum depth (compile-time constant) % %r image class and colorspace % %s scene number (from input unless re-assigned) % %t filename without directory or extension (suffix) % %u unique temporary filename (used for delegates) % %w current width in pixels % %x x resolution (density) % %y y resolution (density) % %z image depth (as read in unless modified, image save depth) % %A image transparency channel enabled (true/false) % %C image compression type % %D image GIF dispose method % %G original image size (%wx%h; before any resizes) % %H page (canvas) height % %M Magick filename (original file exactly as given, including read mods) % %O page (canvas) offset ( = %X%Y ) % %P page (canvas) size ( = %Wx%H ) % %Q image compression quality ( 0 = default ) % %S ?? scenes ?? % %T image time delay (in centi-seconds) % %U image resolution units % %W page (canvas) width % %X page (canvas) x offset (including sign) % %Y page (canvas) y offset (including sign) % %Z unique filename (used for delegates) % %@ CALCULATED: trim bounding box (without actually trimming) % %# CALCULATED: 'signature' hash of image values % % This routine only handles specifically known properties. It does not % handle special prefixed properties, profiles, or expressions. Nor does % it return any free-form property strings. % % The returned string is stored in a structure somewhere, and should not be % directly freed. If the string was generated (common) the string will be % stored as as either as artifact or option 'get-property'. These may be % deleted (cleaned up) when no longer required, but neither artifact or % option is guranteed to exist. % % The format of the GetMagickProperty method is: % % const char *GetMagickProperty(ImageInfo *image_info,Image *image, % const char *property,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info (optional) % % o image: the image (optional) % % o key: the key. % % o exception: return any errors or warnings in this structure. % */ static const char *GetMagickPropertyLetter(ImageInfo *image_info, Image *image,const char letter,ExceptionInfo *exception) { #define WarnNoImageReturn(format,arg) \ if (image == (Image *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageForProperty",format,arg); \ return((const char *) NULL); \ } #define WarnNoImageInfoReturn(format,arg) \ if (image_info == (ImageInfo *) NULL ) { \ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, \ "NoImageInfoForProperty",format,arg); \ return((const char *) NULL); \ } char value[MagickPathExtent]; /* formated string to store as a returned artifact */ const char *string; /* return a string already stored somewher */ if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formatted string */ string=(char *) NULL; /* constant string reference */ /* Get properities that are directly defined by images. */ switch (letter) { case 'b': /* image size read in - in bytes */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatMagickSize(image->extent,MagickFalse,"B",MagickPathExtent, value); if (image->extent == 0) (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } case 'c': /* image comment property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"comment",exception); if ( string == (const char *) NULL ) string=""; break; } case 'd': /* Directory component of filename */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } case 'e': /* Filename extension (suffix) of image file */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } case 'f': /* Filename without directory component */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,TailPath,value); if (*value == '\0') string=""; break; } case 'g': /* Image geometry, canvas and offset %Wx%H+%X+%Y */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); break; } case 'h': /* Image height (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->rows != 0 ? image->rows : image->magick_rows)); break; } case 'i': /* Filename last used for an image (read or write) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->filename; break; } case 'k': /* Number of unique colors */ { /* FUTURE: ensure this does not generate the formatted comment! */ WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetNumberColors(image,(FILE *) NULL,exception)); break; } case 'l': /* Image label property - empty string by default */ { WarnNoImageReturn("\"%%%c\"",letter); string=GetImageProperty(image,"label",exception); if ( string == (const char *) NULL) string=""; break; } case 'm': /* Image format (file magick) */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick; break; } case 'n': /* Number of images in the list. */ { if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); else string="0"; /* no images or scenes */ break; } case 'o': /* Output Filename - for delegate use only */ WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->filename; break; case 'p': /* Image index in current image list */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageIndexInList(image)); break; } case 'q': /* Quantum depth of image in memory */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) MAGICKCORE_QUANTUM_DEPTH); break; } case 'r': /* Image storage class, colorspace, and alpha enabled. */ { ColorspaceType colorspace; WarnNoImageReturn("\"%%%c\"",letter); colorspace=image->colorspace; if (SetImageGray(image,exception) != MagickFalse) colorspace=GRAYColorspace; /* FUTURE: this is IMv6 not IMv7 */ (void) FormatLocaleString(value,MagickPathExtent,"%s %s %s", CommandOptionToMnemonic(MagickClassOptions,(ssize_t) image->storage_class),CommandOptionToMnemonic(MagickColorspaceOptions, (ssize_t) colorspace),image->alpha_trait != UndefinedPixelTrait ? "Alpha" : ""); break; } case 's': /* Image scene number */ { #if 0 /* this seems non-sensical -- simplifing */ if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else if (image != (Image *) NULL) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); else string="0"; #else WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); #endif break; } case 't': /* Base filename without directory or extention */ { WarnNoImageReturn("\"%%%c\"",letter); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } case 'u': /* Unique filename */ { WarnNoImageInfoReturn("\"%%%c\"",letter); string=image_info->unique; break; } case 'w': /* Image width (current) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->columns != 0 ? image->columns : image->magick_columns)); break; } case 'x': /* Image horizontal resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.x) > MagickEpsilon ? image->resolution.x : 72.0); break; } case 'y': /* Image vertical resolution (with units) */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", fabs(image->resolution.y) > MagickEpsilon ? image->resolution.y : 72.0); break; } case 'z': /* Image depth as read in */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) image->depth); break; } case 'A': /* Image alpha channel */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickPixelTraitOptions,(ssize_t) image->alpha_trait); break; } case 'C': /* Image compression method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickCompressOptions, (ssize_t) image->compression); break; } case 'D': /* Image dispose method. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickDisposeOptions, (ssize_t) image->dispose); break; } case 'G': /* Image size as geometry = "%wx%h" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g", (double)image->magick_columns,(double) image->magick_rows); break; } case 'H': /* layer canvas height */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", (double) image->page.height); break; } case 'M': /* Magick filename - filename given incl. coder & read mods */ { WarnNoImageReturn("\"%%%c\"",letter); string=image->magick_filename; break; } case 'O': /* layer canvas offset with sign = "+%X+%Y" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+ld%+ld",(long) image->page.x,(long) image->page.y); break; } case 'P': /* layer canvas page size = "%Wx%H" */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20gx%.20g", (double) image->page.width,(double) image->page.height); break; } case 'Q': /* image compression quality */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->quality == 0 ? 92 : image->quality)); break; } case 'S': /* Number of scenes in image list. */ { WarnNoImageInfoReturn("\"%%%c\"",letter); #if 0 /* What is this number? -- it makes no sense - simplifing */ if (image_info->number_scenes == 0) string="2147483647"; else if ( image != (Image *) NULL ) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene+image_info->number_scenes); else string="0"; #else (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image_info->number_scenes == 0 ? 2147483647 : image_info->number_scenes)); #endif break; } case 'T': /* image time delay for animations */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->delay); break; } case 'U': /* Image resolution units. */ { WarnNoImageReturn("\"%%%c\"",letter); string=CommandOptionToMnemonic(MagickResolutionOptions, (ssize_t) image->units); break; } case 'W': /* layer canvas width */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->page.width); break; } case 'X': /* layer canvas X offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.x); break; } case 'Y': /* layer canvas Y offset */ { WarnNoImageReturn("\"%%%c\"",letter); (void) FormatLocaleString(value,MagickPathExtent,"%+.20g",(double) image->page.y); break; } case '%': /* percent escaped */ { string="%"; break; } case '@': /* Trim bounding box, without actually Trimming! */ { RectangleInfo page; WarnNoImageReturn("\"%%%c\"",letter); page=GetImageBoundingBox(image,exception); (void) FormatLocaleString(value,MagickPathExtent, "%.20gx%.20g%+.20g%+.20g",(double) page.width,(double) page.height, (double) page.x,(double)page.y); break; } case '#': { /* Image signature. */ WarnNoImageReturn("\"%%%c\"",letter); (void) SignatureImage(image,exception); string=GetImageProperty(image,"signature",exception); break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* Create a cloned copy of result. */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } MagickExport const char *GetMagickProperty(ImageInfo *image_info, Image *image,const char *property,ExceptionInfo *exception) { char value[MagickPathExtent]; const char *string; assert(property[0] != '\0'); assert(image != (Image *) NULL || image_info != (ImageInfo *) NULL ); if (property[1] == '\0') /* single letter property request */ return(GetMagickPropertyLetter(image_info,image,*property,exception)); if (image != (Image *) NULL && image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if( image_info != (ImageInfo *) NULL && image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-images"); *value='\0'; /* formated string */ string=(char *) NULL; /* constant string reference */ switch (*property) { case 'b': { if (LocaleCompare("basename",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,BasePath,value); if (*value == '\0') string=""; break; } if (LocaleCompare("bit-depth",property) == 0) { (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageDepth(image, exception)); break; } break; } case 'c': { if (LocaleCompare("channels",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual image channels */ (void) FormatLocaleString(value,MagickPathExtent,"%s", CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace)); LocaleLower(value); if( image->alpha_trait != UndefinedPixelTrait ) (void) ConcatenateMagickString(value,"a",MagickPathExtent); break; } if (LocaleCompare("colorspace",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); /* FUTURE: return actual colorspace - no 'gray' stuff */ string=CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) image->colorspace); break; } if (LocaleCompare("copyright",property) == 0) { (void) CopyMagickString(value,GetMagickCopyright(),MagickPathExtent); break; } break; } case 'd': { if (LocaleCompare("depth",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->depth); break; } if (LocaleCompare("directory",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,HeadPath,value); if (*value == '\0') string=""; break; } break; } case 'e': { if (LocaleCompare("entropy",property) == 0) { double entropy; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageEntropy(image,&entropy,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),entropy); break; } if (LocaleCompare("extension",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); GetPathComponent(image->magick_filename,ExtensionPath,value); if (*value == '\0') string=""; break; } break; } case 'g': { if (LocaleCompare("gamma",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),image->gamma); break; } break; } case 'h': { if (LocaleCompare("height",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g", image->magick_rows != 0 ? (double) image->magick_rows : 256.0); break; } break; } case 'i': { if (LocaleCompare("input",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->filename; break; } break; } case 'k': { if (LocaleCompare("kurtosis",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),kurtosis); break; } break; } case 'm': { if (LocaleCompare("magick",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=image->magick; break; } if ((LocaleCompare("maxima",property) == 0) || (LocaleCompare("max",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),maximum); break; } if (LocaleCompare("mean",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),mean); break; } if ((LocaleCompare("minima",property) == 0) || (LocaleCompare("min",property) == 0)) { double maximum, minimum; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageRange(image,&minimum,&maximum,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),minimum); break; } break; } case 'o': { if (LocaleCompare("opaque",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickBooleanOptions,(ssize_t) IsImageOpaque(image,exception)); break; } if (LocaleCompare("orientation",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickOrientationOptions,(ssize_t) image->orientation); break; } if (LocaleCompare("output",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); (void) CopyMagickString(value,image_info->filename,MagickPathExtent); break; } break; } case 'p': { #if defined(MAGICKCORE_LCMS_DELEGATE) if (LocaleCompare("profile:icc",property) == 0 || LocaleCompare("profile:icm",property) == 0) { #if !defined(LCMS_VERSION) || (LCMS_VERSION < 2000) #define cmsUInt32Number DWORD #endif const StringInfo *profile; cmsHPROFILE icc_profile; profile=GetImageProfile(image,property+8); if (profile == (StringInfo *) NULL) break; icc_profile=cmsOpenProfileFromMem(GetStringInfoDatum(profile), (cmsUInt32Number) GetStringInfoLength(profile)); if (icc_profile != (cmsHPROFILE *) NULL) { #if defined(LCMS_VERSION) && (LCMS_VERSION < 2000) string=cmsTakeProductName(icc_profile); #else (void) cmsGetProfileInfoASCII(icc_profile,cmsInfoDescription, "en","US",value,MagickPathExtent); #endif (void) cmsCloseProfile(icc_profile); } } #endif if (LocaleCompare("profiles",property) == 0) { const char *name; ResetImageProfileIterator(image); name=GetNextImageProfile(image); if (name != (char *) NULL) { (void) CopyMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); while (name != (char *) NULL) { ConcatenateMagickString(value,",",MagickPathExtent); ConcatenateMagickString(value,name,MagickPathExtent); name=GetNextImageProfile(image); } } break; } break; } case 'r': { if (LocaleCompare("resolution.x",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); break; } if (LocaleCompare("resolution.y",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); break; } break; } case 's': { if (LocaleCompare("scene",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); if (image_info->number_scenes != 0) (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image_info->scene); else { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) image->scene); } break; } if (LocaleCompare("scenes",property) == 0) { /* FUTURE: equivelent to %n? */ WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) GetImageListLength(image)); break; } if (LocaleCompare("size",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatMagickSize(GetBlobSize(image),MagickFalse,"B", MagickPathExtent,value); break; } if (LocaleCompare("skewness",property) == 0) { double kurtosis, skewness; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),skewness); break; } if (LocaleCompare("standard-deviation",property) == 0) { double mean, standard_deviation; WarnNoImageReturn("\"%%[%s]\"",property); (void) GetImageMean(image,&mean,&standard_deviation,exception); (void) FormatLocaleString(value,MagickPathExtent,"%.*g", GetMagickPrecision(),standard_deviation); break; } break; } case 't': { if (LocaleCompare("type",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) IdentifyImageType(image,exception)); break; } break; } case 'u': { if (LocaleCompare("unique",property) == 0) { WarnNoImageInfoReturn("\"%%[%s]\"",property); string=image_info->unique; break; } if (LocaleCompare("units",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); string=CommandOptionToMnemonic(MagickResolutionOptions,(ssize_t) image->units); break; } if (LocaleCompare("copyright",property) == 0) break; } case 'v': { if (LocaleCompare("version",property) == 0) { string=GetMagickVersion((size_t *) NULL); break; } break; } case 'w': { if (LocaleCompare("width",property) == 0) { WarnNoImageReturn("\"%%[%s]\"",property); (void) FormatLocaleString(value,MagickPathExtent,"%.20g",(double) (image->magick_columns != 0 ? image->magick_columns : 256)); break; } break; } } if (string != (char *) NULL) return(string); if (*value != '\0') { /* create a cloned copy of result, that will get cleaned up, eventually */ if (image != (Image *) NULL) { (void) SetImageArtifact(image,"get-property",value); return(GetImageArtifact(image,"get-property")); } else { (void) SetImageOption(image_info,"get-property",value); return(GetImageOption(image_info,"get-property")); } } return((char *) NULL); } #undef WarnNoImageReturn /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProperty() gets the next free-form string property name. % % The format of the GetNextImageProperty method is: % % char *GetNextImageProperty(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetNextImageProperty(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return((const char *) NULL); return((const char *) GetNextKeyInSplayTree( (SplayTreeInfo *) image->properties)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p r e t I m a g e P r o p e r t i e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpretImageProperties() replaces any embedded formatting characters with % the appropriate image property and returns the interpreted text. % % This searches for and replaces % \n \r \% replaced by newline, return, and percent resp. % &lt; &gt; &amp; replaced by '<', '>', '&' resp. % %% replaced by percent % % %x %[x] where 'x' is a single letter properity, case sensitive). % %[type:name] where 'type' a is special and known prefix. % %[name] where 'name' is a specifically known attribute, calculated % value, or a per-image property string name, or a per-image % 'artifact' (as generated from a global option). % It may contain ':' as long as the prefix is not special. % % Single letter % substitutions will only happen if the character before the % percent is NOT a number. But braced substitutions will always be performed. % This prevents the typical usage of percent in a interpreted geometry % argument from being substituted when the percent is a geometry flag. % % If 'glob-expresions' ('*' or '?' characters) is used for 'name' it may be % used as a search pattern to print multiple lines of "name=value\n" pairs of % the associacted set of properties. % % The returned string must be freed using DestoryString() by the caller. % % The format of the InterpretImageProperties method is: % % char *InterpretImageProperties(ImageInfo *image_info, % Image *image,const char *embed_text,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. (required) % % o image: the image. (optional) % % o embed_text: the address of a character string containing the embedded % formatting characters. % % o exception: return any errors or warnings in this structure. % */ MagickExport char *InterpretImageProperties(ImageInfo *image_info, Image *image,const char *embed_text,ExceptionInfo *exception) { #define ExtendInterpretText(string_length) \ DisableMSCWarning(4127) \ { \ size_t length=(string_length); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ } \ RestoreMSCWarning #define AppendKeyValue2Text(key,value)\ DisableMSCWarning(4127) \ { \ size_t length=strlen(key)+strlen(value)+2; \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ q+=FormatLocaleString(q,extent,"%s=%s\n",(key),(value)); \ } \ RestoreMSCWarning #define AppendString2Text(string) \ DisableMSCWarning(4127) \ { \ size_t length=strlen((string)); \ if ((size_t) (q-interpret_text+length+1) >= extent) \ { \ extent+=length; \ interpret_text=(char *) ResizeQuantumMemory(interpret_text,extent+ \ MaxTextExtent,sizeof(*interpret_text)); \ if (interpret_text == (char *) NULL) \ return((char *) NULL); \ q=interpret_text+strlen(interpret_text); \ } \ (void) CopyMagickString(q,(string),extent); \ q+=length; \ } \ RestoreMSCWarning char *interpret_text; register char *q; /* current position in interpret_text */ register const char *p; /* position in embed_text string being expanded */ size_t extent; /* allocated length of interpret_text */ MagickBooleanType number; assert(image == NULL || image->signature == MagickCoreSignature); assert(image_info == NULL || image_info->signature == MagickCoreSignature); if ((image != (Image *) NULL) && (image->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); else if ((image_info != (ImageInfo *) NULL) && (image_info->debug != MagickFalse)) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s","no-image"); if (embed_text == (const char *) NULL) return(ConstantString("")); p=embed_text; while ((isspace((int) ((unsigned char) *p)) != 0) && (*p != '\0')) p++; if (*p == '\0') return(ConstantString("")); if ((*p == '@') && (IsPathAccessible(p+1) != MagickFalse)) { /* Handle a '@' replace string from file. */ if (IsRightsAuthorized(PathPolicyDomain,ReadPolicyRights,p) == MagickFalse) { errno=EPERM; (void) ThrowMagickException(exception,GetMagickModule(),PolicyError, "NotAuthorized","`%s'",p); return(ConstantString("")); } interpret_text=FileToString(p+1,~0UL,exception); if (interpret_text != (char *) NULL) return(interpret_text); } /* Translate any embedded format characters. */ interpret_text=AcquireString(embed_text); /* new string with extra space */ extent=MagickPathExtent; /* allocated space in string */ number=MagickFalse; /* is last char a number? */ for (q=interpret_text; *p!='\0'; number=isdigit(*p) ? MagickTrue : MagickFalse,p++) { /* Look for the various escapes, (and handle other specials) */ *q='\0'; ExtendInterpretText(MagickPathExtent); switch (*p) { case '\\': { switch (*(p+1)) { case '\0': continue; case 'r': /* convert to RETURN */ { *q++='\r'; p++; continue; } case 'n': /* convert to NEWLINE */ { *q++='\n'; p++; continue; } case '\n': /* EOL removal UNIX,MacOSX */ { p++; continue; } case '\r': /* EOL removal DOS,Windows */ { p++; if (*p == '\n') /* return-newline EOL */ p++; continue; } default: { p++; *q++=(*p); } } continue; } case '&': { if (LocaleNCompare("&lt;",p,4) == 0) { *q++='<'; p+=3; } else if (LocaleNCompare("&gt;",p,4) == 0) { *q++='>'; p+=3; } else if (LocaleNCompare("&amp;",p,5) == 0) { *q++='&'; p+=4; } else *q++=(*p); continue; } case '%': break; /* continue to next set of handlers */ default: { *q++=(*p); /* any thing else is 'as normal' */ continue; } } p++; /* advance beyond the percent */ /* Doubled Percent - or percent at end of string. */ if ((*p == '\0') || (*p == '\'') || (*p == '"')) p--; if (*p == '%') { *q++='%'; continue; } /* Single letter escapes %c. */ if (*p != '[') { const char *string; if (number != MagickFalse) { /* But only if not preceeded by a number! */ *q++='%'; /* do NOT substitute the percent */ p--; /* back up one */ continue; } string=GetMagickPropertyLetter(image_info,image,*p, exception); if (string != (char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void) DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void) DeleteImageOption(image_info,"get-property"); continue; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%%c\"",*p); continue; } { char pattern[2*MagickPathExtent]; const char *key, *string; register ssize_t len; ssize_t depth; /* Braced Percent Escape %[...]. */ p++; /* advance p to just inside the opening brace */ depth=1; if (*p == ']') { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[]\""); break; } for (len=0; len<(MagickPathExtent-1L) && (*p != '\0');) { if ((*p == '\\') && (*(p+1) != '\0')) { /* Skip escaped braces within braced pattern. */ pattern[len++]=(*p++); pattern[len++]=(*p++); continue; } if (*p == '[') depth++; if (*p == ']') depth--; if (depth <= 0) break; pattern[len++]=(*p++); } pattern[len]='\0'; if (depth != 0) { /* Check for unmatched final ']' for "%[...]". */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"UnbalancedBraces","\"%%[%s\"",pattern); interpret_text=DestroyString(interpret_text); return((char *) NULL); } /* Special Lookup Prefixes %[prefix:...]. */ if (LocaleNCompare("fx:",pattern,3) == 0) { FxInfo *fx_info; double value; MagickBooleanType status; /* FX - value calculator. */ if (image == (Image *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } fx_info=AcquireFxInfo(image,pattern+3,exception); status=FxEvaluateChannelExpression(fx_info,IntensityPixelChannel,0,0, &value,exception); fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char result[MagickPathExtent]; (void) FormatLocaleString(result,MagickPathExtent,"%.*g", GetMagickPrecision(),(double) value); AppendString2Text(result); } continue; } if (LocaleNCompare("pixel:",pattern,6) == 0) { FxInfo *fx_info; double value; MagickStatusType status; PixelInfo pixel; /* Pixel - color value calculator. */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } GetPixelInfo(image,&pixel); fx_info=AcquireFxInfo(image,pattern+6,exception); status=FxEvaluateChannelExpression(fx_info,RedPixelChannel,0,0, &value,exception); pixel.red=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,GreenPixelChannel,0,0, &value,exception); pixel.green=(double) QuantumRange*value; status&=FxEvaluateChannelExpression(fx_info,BluePixelChannel,0,0, &value,exception); pixel.blue=(double) QuantumRange*value; if (image->colorspace == CMYKColorspace) { status&=FxEvaluateChannelExpression(fx_info,BlackPixelChannel,0,0, &value,exception); pixel.black=(double) QuantumRange*value; } status&=FxEvaluateChannelExpression(fx_info,AlphaPixelChannel,0,0, &value,exception); pixel.alpha=(double) QuantumRange*value; fx_info=DestroyFxInfo(fx_info); if (status != MagickFalse) { char name[MagickPathExtent]; (void) QueryColorname(image,&pixel,SVGCompliance,name, exception); AppendString2Text(name); } continue; } if (LocaleNCompare("option:",pattern,7) == 0) { /* Option - direct global option lookup (with globbing). */ if (image_info == (ImageInfo *) NULL ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+7) != MagickFalse) { ResetImageOptionIterator(image_info); while ((key=GetNextImageOption(image_info)) != (const char *) NULL) if (GlobExpression(key,pattern+7,MagickTrue) != MagickFalse) { string=GetImageOption(image_info,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageOption(image_info,pattern+7); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("artifact:",pattern,9) == 0) { /* Artifact - direct image artifact lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImageArtifactIterator(image); while ((key=GetNextImageArtifact(image)) != (const char *) NULL) if (GlobExpression(key,pattern+9,MagickTrue) != MagickFalse) { string=GetImageArtifact(image,key); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? key found but no string value! */ } continue; } string=GetImageArtifact(image,pattern+9); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (LocaleNCompare("property:",pattern,9) == 0) { /* Property - direct image property lookup (with glob). */ if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"NoImageForProperty","\"%%[%s]\"",pattern); continue; /* else no image to retrieve artifact */ } if (IsGlob(pattern+9) != MagickFalse) { ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } string=GetImageProperty(image,pattern+9,exception); if (string == (char *) NULL) goto PropertyLookupFailure; /* no artifact of this specifc name */ AppendString2Text(string); continue; } if (image != (Image *) NULL) { /* Properties without special prefix. This handles attributes, properties, and profiles such as %[exif:...]. Note the profile properties may also include a glob expansion pattern. */ string=GetImageProperty(image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); if (image != (Image *) NULL) (void)DeleteImageArtifact(image,"get-property"); if (image_info != (ImageInfo *) NULL) (void)DeleteImageOption(image_info,"get-property"); continue; } } if (IsGlob(pattern) != MagickFalse) { /* Handle property 'glob' patterns such as: %[*] %[user:array_??] %[filename:e*]> */ if (image == (Image *) NULL) continue; /* else no image to retrieve proprty - no list */ ResetImagePropertyIterator(image); while ((key=GetNextImageProperty(image)) != (const char *) NULL) if (GlobExpression(key,pattern,MagickTrue) != MagickFalse) { string=GetImageProperty(image,key,exception); if (string != (const char *) NULL) AppendKeyValue2Text(key,string); /* else - assertion failure? */ } continue; } /* Look for a known property or image attribute such as %[basename] %[denisty] %[delay]. Also handles a braced single letter: %[b] %[G] %[g]. */ string=GetMagickProperty(image_info,image,pattern,exception); if (string != (const char *) NULL) { AppendString2Text(string); continue; } /* Look for a per-image artifact. This includes option lookup (FUTURE: interpreted according to image). */ if (image != (Image *) NULL) { string=GetImageArtifact(image,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } else if (image_info != (ImageInfo *) NULL) { /* No image, so direct 'option' lookup (no delayed percent escapes). */ string=GetImageOption(image_info,pattern); if (string != (char *) NULL) { AppendString2Text(string); continue; } } PropertyLookupFailure: /* Failed to find any match anywhere! */ if (len >= 64) { pattern[61] = '.'; /* truncate string for error message */ pattern[62] = '.'; pattern[63] = '.'; pattern[64] = '\0'; } (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "UnknownImageProperty","\"%%[%s]\"",pattern); } } *q='\0'; return(interpret_text); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProperty() removes a property from the image and returns its % value. % % In this case the ConstantString() value returned should be freed by the % caller when finished. % % The format of the RemoveImageProperty method is: % % char *RemoveImageProperty(Image *image,const char *property) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % */ MagickExport char *RemoveImageProperty(Image *image, const char *property) { char *value; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return((char *) NULL); value=(char *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->properties, property); return(value); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t I m a g e P r o p e r t y I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImagePropertyIterator() resets the image properties iterator. Use it % in conjunction with GetNextImageProperty() to iterate over all the values % associated with an image property. % % The format of the ResetImagePropertyIterator method is: % % ResetImagePropertyIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImagePropertyIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image->filename); if (image->properties == (void *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->properties); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o p e r t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProperty() saves the given string value either to specific known % attribute or to a freeform property string. % % Attempting to set a property that is normally calculated will produce % an exception. % % The format of the SetImageProperty method is: % % MagickBooleanType SetImageProperty(Image *image,const char *property, % const char *value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o property: the image property. % % o values: the image property values. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetImageProperty(Image *image, const char *property,const char *value,ExceptionInfo *exception) { MagickBooleanType status; MagickStatusType flags; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->properties == (void *) NULL) image->properties=NewSplayTree(CompareSplayTreeString, RelinquishMagickMemory,RelinquishMagickMemory); /* create splay-tree */ if (value == (const char *) NULL) return(DeleteImageProperty(image,property)); /* delete if NULL */ status=MagickTrue; if (strlen(property) <= 1) { /* Do not 'set' single letter properties - read only shorthand. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } /* FUTURE: binary chars or quotes in key should produce a error */ /* Set attributes with known names or special prefixes return result is found, or break to set a free form properity */ switch (*property) { #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case '8': { if (LocaleNCompare("8bim:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; } #endif case 'B': case 'b': { if (LocaleCompare("background",property) == 0) { (void) QueryColorCompliance(value,AllCompliance, &image->background_color,exception); /* check for FUTURE: value exception?? */ /* also add user input to splay tree */ } break; /* not an attribute, add as a property */ } case 'C': case 'c': { if (LocaleCompare("channels",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("colorspace",property) == 0) { ssize_t colorspace; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse, value); if (colorspace < 0) return(MagickFalse); /* FUTURE: value exception?? */ return(SetImageColorspace(image,(ColorspaceType) colorspace,exception)); } if (LocaleCompare("compose",property) == 0) { ssize_t compose; compose=ParseCommandOption(MagickComposeOptions,MagickFalse,value); if (compose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compose=(CompositeOperator) compose; return(MagickTrue); } if (LocaleCompare("compress",property) == 0) { ssize_t compression; compression=ParseCommandOption(MagickCompressOptions,MagickFalse, value); if (compression < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->compression=(CompressionType) compression; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'D': case 'd': { if (LocaleCompare("delay",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); if ((flags & GreaterValue) != 0) { if (image->delay > (size_t) floor(geometry_info.rho+0.5)) image->delay=(size_t) floor(geometry_info.rho+0.5); } else if ((flags & LessValue) != 0) { if (image->delay < (size_t) floor(geometry_info.rho+0.5)) image->delay=(ssize_t) floor(geometry_info.sigma+0.5); } else image->delay=(size_t) floor(geometry_info.rho+0.5); if ((flags & SigmaValue) != 0) image->ticks_per_second=(ssize_t) floor(geometry_info.sigma+0.5); return(MagickTrue); } if (LocaleCompare("delay_units",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } if (LocaleCompare("density",property) == 0) { GeometryInfo geometry_info; flags=ParseGeometry(value,&geometry_info); image->resolution.x=geometry_info.rho; image->resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->resolution.y=image->resolution.x; return(MagickTrue); } if (LocaleCompare("depth",property) == 0) { image->depth=StringToUnsignedLong(value); return(MagickTrue); } if (LocaleCompare("dispose",property) == 0) { ssize_t dispose; dispose=ParseCommandOption(MagickDisposeOptions,MagickFalse,value); if (dispose < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->dispose=(DisposeType) dispose; return(MagickTrue); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'E': case 'e': { if (LocaleNCompare("exif:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'F': case 'f': { if (LocaleNCompare("fx:",property,3) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif case 'G': case 'g': { if (LocaleCompare("gamma",property) == 0) { image->gamma=StringToDouble(value,(char **) NULL); return(MagickTrue); } if (LocaleCompare("gravity",property) == 0) { ssize_t gravity; gravity=ParseCommandOption(MagickGravityOptions,MagickFalse,value); if (gravity < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->gravity=(GravityType) gravity; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'H': case 'h': { if (LocaleCompare("height",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'I': case 'i': { if (LocaleCompare("intensity",property) == 0) { ssize_t intensity; intensity=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (intensity < 0) return(MagickFalse); image->intensity=(PixelIntensityMethod) intensity; return(MagickTrue); } if (LocaleCompare("intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } if (LocaleCompare("interpolate",property) == 0) { ssize_t interpolate; interpolate=ParseCommandOption(MagickInterpolateOptions,MagickFalse, value); if (interpolate < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->interpolate=(PixelInterpolateMethod) interpolate; return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("iptc:",property,5) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif break; /* not an attribute, add as a property */ } case 'K': case 'k': if (LocaleCompare("kurtosis",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'L': case 'l': { if (LocaleCompare("loop",property) == 0) { image->iterations=StringToUnsignedLong(value); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'M': case 'm': if ( (LocaleCompare("magick",property) == 0) || (LocaleCompare("max",property) == 0) || (LocaleCompare("mean",property) == 0) || (LocaleCompare("min",property) == 0) || (LocaleCompare("min",property) == 0) ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'O': case 'o': if (LocaleCompare("opaque",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'P': case 'p': { if (LocaleCompare("page",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->page); geometry=DestroyString(geometry); return(MagickTrue); } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ if (LocaleNCompare("pixel:",property,6) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } #endif if (LocaleCompare("profile",property) == 0) { ImageInfo *image_info; StringInfo *profile; image_info=AcquireImageInfo(); (void) CopyMagickString(image_info->filename,value,MagickPathExtent); (void) SetImageInfo(image_info,1,exception); profile=FileToStringInfo(image_info->filename,~0UL,exception); if (profile != (StringInfo *) NULL) status=SetImageProfile(image,image_info->magick,profile,exception); image_info=DestroyImageInfo(image_info); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'R': case 'r': { if (LocaleCompare("rendering-intent",property) == 0) { ssize_t rendering_intent; rendering_intent=ParseCommandOption(MagickIntentOptions,MagickFalse, value); if (rendering_intent < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->rendering_intent=(RenderingIntent) rendering_intent; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'S': case 's': if ( (LocaleCompare("size",property) == 0) || (LocaleCompare("skewness",property) == 0) || (LocaleCompare("scenes",property) == 0) || (LocaleCompare("standard-deviation",property) == 0) ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ case 'T': case 't': { if (LocaleCompare("tile-offset",property) == 0) { char *geometry; geometry=GetPageGeometry(value); flags=ParseAbsoluteGeometry(geometry,&image->tile_offset); geometry=DestroyString(geometry); return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'U': case 'u': { if (LocaleCompare("units",property) == 0) { ssize_t units; units=ParseCommandOption(MagickResolutionOptions,MagickFalse,value); if (units < 0) return(MagickFalse); /* FUTURE: value exception?? */ image->units=(ResolutionType) units; return(MagickTrue); } break; /* not an attribute, add as a property */ } case 'V': case 'v': { if (LocaleCompare("version",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } case 'W': case 'w': { if (LocaleCompare("width",property) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #if 0 /* Percent escape's sets values with this prefix: for later use Throwing an exception causes this setting to fail */ case 'X': case 'x': { if (LocaleNCompare("xmp:",property,4) == 0) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"SetReadOnlyProperty","`%s'",property); return(MagickFalse); } break; /* not an attribute, add as a property */ } #endif } /* Default: not an attribute, add as a property */ status=AddValueToSplayTree((SplayTreeInfo *) image->properties, ConstantString(property),ConstantString(value)); /* FUTURE: error if status is bad? */ return(status); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_5177_1
crossvul-cpp_data_bad_3178_1
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef AMIGA # include <time.h> /* for time() */ #endif /* * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred) * It has been changed beyond recognition since then. * * Differences between version 7.4 and 8.x can be found with ":help version8". * Differences between version 6.4 and 7.x can be found with ":help version7". * Differences between version 5.8 and 6.x can be found with ":help version6". * Differences between version 4.x and 5.x can be found with ":help version5". * Differences between version 3.0 and 4.x can be found with ":help version4". * All the remarks about older versions have been removed, they are not very * interesting. */ #include "version.h" char *Version = VIM_VERSION_SHORT; static char *mediumVersion = VIM_VERSION_MEDIUM; #if defined(HAVE_DATE_TIME) || defined(PROTO) # if (defined(VMS) && defined(VAXC)) || defined(PROTO) char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__) + sizeof(__TIME__) + 3]; void make_version(void) { /* * Construct the long version string. Necessary because * VAX C can't catenate strings in the preprocessor. */ strcpy(longVersion, VIM_VERSION_LONG_DATE); strcat(longVersion, __DATE__); strcat(longVersion, " "); strcat(longVersion, __TIME__); strcat(longVersion, ")"); } # else char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")"; # endif #else char *longVersion = VIM_VERSION_LONG; #endif static void list_features(void); static void version_msg(char *s); static char *(features[]) = { #ifdef HAVE_ACL "+acl", #else "-acl", #endif #ifdef AMIGA /* only for Amiga systems */ # ifdef FEAT_ARP "+ARP", # else "-ARP", # endif #endif #ifdef FEAT_ARABIC "+arabic", #else "-arabic", #endif #ifdef FEAT_AUTOCMD "+autocmd", #else "-autocmd", #endif #ifdef FEAT_BEVAL "+balloon_eval", #else "-balloon_eval", #endif #ifdef FEAT_BROWSE "+browse", #else "-browse", #endif #ifdef NO_BUILTIN_TCAPS "-builtin_terms", #endif #ifdef SOME_BUILTIN_TCAPS "+builtin_terms", #endif #ifdef ALL_BUILTIN_TCAPS "++builtin_terms", #endif #ifdef FEAT_BYTEOFF "+byte_offset", #else "-byte_offset", #endif #ifdef FEAT_JOB_CHANNEL "+channel", #else "-channel", #endif #ifdef FEAT_CINDENT "+cindent", #else "-cindent", #endif #ifdef FEAT_CLIENTSERVER "+clientserver", #else "-clientserver", #endif #ifdef FEAT_CLIPBOARD "+clipboard", #else "-clipboard", #endif #ifdef FEAT_CMDL_COMPL "+cmdline_compl", #else "-cmdline_compl", #endif #ifdef FEAT_CMDHIST "+cmdline_hist", #else "-cmdline_hist", #endif #ifdef FEAT_CMDL_INFO "+cmdline_info", #else "-cmdline_info", #endif #ifdef FEAT_COMMENTS "+comments", #else "-comments", #endif #ifdef FEAT_CONCEAL "+conceal", #else "-conceal", #endif #ifdef FEAT_CRYPT "+cryptv", #else "-cryptv", #endif #ifdef FEAT_CSCOPE "+cscope", #else "-cscope", #endif #ifdef FEAT_CURSORBIND "+cursorbind", #else "-cursorbind", #endif #ifdef CURSOR_SHAPE "+cursorshape", #else "-cursorshape", #endif #if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG) "+dialog_con_gui", #else # if defined(FEAT_CON_DIALOG) "+dialog_con", # else # if defined(FEAT_GUI_DIALOG) "+dialog_gui", # else "-dialog", # endif # endif #endif #ifdef FEAT_DIFF "+diff", #else "-diff", #endif #ifdef FEAT_DIGRAPHS "+digraphs", #else "-digraphs", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_DIRECTX "+directx", # else "-directx", # endif #endif #ifdef FEAT_DND "+dnd", #else "-dnd", #endif #ifdef EBCDIC "+ebcdic", #else "-ebcdic", #endif #ifdef FEAT_EMACS_TAGS "+emacs_tags", #else "-emacs_tags", #endif #ifdef FEAT_EVAL "+eval", #else "-eval", #endif "+ex_extra", #ifdef FEAT_SEARCH_EXTRA "+extra_search", #else "-extra_search", #endif #ifdef FEAT_FKMAP "+farsi", #else "-farsi", #endif #ifdef FEAT_SEARCHPATH "+file_in_path", #else "-file_in_path", #endif #ifdef FEAT_FIND_ID "+find_in_path", #else "-find_in_path", #endif #ifdef FEAT_FLOAT "+float", #else "-float", #endif #ifdef FEAT_FOLDING "+folding", #else "-folding", #endif #ifdef FEAT_FOOTER "+footer", #else "-footer", #endif /* only interesting on Unix systems */ #if !defined(USE_SYSTEM) && defined(UNIX) "+fork()", #endif #ifdef FEAT_GETTEXT # ifdef DYNAMIC_GETTEXT "+gettext/dyn", # else "+gettext", # endif #else "-gettext", #endif #ifdef FEAT_HANGULIN "+hangul_input", #else "-hangul_input", #endif #if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV) # ifdef DYNAMIC_ICONV "+iconv/dyn", # else "+iconv", # endif #else "-iconv", #endif #ifdef FEAT_INS_EXPAND "+insert_expand", #else "-insert_expand", #endif #ifdef FEAT_JOB_CHANNEL "+job", #else "-job", #endif #ifdef FEAT_JUMPLIST "+jumplist", #else "-jumplist", #endif #ifdef FEAT_KEYMAP "+keymap", #else "-keymap", #endif #ifdef FEAT_EVAL "+lambda", #else "-lambda", #endif #ifdef FEAT_LANGMAP "+langmap", #else "-langmap", #endif #ifdef FEAT_LIBCALL "+libcall", #else "-libcall", #endif #ifdef FEAT_LINEBREAK "+linebreak", #else "-linebreak", #endif #ifdef FEAT_LISP "+lispindent", #else "-lispindent", #endif #ifdef FEAT_LISTCMDS "+listcmds", #else "-listcmds", #endif #ifdef FEAT_LOCALMAP "+localmap", #else "-localmap", #endif #ifdef FEAT_LUA # ifdef DYNAMIC_LUA "+lua/dyn", # else "+lua", # endif #else "-lua", #endif #ifdef FEAT_MENU "+menu", #else "-menu", #endif #ifdef FEAT_SESSION "+mksession", #else "-mksession", #endif #ifdef FEAT_MODIFY_FNAME "+modify_fname", #else "-modify_fname", #endif #ifdef FEAT_MOUSE "+mouse", # ifdef FEAT_MOUSESHAPE "+mouseshape", # else "-mouseshape", # endif # else "-mouse", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "+mouse_dec", # else "-mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "+mouse_gpm", # else "-mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "+mouse_jsbterm", # else "-mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "+mouse_netterm", # else "-mouse_netterm", # endif #endif #ifdef __QNX__ # ifdef FEAT_MOUSE_PTERM "+mouse_pterm", # else "-mouse_pterm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_SGR "+mouse_sgr", # else "-mouse_sgr", # endif # ifdef FEAT_SYSMOUSE "+mouse_sysmouse", # else "-mouse_sysmouse", # endif # ifdef FEAT_MOUSE_URXVT "+mouse_urxvt", # else "-mouse_urxvt", # endif # ifdef FEAT_MOUSE_XTERM "+mouse_xterm", # else "-mouse_xterm", # endif #endif #ifdef FEAT_MBYTE_IME # ifdef DYNAMIC_IME "+multi_byte_ime/dyn", # else "+multi_byte_ime", # endif #else # ifdef FEAT_MBYTE "+multi_byte", # else "-multi_byte", # endif #endif #ifdef FEAT_MULTI_LANG "+multi_lang", #else "-multi_lang", #endif #ifdef FEAT_MZSCHEME # ifdef DYNAMIC_MZSCHEME "+mzscheme/dyn", # else "+mzscheme", # endif #else "-mzscheme", #endif #ifdef FEAT_NETBEANS_INTG "+netbeans_intg", #else "-netbeans_intg", #endif #ifdef FEAT_NUM64 "+num64", #else "-num64", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_OLE "+ole", # else "-ole", # endif #endif "+packages", #ifdef FEAT_PATH_EXTRA "+path_extra", #else "-path_extra", #endif #ifdef FEAT_PERL # ifdef DYNAMIC_PERL "+perl/dyn", # else "+perl", # endif #else "-perl", #endif #ifdef FEAT_PERSISTENT_UNDO "+persistent_undo", #else "-persistent_undo", #endif #ifdef FEAT_PRINTER # ifdef FEAT_POSTSCRIPT "+postscript", # else "-postscript", # endif "+printer", #else "-printer", #endif #ifdef FEAT_PROFILE "+profile", #else "-profile", #endif #ifdef FEAT_PYTHON # ifdef DYNAMIC_PYTHON "+python/dyn", # else "+python", # endif #else "-python", #endif #ifdef FEAT_PYTHON3 # ifdef DYNAMIC_PYTHON3 "+python3/dyn", # else "+python3", # endif #else "-python3", #endif #ifdef FEAT_QUICKFIX "+quickfix", #else "-quickfix", #endif #ifdef FEAT_RELTIME "+reltime", #else "-reltime", #endif #ifdef FEAT_RIGHTLEFT "+rightleft", #else "-rightleft", #endif #ifdef FEAT_RUBY # ifdef DYNAMIC_RUBY "+ruby/dyn", # else "+ruby", # endif #else "-ruby", #endif #ifdef FEAT_SCROLLBIND "+scrollbind", #else "-scrollbind", #endif #ifdef FEAT_SIGNS "+signs", #else "-signs", #endif #ifdef FEAT_SMARTINDENT "+smartindent", #else "-smartindent", #endif #ifdef STARTUPTIME "+startuptime", #else "-startuptime", #endif #ifdef FEAT_STL_OPT "+statusline", #else "-statusline", #endif #ifdef FEAT_SUN_WORKSHOP "+sun_workshop", #else "-sun_workshop", #endif #ifdef FEAT_SYN_HL "+syntax", #else "-syntax", #endif /* only interesting on Unix systems */ #if defined(USE_SYSTEM) && defined(UNIX) "+system()", #endif #ifdef FEAT_TAG_BINS "+tag_binary", #else "-tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "+tag_old_static", #else "-tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "+tag_any_white", #else "-tag_any_white", #endif #ifdef FEAT_TCL # ifdef DYNAMIC_TCL "+tcl/dyn", # else "+tcl", # endif #else "-tcl", #endif #ifdef FEAT_TERMGUICOLORS "+termguicolors", #else "-termguicolors", #endif #if defined(UNIX) /* only Unix can have terminfo instead of termcap */ # ifdef TERMINFO "+terminfo", # else "-terminfo", # endif #else /* unix always includes termcap support */ # ifdef HAVE_TGETENT "+tgetent", # else "-tgetent", # endif #endif #ifdef FEAT_TERMRESPONSE "+termresponse", #else "-termresponse", #endif #ifdef FEAT_TEXTOBJ "+textobjects", #else "-textobjects", #endif #ifdef FEAT_TIMERS "+timers", #else "-timers", #endif #ifdef FEAT_TITLE "+title", #else "-title", #endif #ifdef FEAT_TOOLBAR "+toolbar", #else "-toolbar", #endif #ifdef FEAT_USR_CMDS "+user_commands", #else "-user_commands", #endif #ifdef FEAT_WINDOWS "+vertsplit", #else "-vertsplit", #endif #ifdef FEAT_VIRTUALEDIT "+virtualedit", #else "-virtualedit", #endif "+visual", #ifdef FEAT_VISUALEXTRA "+visualextra", #else "-visualextra", #endif #ifdef FEAT_VIMINFO "+viminfo", #else "-viminfo", #endif #ifdef FEAT_VREPLACE "+vreplace", #else "-vreplace", #endif #ifdef FEAT_WILDIGN "+wildignore", #else "-wildignore", #endif #ifdef FEAT_WILDMENU "+wildmenu", #else "-wildmenu", #endif #ifdef FEAT_WINDOWS "+windows", #else "-windows", #endif #ifdef FEAT_WRITEBACKUP "+writebackup", #else "-writebackup", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_X11 "+X11", # else "-X11", # endif #endif #ifdef FEAT_XFONTSET "+xfontset", #else "-xfontset", #endif #ifdef FEAT_XIM "+xim", #else "-xim", #endif #ifdef WIN3264 # ifdef FEAT_XPM_W32 "+xpm_w32", # else "-xpm_w32", # endif #else # ifdef HAVE_XPM "+xpm", # else "-xpm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef USE_XSMP_INTERACT "+xsmp_interact", # else # ifdef USE_XSMP "+xsmp", # else "-xsmp", # endif # endif # ifdef FEAT_XCLIPBOARD "+xterm_clipboard", # else "-xterm_clipboard", # endif #endif #ifdef FEAT_XTERM_SAVE "+xterm_save", #else "-xterm_save", #endif NULL }; static int included_patches[] = { /* Add new patch number below this line */ /**/ 376, /**/ 375, /**/ 374, /**/ 373, /**/ 372, /**/ 371, /**/ 370, /**/ 369, /**/ 368, /**/ 367, /**/ 366, /**/ 365, /**/ 364, /**/ 363, /**/ 362, /**/ 361, /**/ 360, /**/ 359, /**/ 358, /**/ 357, /**/ 356, /**/ 355, /**/ 354, /**/ 353, /**/ 352, /**/ 351, /**/ 350, /**/ 349, /**/ 348, /**/ 347, /**/ 346, /**/ 345, /**/ 344, /**/ 343, /**/ 342, /**/ 341, /**/ 340, /**/ 339, /**/ 338, /**/ 337, /**/ 336, /**/ 335, /**/ 334, /**/ 333, /**/ 332, /**/ 331, /**/ 330, /**/ 329, /**/ 328, /**/ 327, /**/ 326, /**/ 325, /**/ 324, /**/ 323, /**/ 322, /**/ 321, /**/ 320, /**/ 319, /**/ 318, /**/ 317, /**/ 316, /**/ 315, /**/ 314, /**/ 313, /**/ 312, /**/ 311, /**/ 310, /**/ 309, /**/ 308, /**/ 307, /**/ 306, /**/ 305, /**/ 304, /**/ 303, /**/ 302, /**/ 301, /**/ 300, /**/ 299, /**/ 298, /**/ 297, /**/ 296, /**/ 295, /**/ 294, /**/ 293, /**/ 292, /**/ 291, /**/ 290, /**/ 289, /**/ 288, /**/ 287, /**/ 286, /**/ 285, /**/ 284, /**/ 283, /**/ 282, /**/ 281, /**/ 280, /**/ 279, /**/ 278, /**/ 277, /**/ 276, /**/ 275, /**/ 274, /**/ 273, /**/ 272, /**/ 271, /**/ 270, /**/ 269, /**/ 268, /**/ 267, /**/ 266, /**/ 265, /**/ 264, /**/ 263, /**/ 262, /**/ 261, /**/ 260, /**/ 259, /**/ 258, /**/ 257, /**/ 256, /**/ 255, /**/ 254, /**/ 253, /**/ 252, /**/ 251, /**/ 250, /**/ 249, /**/ 248, /**/ 247, /**/ 246, /**/ 245, /**/ 244, /**/ 243, /**/ 242, /**/ 241, /**/ 240, /**/ 239, /**/ 238, /**/ 237, /**/ 236, /**/ 235, /**/ 234, /**/ 233, /**/ 232, /**/ 231, /**/ 230, /**/ 229, /**/ 228, /**/ 227, /**/ 226, /**/ 225, /**/ 224, /**/ 223, /**/ 222, /**/ 221, /**/ 220, /**/ 219, /**/ 218, /**/ 217, /**/ 216, /**/ 215, /**/ 214, /**/ 213, /**/ 212, /**/ 211, /**/ 210, /**/ 209, /**/ 208, /**/ 207, /**/ 206, /**/ 205, /**/ 204, /**/ 203, /**/ 202, /**/ 201, /**/ 200, /**/ 199, /**/ 198, /**/ 197, /**/ 196, /**/ 195, /**/ 194, /**/ 193, /**/ 192, /**/ 191, /**/ 190, /**/ 189, /**/ 188, /**/ 187, /**/ 186, /**/ 185, /**/ 184, /**/ 183, /**/ 182, /**/ 181, /**/ 180, /**/ 179, /**/ 178, /**/ 177, /**/ 176, /**/ 175, /**/ 174, /**/ 173, /**/ 172, /**/ 171, /**/ 170, /**/ 169, /**/ 168, /**/ 167, /**/ 166, /**/ 165, /**/ 164, /**/ 163, /**/ 162, /**/ 161, /**/ 160, /**/ 159, /**/ 158, /**/ 157, /**/ 156, /**/ 155, /**/ 154, /**/ 153, /**/ 152, /**/ 151, /**/ 150, /**/ 149, /**/ 148, /**/ 147, /**/ 146, /**/ 145, /**/ 144, /**/ 143, /**/ 142, /**/ 141, /**/ 140, /**/ 139, /**/ 138, /**/ 137, /**/ 136, /**/ 135, /**/ 134, /**/ 133, /**/ 132, /**/ 131, /**/ 130, /**/ 129, /**/ 128, /**/ 127, /**/ 126, /**/ 125, /**/ 124, /**/ 123, /**/ 122, /**/ 121, /**/ 120, /**/ 119, /**/ 118, /**/ 117, /**/ 116, /**/ 115, /**/ 114, /**/ 113, /**/ 112, /**/ 111, /**/ 110, /**/ 109, /**/ 108, /**/ 107, /**/ 106, /**/ 105, /**/ 104, /**/ 103, /**/ 102, /**/ 101, /**/ 100, /**/ 99, /**/ 98, /**/ 97, /**/ 96, /**/ 95, /**/ 94, /**/ 93, /**/ 92, /**/ 91, /**/ 90, /**/ 89, /**/ 88, /**/ 87, /**/ 86, /**/ 85, /**/ 84, /**/ 83, /**/ 82, /**/ 81, /**/ 80, /**/ 79, /**/ 78, /**/ 77, /**/ 76, /**/ 75, /**/ 74, /**/ 73, /**/ 72, /**/ 71, /**/ 70, /**/ 69, /**/ 68, /**/ 67, /**/ 66, /**/ 65, /**/ 64, /**/ 63, /**/ 62, /**/ 61, /**/ 60, /**/ 59, /**/ 58, /**/ 57, /**/ 56, /**/ 55, /**/ 54, /**/ 53, /**/ 52, /**/ 51, /**/ 50, /**/ 49, /**/ 48, /**/ 47, /**/ 46, /**/ 45, /**/ 44, /**/ 43, /**/ 42, /**/ 41, /**/ 40, /**/ 39, /**/ 38, /**/ 37, /**/ 36, /**/ 35, /**/ 34, /**/ 33, /**/ 32, /**/ 31, /**/ 30, /**/ 29, /**/ 28, /**/ 27, /**/ 26, /**/ 25, /**/ 24, /**/ 23, /**/ 22, /**/ 21, /**/ 20, /**/ 19, /**/ 18, /**/ 17, /**/ 16, /**/ 15, /**/ 14, /**/ 13, /**/ 12, /**/ 11, /**/ 10, /**/ 9, /**/ 8, /**/ 7, /**/ 6, /**/ 5, /**/ 4, /**/ 3, /**/ 2, /**/ 1, /**/ 0 }; /* * Place to put a short description when adding a feature with a patch. * Keep it short, e.g.,: "relative numbers", "persistent undo". * Also add a comment marker to separate the lines. * See the official Vim patches for the diff format: It must use a context of * one line only. Create it by hand or use "diff -C2" and edit the patch. */ static char *(extra_patches[]) = { /* Add your patch description below this line */ /**/ NULL }; int highest_patch(void) { int i; int h = 0; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] > h) h = included_patches[i]; return h; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if patch "n" has been included. */ int has_patch(int n) { int i; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] == n) return TRUE; return FALSE; } #endif void ex_version(exarg_T *eap) { /* * Ignore a ":version 9.99" command. */ if (*eap->arg == NUL) { msg_putchar('\n'); list_version(); } } /* * List all features aligned in columns, dictionary style. */ static void list_features(void) { int i; int ncol; int nrow; int nfeat = 0; int width = 0; /* Find the length of the longest feature name, use that + 1 as the column * width */ for (i = 0; features[i] != NULL; ++i) { int l = (int)STRLEN(features[i]); if (l > width) width = l; ++nfeat; } width += 1; if (Columns < width) { /* Not enough screen columns - show one per line */ for (i = 0; features[i] != NULL; ++i) { version_msg(features[i]); if (msg_col > 0) msg_putchar('\n'); } return; } /* The rightmost column doesn't need a separator. * Sacrifice it to fit in one more column if possible. */ ncol = (int) (Columns + 1) / width; nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0); /* i counts columns then rows. idx counts rows then columns. */ for (i = 0; !got_int && i < nrow * ncol; ++i) { int idx = (i / ncol) + (i % ncol) * nrow; if (idx < nfeat) { int last_col = (i + 1) % ncol == 0; msg_puts((char_u *)features[idx]); if (last_col) { if (msg_col > 0) msg_putchar('\n'); } else { while (msg_col % width) msg_putchar(' '); } } else { if (msg_col > 0) msg_putchar('\n'); } } } void list_version(void) { int i; int first; char *s = ""; /* * When adding features here, don't forget to update the list of * internal variables in eval.c! */ MSG(longVersion); #ifdef WIN3264 # ifdef FEAT_GUI_W32 # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit GUI version")); # else MSG_PUTS(_("\nMS-Windows 32-bit GUI version")); # endif # ifdef FEAT_OLE MSG_PUTS(_(" with OLE support")); # endif # else # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit console version")); # else MSG_PUTS(_("\nMS-Windows 32-bit console version")); # endif # endif #endif #ifdef MACOS # ifdef MACOS_X # ifdef MACOS_X_UNIX MSG_PUTS(_("\nMacOS X (unix) version")); # else MSG_PUTS(_("\nMacOS X version")); # endif #else MSG_PUTS(_("\nMacOS version")); # endif #endif #ifdef VMS MSG_PUTS(_("\nOpenVMS version")); # ifdef HAVE_PATHDEF if (*compiled_arch != NUL) { MSG_PUTS(" - "); MSG_PUTS(compiled_arch); } # endif #endif /* Print the list of patch numbers if there is at least one. */ /* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */ if (included_patches[0] != 0) { MSG_PUTS(_("\nIncluded patches: ")); first = -1; /* find last one */ for (i = 0; included_patches[i] != 0; ++i) ; while (--i >= 0) { if (first < 0) first = included_patches[i]; if (i == 0 || included_patches[i - 1] != included_patches[i] + 1) { MSG_PUTS(s); s = ", "; msg_outnum((long)first); if (first != included_patches[i]) { MSG_PUTS("-"); msg_outnum((long)included_patches[i]); } first = -1; } } } /* Print the list of extra patch descriptions if there is at least one. */ if (extra_patches[0] != NULL) { MSG_PUTS(_("\nExtra patches: ")); s = ""; for (i = 0; extra_patches[i] != NULL; ++i) { MSG_PUTS(s); s = ", "; MSG_PUTS(extra_patches[i]); } } #ifdef MODIFIED_BY MSG_PUTS("\n"); MSG_PUTS(_("Modified by ")); MSG_PUTS(MODIFIED_BY); #endif #ifdef HAVE_PATHDEF if (*compiled_user != NUL || *compiled_sys != NUL) { MSG_PUTS(_("\nCompiled ")); if (*compiled_user != NUL) { MSG_PUTS(_("by ")); MSG_PUTS(compiled_user); } if (*compiled_sys != NUL) { MSG_PUTS("@"); MSG_PUTS(compiled_sys); } } #endif #ifdef FEAT_HUGE MSG_PUTS(_("\nHuge version ")); #else # ifdef FEAT_BIG MSG_PUTS(_("\nBig version ")); # else # ifdef FEAT_NORMAL MSG_PUTS(_("\nNormal version ")); # else # ifdef FEAT_SMALL MSG_PUTS(_("\nSmall version ")); # else MSG_PUTS(_("\nTiny version ")); # endif # endif # endif #endif #ifndef FEAT_GUI MSG_PUTS(_("without GUI.")); #else # ifdef FEAT_GUI_GTK # ifdef USE_GTK3 MSG_PUTS(_("with GTK3 GUI.")); # else # ifdef FEAT_GUI_GNOME MSG_PUTS(_("with GTK2-GNOME GUI.")); # else MSG_PUTS(_("with GTK2 GUI.")); # endif # endif # else # ifdef FEAT_GUI_MOTIF MSG_PUTS(_("with X11-Motif GUI.")); # else # ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW MSG_PUTS(_("with X11-neXtaw GUI.")); # else MSG_PUTS(_("with X11-Athena GUI.")); # endif # else # ifdef FEAT_GUI_PHOTON MSG_PUTS(_("with Photon GUI.")); # else # if defined(MSWIN) MSG_PUTS(_("with GUI.")); # else # if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON MSG_PUTS(_("with Carbon GUI.")); # else # if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX MSG_PUTS(_("with Cocoa GUI.")); # else # if defined(MACOS) MSG_PUTS(_("with (classic) GUI.")); # endif # endif # endif # endif # endif # endif # endif # endif #endif version_msg(_(" Features included (+) or not (-):\n")); list_features(); #ifdef SYS_VIMRC_FILE version_msg(_(" system vimrc file: \"")); version_msg(SYS_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE version_msg(_(" user vimrc file: \"")); version_msg(USR_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE2 version_msg(_(" 2nd user vimrc file: \"")); version_msg(USR_VIMRC_FILE2); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE3 version_msg(_(" 3rd user vimrc file: \"")); version_msg(USR_VIMRC_FILE3); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE version_msg(_(" user exrc file: \"")); version_msg(USR_EXRC_FILE); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE2 version_msg(_(" 2nd user exrc file: \"")); version_msg(USR_EXRC_FILE2); version_msg("\"\n"); #endif #ifdef FEAT_GUI # ifdef SYS_GVIMRC_FILE version_msg(_(" system gvimrc file: \"")); version_msg(SYS_GVIMRC_FILE); version_msg("\"\n"); # endif version_msg(_(" user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE); version_msg("\"\n"); # ifdef USR_GVIMRC_FILE2 version_msg(_("2nd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE2); version_msg("\"\n"); # endif # ifdef USR_GVIMRC_FILE3 version_msg(_("3rd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE3); version_msg("\"\n"); # endif #endif version_msg(_(" defaults file: \"")); version_msg(VIM_DEFAULTS_FILE); version_msg("\"\n"); #ifdef FEAT_GUI # ifdef SYS_MENU_FILE version_msg(_(" system menu file: \"")); version_msg(SYS_MENU_FILE); version_msg("\"\n"); # endif #endif #ifdef HAVE_PATHDEF if (*default_vim_dir != NUL) { version_msg(_(" fall-back for $VIM: \"")); version_msg((char *)default_vim_dir); version_msg("\"\n"); } if (*default_vimruntime_dir != NUL) { version_msg(_(" f-b for $VIMRUNTIME: \"")); version_msg((char *)default_vimruntime_dir); version_msg("\"\n"); } version_msg(_("Compilation: ")); version_msg((char *)all_cflags); version_msg("\n"); #ifdef VMS if (*compiler_version != NUL) { version_msg(_("Compiler: ")); version_msg((char *)compiler_version); version_msg("\n"); } #endif version_msg(_("Linking: ")); version_msg((char *)all_lflags); #endif #ifdef DEBUG version_msg("\n"); version_msg(_(" DEBUG BUILD")); #endif } /* * Output a string for the version message. If it's going to wrap, output a * newline, unless the message is too long to fit on the screen anyway. */ static void version_msg(char *s) { int len = (int)STRLEN(s); if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns && *s != '\n') msg_putchar('\n'); if (!got_int) MSG_PUTS(s); } static void do_intro_line(int row, char_u *mesg, int add_version, int attr); /* * Show the intro message when not editing a file. */ void maybe_intro_message(void) { if (bufempty() && curbuf->b_fname == NULL #ifdef FEAT_WINDOWS && firstwin->w_next == NULL #endif && vim_strchr(p_shm, SHM_INTRO) == NULL) intro_message(FALSE); } /* * Give an introductory message about Vim. * Only used when starting Vim on an empty file, without a file name. * Or with the ":intro" command (for Sven :-). */ void intro_message( int colon) /* TRUE for ":intro" */ { int i; int row; int blanklines; int sponsor; char *p; static char *(lines[]) = { N_("VIM - Vi IMproved"), "", N_("version "), N_("by Bram Moolenaar et al."), #ifdef MODIFIED_BY " ", #endif N_("Vim is open source and freely distributable"), "", N_("Help poor children in Uganda!"), N_("type :help iccf<Enter> for information "), "", N_("type :q<Enter> to exit "), N_("type :help<Enter> or <F1> for on-line help"), N_("type :help version8<Enter> for version info"), NULL, "", N_("Running in Vi compatible mode"), N_("type :set nocp<Enter> for Vim defaults"), N_("type :help cp-default<Enter> for info on this"), }; #ifdef FEAT_GUI static char *(gui_lines[]) = { NULL, NULL, NULL, NULL, #ifdef MODIFIED_BY NULL, #endif NULL, NULL, NULL, N_("menu Help->Orphans for information "), NULL, N_("Running modeless, typed text is inserted"), N_("menu Edit->Global Settings->Toggle Insert Mode "), N_(" for two modes "), NULL, NULL, NULL, N_("menu Edit->Global Settings->Toggle Vi Compatible"), N_(" for Vim defaults "), }; #endif /* blanklines = screen height - # message lines */ blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1); if (!p_cp) blanklines += 4; /* add 4 for not showing "Vi compatible" message */ #ifdef FEAT_WINDOWS /* Don't overwrite a statusline. Depends on 'cmdheight'. */ if (p_ls > 1) blanklines -= Rows - topframe->fr_height; #endif if (blanklines < 0) blanklines = 0; /* Show the sponsor and register message one out of four times, the Uganda * message two out of four times. */ sponsor = (int)time(NULL); sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0); /* start displaying the message lines after half of the blank lines */ row = blanklines / 2; if ((row >= 2 && Columns >= 50) || colon) { for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i) { p = lines[i]; #ifdef FEAT_GUI if (p_im && gui.in_use && gui_lines[i] != NULL) p = gui_lines[i]; #endif if (p == NULL) { if (!p_cp) break; continue; } if (sponsor != 0) { if (strstr(p, "children") != NULL) p = sponsor < 0 ? N_("Sponsor Vim development!") : N_("Become a registered Vim user!"); else if (strstr(p, "iccf") != NULL) p = sponsor < 0 ? N_("type :help sponsor<Enter> for information ") : N_("type :help register<Enter> for information "); else if (strstr(p, "Orphans") != NULL) p = N_("menu Help->Sponsor/Register for information "); } if (*p != NUL) do_intro_line(row, (char_u *)_(p), i == 2, 0); ++row; } } /* Make the wait-return message appear just below the text. */ if (colon) msg_row = row; } static void do_intro_line( int row, char_u *mesg, int add_version, int attr) { char_u vers[20]; int col; char_u *p; int l; int clen; #ifdef MODIFIED_BY # define MODBY_LEN 150 char_u modby[MODBY_LEN]; if (*mesg == ' ') { vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1); l = (int)STRLEN(modby); vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1); mesg = modby; } #endif /* Center the message horizontally. */ col = vim_strsize(mesg); if (add_version) { STRCPY(vers, mediumVersion); if (highest_patch()) { /* Check for 9.9x or 9.9xx, alpha/beta version */ if (isalpha((int)vers[3])) { int len = (isalpha((int)vers[4])) ? 5 : 4; sprintf((char *)vers + len, ".%d%s", highest_patch(), mediumVersion + len); } else sprintf((char *)vers + 3, ".%d", highest_patch()); } col += (int)STRLEN(vers); } col = (Columns - col) / 2; if (col < 0) col = 0; /* Split up in parts to highlight <> items differently. */ for (p = mesg; *p != NUL; p += l) { clen = 0; for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l) { #ifdef FEAT_MBYTE if (has_mbyte) { clen += ptr2cells(p + l); l += (*mb_ptr2len)(p + l) - 1; } else #endif clen += byte2cells(p[l]); } screen_puts_len(p, l, row, col, *p == '<' ? hl_attr(HLF_8) : attr); col += clen; } /* Add the version number to the version line. */ if (add_version) screen_puts(vers, row, col, 0); } /* * ":intro": clear screen, display intro screen and wait for return. */ void ex_intro(exarg_T *eap UNUSED) { screenclear(); intro_message(TRUE); wait_return(TRUE); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3178_1
crossvul-cpp_data_good_3171_0
/* * alloc.c -- Useful allocation function/defintions * * Copyright (C)1999-2006 Mark Simpson <damned@world.std.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you can either send email to this * program's maintainer or write to: The Free Software Foundation, * Inc.; 59 Temple Place, Suite 330; Boston, MA 02111-1307, USA. * */ #ifdef HAVE_CONFIG_H # include "config.h" #endif /* HAVE_CONFIG_H */ #include "common.h" #include "alloc.h" static size_t alloc_limit = 0; void set_alloc_limit (size_t size) { alloc_limit = size; } size_t get_alloc_limit() { return alloc_limit; } size_t check_mul_overflow(size_t a, size_t b, size_t* res) { size_t tmp = a * b; if (a != 0 && tmp / a != b) return 1; *res = tmp; return 0; } static void alloc_limit_failure (char *fn_name, size_t size) { fprintf (stderr, "%s: Maximum allocation size exceeded " "(maxsize = %lu; size = %lu).\n", fn_name, (unsigned long)alloc_limit, (unsigned long)size); } void alloc_limit_assert (char *fn_name, size_t size) { if (alloc_limit && size > alloc_limit) { alloc_limit_failure (fn_name, size); exit (-1); } } /* attempts to malloc memory, if fails print error and call abort */ void* xmalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); void *ptr = malloc (res); if (!ptr && (size != 0)) /* some libc don't like size == 0 */ { perror ("xmalloc: Memory allocation failure"); abort(); } return ptr; } /* Allocates memory but only up to a limit */ void* checked_xmalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xmalloc", res); return xmalloc (num, size); } /* xmallocs memory and clears it out */ void* xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); void *ptr; ptr = malloc(res); if (ptr) { memset (ptr, '\0', (res)); } return ptr; } /* xcallocs memory but only up to a limit */ void* checked_xcalloc (size_t num, size_t size) { size_t res; if (check_mul_overflow(num, size, &res)) abort(); alloc_limit_assert ("checked_xcalloc", (res)); return xcalloc (num, size); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_3171_0
crossvul-cpp_data_good_5262_0
/* +----------------------------------------------------------------------+ | Zend Engine | +----------------------------------------------------------------------+ | Copyright (c) 1998-2016 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@zend.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Andi Gutmans <andi@zend.com> | | Zeev Suraski <zeev@zend.com> | | Dmitry Stogov <dmitry@zend.com> | +----------------------------------------------------------------------+ */ /* $Id$ */ /* * zend_alloc is designed to be a modern CPU cache friendly memory manager * for PHP. Most ideas are taken from jemalloc and tcmalloc implementations. * * All allocations are split into 3 categories: * * Huge - the size is greater than CHUNK size (~2M by default), allocation is * performed using mmap(). The result is aligned on 2M boundary. * * Large - a number of 4096K pages inside a CHUNK. Large blocks * are always aligned on page boundary. * * Small - less than 3/4 of page size. Small sizes are rounded up to nearest * greater predefined small size (there are 30 predefined sizes: * 8, 16, 24, 32, ... 3072). Small blocks are allocated from * RUNs. Each RUN is allocated as a single or few following pages. * Allocation inside RUNs implemented using linked list of free * elements. The result is aligned to 8 bytes. * * zend_alloc allocates memory from OS by CHUNKs, these CHUNKs and huge memory * blocks are always aligned to CHUNK boundary. So it's very easy to determine * the CHUNK owning the certain pointer. Regular CHUNKs reserve a single * page at start for special purpose. It contains bitset of free pages, * few bitset for available runs of predefined small sizes, map of pages that * keeps information about usage of each page in this CHUNK, etc. * * zend_alloc provides familiar emalloc/efree/erealloc API, but in addition it * provides specialized and optimized routines to allocate blocks of predefined * sizes (e.g. emalloc_2(), emallc_4(), ..., emalloc_large(), etc) * The library uses C preprocessor tricks that substitute calls to emalloc() * with more specialized routines when the requested size is known. */ #include "zend.h" #include "zend_alloc.h" #include "zend_globals.h" #include "zend_operators.h" #include "zend_multiply.h" #ifdef HAVE_SIGNAL_H # include <signal.h> #endif #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #ifdef ZEND_WIN32 # include <wincrypt.h> # include <process.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #if HAVE_LIMITS_H #include <limits.h> #endif #include <fcntl.h> #include <errno.h> #ifndef _WIN32 # ifdef HAVE_MREMAP # ifndef _GNU_SOURCE # define _GNU_SOURCE # endif # ifndef __USE_GNU # define __USE_GNU # endif # endif # include <sys/mman.h> # ifndef MAP_ANON # ifdef MAP_ANONYMOUS # define MAP_ANON MAP_ANONYMOUS # endif # endif # ifndef MREMAP_MAYMOVE # define MREMAP_MAYMOVE 0 # endif # ifndef MAP_FAILED # define MAP_FAILED ((void*)-1) # endif # ifndef MAP_POPULATE # define MAP_POPULATE 0 # endif # if defined(_SC_PAGESIZE) || (_SC_PAGE_SIZE) # define REAL_PAGE_SIZE _real_page_size static size_t _real_page_size = ZEND_MM_PAGE_SIZE; # endif #endif #ifndef REAL_PAGE_SIZE # define REAL_PAGE_SIZE ZEND_MM_PAGE_SIZE #endif #ifndef ZEND_MM_STAT # define ZEND_MM_STAT 1 /* track current and peak memory usage */ #endif #ifndef ZEND_MM_LIMIT # define ZEND_MM_LIMIT 1 /* support for user-defined memory limit */ #endif #ifndef ZEND_MM_CUSTOM # define ZEND_MM_CUSTOM 1 /* support for custom memory allocator */ /* USE_ZEND_ALLOC=0 may switch to system malloc() */ #endif #ifndef ZEND_MM_STORAGE # define ZEND_MM_STORAGE 1 /* support for custom memory storage */ #endif #ifndef ZEND_MM_ERROR # define ZEND_MM_ERROR 1 /* report system errors */ #endif #ifndef ZEND_MM_CHECK # define ZEND_MM_CHECK(condition, message) do { \ if (UNEXPECTED(!(condition))) { \ zend_mm_panic(message); \ } \ } while (0) #endif typedef uint32_t zend_mm_page_info; /* 4-byte integer */ typedef zend_ulong zend_mm_bitset; /* 4-byte or 8-byte integer */ #define ZEND_MM_ALIGNED_OFFSET(size, alignment) \ (((size_t)(size)) & ((alignment) - 1)) #define ZEND_MM_ALIGNED_BASE(size, alignment) \ (((size_t)(size)) & ~((alignment) - 1)) #define ZEND_MM_SIZE_TO_NUM(size, alignment) \ (((size_t)(size) + ((alignment) - 1)) / (alignment)) #define ZEND_MM_BITSET_LEN (sizeof(zend_mm_bitset) * 8) /* 32 or 64 */ #define ZEND_MM_PAGE_MAP_LEN (ZEND_MM_PAGES / ZEND_MM_BITSET_LEN) /* 16 or 8 */ typedef zend_mm_bitset zend_mm_page_map[ZEND_MM_PAGE_MAP_LEN]; /* 64B */ #define ZEND_MM_IS_FRUN 0x00000000 #define ZEND_MM_IS_LRUN 0x40000000 #define ZEND_MM_IS_SRUN 0x80000000 #define ZEND_MM_LRUN_PAGES_MASK 0x000003ff #define ZEND_MM_LRUN_PAGES_OFFSET 0 #define ZEND_MM_SRUN_BIN_NUM_MASK 0x0000001f #define ZEND_MM_SRUN_BIN_NUM_OFFSET 0 #define ZEND_MM_SRUN_FREE_COUNTER_MASK 0x01ff0000 #define ZEND_MM_SRUN_FREE_COUNTER_OFFSET 16 #define ZEND_MM_NRUN_OFFSET_MASK 0x01ff0000 #define ZEND_MM_NRUN_OFFSET_OFFSET 16 #define ZEND_MM_LRUN_PAGES(info) (((info) & ZEND_MM_LRUN_PAGES_MASK) >> ZEND_MM_LRUN_PAGES_OFFSET) #define ZEND_MM_SRUN_BIN_NUM(info) (((info) & ZEND_MM_SRUN_BIN_NUM_MASK) >> ZEND_MM_SRUN_BIN_NUM_OFFSET) #define ZEND_MM_SRUN_FREE_COUNTER(info) (((info) & ZEND_MM_SRUN_FREE_COUNTER_MASK) >> ZEND_MM_SRUN_FREE_COUNTER_OFFSET) #define ZEND_MM_NRUN_OFFSET(info) (((info) & ZEND_MM_NRUN_OFFSET_MASK) >> ZEND_MM_NRUN_OFFSET_OFFSET) #define ZEND_MM_FRUN() ZEND_MM_IS_FRUN #define ZEND_MM_LRUN(count) (ZEND_MM_IS_LRUN | ((count) << ZEND_MM_LRUN_PAGES_OFFSET)) #define ZEND_MM_SRUN(bin_num) (ZEND_MM_IS_SRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET)) #define ZEND_MM_SRUN_EX(bin_num, count) (ZEND_MM_IS_SRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET) | ((count) << ZEND_MM_SRUN_FREE_COUNTER_OFFSET)) #define ZEND_MM_NRUN(bin_num, offset) (ZEND_MM_IS_SRUN | ZEND_MM_IS_LRUN | ((bin_num) << ZEND_MM_SRUN_BIN_NUM_OFFSET) | ((offset) << ZEND_MM_NRUN_OFFSET_OFFSET)) #define ZEND_MM_BINS 30 typedef struct _zend_mm_page zend_mm_page; typedef struct _zend_mm_bin zend_mm_bin; typedef struct _zend_mm_free_slot zend_mm_free_slot; typedef struct _zend_mm_chunk zend_mm_chunk; typedef struct _zend_mm_huge_list zend_mm_huge_list; #ifdef _WIN64 # define PTR_FMT "0x%0.16I64x" #elif SIZEOF_LONG == 8 # define PTR_FMT "0x%0.16lx" #else # define PTR_FMT "0x%0.8lx" #endif #ifdef MAP_HUGETLB int zend_mm_use_huge_pages = 0; #endif /* * Memory is retrived from OS by chunks of fixed size 2MB. * Inside chunk it's managed by pages of fixed size 4096B. * So each chunk consists from 512 pages. * The first page of each chunk is reseved for chunk header. * It contains service information about all pages. * * free_pages - current number of free pages in this chunk * * free_tail - number of continuous free pages at the end of chunk * * free_map - bitset (a bit for each page). The bit is set if the corresponding * page is allocated. Allocator for "lage sizes" may easily find a * free page (or a continuous number of pages) searching for zero * bits. * * map - contains service information for each page. (32-bits for each * page). * usage: * (2 bits) * FRUN - free page, * LRUN - first page of "large" allocation * SRUN - first page of a bin used for "small" allocation * * lrun_pages: * (10 bits) number of allocated pages * * srun_bin_num: * (5 bits) bin number (e.g. 0 for sizes 0-2, 1 for 3-4, * 2 for 5-8, 3 for 9-16 etc) see zend_alloc_sizes.h */ struct _zend_mm_heap { #if ZEND_MM_CUSTOM int use_custom_heap; #endif #if ZEND_MM_STORAGE zend_mm_storage *storage; #endif #if ZEND_MM_STAT size_t size; /* current memory usage */ size_t peak; /* peak memory usage */ #endif zend_mm_free_slot *free_slot[ZEND_MM_BINS]; /* free lists for small sizes */ #if ZEND_MM_STAT || ZEND_MM_LIMIT size_t real_size; /* current size of allocated pages */ #endif #if ZEND_MM_STAT size_t real_peak; /* peak size of allocated pages */ #endif #if ZEND_MM_LIMIT size_t limit; /* memory limit */ int overflow; /* memory overflow flag */ #endif zend_mm_huge_list *huge_list; /* list of huge allocated blocks */ zend_mm_chunk *main_chunk; zend_mm_chunk *cached_chunks; /* list of unused chunks */ int chunks_count; /* number of alocated chunks */ int peak_chunks_count; /* peak number of allocated chunks for current request */ int cached_chunks_count; /* number of cached chunks */ double avg_chunks_count; /* average number of chunks allocated per request */ #if ZEND_MM_CUSTOM union { struct { void *(*_malloc)(size_t); void (*_free)(void*); void *(*_realloc)(void*, size_t); } std; struct { void *(*_malloc)(size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); void (*_free)(void* ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); void *(*_realloc)(void*, size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); } debug; } custom_heap; #endif }; struct _zend_mm_chunk { zend_mm_heap *heap; zend_mm_chunk *next; zend_mm_chunk *prev; int free_pages; /* number of free pages */ int free_tail; /* number of free pages at the end of chunk */ int num; char reserve[64 - (sizeof(void*) * 3 + sizeof(int) * 3)]; zend_mm_heap heap_slot; /* used only in main chunk */ zend_mm_page_map free_map; /* 512 bits or 64 bytes */ zend_mm_page_info map[ZEND_MM_PAGES]; /* 2 KB = 512 * 4 */ }; struct _zend_mm_page { char bytes[ZEND_MM_PAGE_SIZE]; }; /* * bin - is one or few continuous pages (up to 8) used for allocation of * a particular "small size". */ struct _zend_mm_bin { char bytes[ZEND_MM_PAGE_SIZE * 8]; }; struct _zend_mm_free_slot { zend_mm_free_slot *next_free_slot; }; struct _zend_mm_huge_list { void *ptr; size_t size; zend_mm_huge_list *next; #if ZEND_DEBUG zend_mm_debug_info dbg; #endif }; #define ZEND_MM_PAGE_ADDR(chunk, page_num) \ ((void*)(((zend_mm_page*)(chunk)) + (page_num))) #define _BIN_DATA_SIZE(num, size, elements, pages, x, y) size, static const unsigned int bin_data_size[] = { ZEND_MM_BINS_INFO(_BIN_DATA_SIZE, x, y) }; #define _BIN_DATA_ELEMENTS(num, size, elements, pages, x, y) elements, static const int bin_elements[] = { ZEND_MM_BINS_INFO(_BIN_DATA_ELEMENTS, x, y) }; #define _BIN_DATA_PAGES(num, size, elements, pages, x, y) pages, static const int bin_pages[] = { ZEND_MM_BINS_INFO(_BIN_DATA_PAGES, x, y) }; #if ZEND_DEBUG ZEND_COLD void zend_debug_alloc_output(char *format, ...) { char output_buf[256]; va_list args; va_start(args, format); vsprintf(output_buf, format, args); va_end(args); #ifdef ZEND_WIN32 OutputDebugString(output_buf); #else fprintf(stderr, "%s", output_buf); #endif } #endif static ZEND_COLD ZEND_NORETURN void zend_mm_panic(const char *message) { fprintf(stderr, "%s\n", message); /* See http://support.microsoft.com/kb/190351 */ #ifdef ZEND_WIN32 fflush(stderr); #endif #if ZEND_DEBUG && defined(HAVE_KILL) && defined(HAVE_GETPID) kill(getpid(), SIGSEGV); #endif exit(1); } static ZEND_COLD ZEND_NORETURN void zend_mm_safe_error(zend_mm_heap *heap, const char *format, size_t limit, #if ZEND_DEBUG const char *filename, uint lineno, #endif size_t size) { heap->overflow = 1; zend_try { zend_error_noreturn(E_ERROR, format, limit, #if ZEND_DEBUG filename, lineno, #endif size); } zend_catch { } zend_end_try(); heap->overflow = 0; zend_bailout(); exit(1); } #ifdef _WIN32 void stderr_last_error(char *msg) { LPSTR buf = NULL; DWORD err = GetLastError(); if (!FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&buf, 0, NULL)) { fprintf(stderr, "\n%s: [0x%08lx]\n", msg, err); } else { fprintf(stderr, "\n%s: [0x%08lx] %s\n", msg, err, buf); } } #endif /*****************/ /* OS Allocation */ /*****************/ static void *zend_mm_mmap_fixed(void *addr, size_t size) { #ifdef _WIN32 return VirtualAlloc(addr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); #else /* MAP_FIXED leads to discarding of the old mapping, so it can't be used. */ void *ptr = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON /*| MAP_POPULATE | MAP_HUGETLB*/, -1, 0); if (ptr == MAP_FAILED) { #if ZEND_MM_ERROR fprintf(stderr, "\nmmap() failed: [%d] %s\n", errno, strerror(errno)); #endif return NULL; } else if (ptr != addr) { if (munmap(ptr, size) != 0) { #if ZEND_MM_ERROR fprintf(stderr, "\nmunmap() failed: [%d] %s\n", errno, strerror(errno)); #endif } return NULL; } return ptr; #endif } static void *zend_mm_mmap(size_t size) { #ifdef _WIN32 void *ptr = VirtualAlloc(NULL, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); if (ptr == NULL) { #if ZEND_MM_ERROR stderr_last_error("VirtualAlloc() failed"); #endif return NULL; } return ptr; #else void *ptr; #ifdef MAP_HUGETLB if (zend_mm_use_huge_pages && size == ZEND_MM_CHUNK_SIZE) { ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON | MAP_HUGETLB, -1, 0); if (ptr != MAP_FAILED) { return ptr; } } #endif ptr = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); if (ptr == MAP_FAILED) { #if ZEND_MM_ERROR fprintf(stderr, "\nmmap() failed: [%d] %s\n", errno, strerror(errno)); #endif return NULL; } return ptr; #endif } static void zend_mm_munmap(void *addr, size_t size) { #ifdef _WIN32 if (VirtualFree(addr, 0, MEM_RELEASE) == 0) { #if ZEND_MM_ERROR stderr_last_error("VirtualFree() failed"); #endif } #else if (munmap(addr, size) != 0) { #if ZEND_MM_ERROR fprintf(stderr, "\nmunmap() failed: [%d] %s\n", errno, strerror(errno)); #endif } #endif } /***********/ /* Bitmask */ /***********/ /* number of trailing set (1) bits */ static zend_always_inline int zend_mm_bitset_nts(zend_mm_bitset bitset) { #if (defined(__GNUC__) || __has_builtin(__builtin_ctzl)) && SIZEOF_ZEND_LONG == SIZEOF_LONG && defined(PHP_HAVE_BUILTIN_CTZL) return __builtin_ctzl(~bitset); #elif (defined(__GNUC__) || __has_builtin(__builtin_ctzll)) && defined(PHP_HAVE_BUILTIN_CTZLL) return __builtin_ctzll(~bitset); #elif defined(_WIN32) unsigned long index; #if defined(_WIN64) if (!BitScanForward64(&index, ~bitset)) { #else if (!BitScanForward(&index, ~bitset)) { #endif /* undefined behavior */ return 32; } return (int)index; #else int n; if (bitset == (zend_mm_bitset)-1) return ZEND_MM_BITSET_LEN; n = 0; #if SIZEOF_ZEND_LONG == 8 if (sizeof(zend_mm_bitset) == 8) { if ((bitset & 0xffffffff) == 0xffffffff) {n += 32; bitset = bitset >> Z_UL(32);} } #endif if ((bitset & 0x0000ffff) == 0x0000ffff) {n += 16; bitset = bitset >> 16;} if ((bitset & 0x000000ff) == 0x000000ff) {n += 8; bitset = bitset >> 8;} if ((bitset & 0x0000000f) == 0x0000000f) {n += 4; bitset = bitset >> 4;} if ((bitset & 0x00000003) == 0x00000003) {n += 2; bitset = bitset >> 2;} return n + (bitset & 1); #endif } /* number of trailing zero bits (0x01 -> 1; 0x40 -> 6; 0x00 -> LEN) */ static zend_always_inline int zend_mm_bitset_ntz(zend_mm_bitset bitset) { #if (defined(__GNUC__) || __has_builtin(__builtin_ctzl)) && SIZEOF_ZEND_LONG == SIZEOF_LONG && defined(PHP_HAVE_BUILTIN_CTZL) return __builtin_ctzl(bitset); #elif (defined(__GNUC__) || __has_builtin(__builtin_ctzll)) && defined(PHP_HAVE_BUILTIN_CTZLL) return __builtin_ctzll(bitset); #elif defined(_WIN32) unsigned long index; #if defined(_WIN64) if (!BitScanForward64(&index, bitset)) { #else if (!BitScanForward(&index, bitset)) { #endif /* undefined behavior */ return 32; } return (int)index; #else int n; if (bitset == (zend_mm_bitset)0) return ZEND_MM_BITSET_LEN; n = 1; #if SIZEOF_ZEND_LONG == 8 if (sizeof(zend_mm_bitset) == 8) { if ((bitset & 0xffffffff) == 0) {n += 32; bitset = bitset >> Z_UL(32);} } #endif if ((bitset & 0x0000ffff) == 0) {n += 16; bitset = bitset >> 16;} if ((bitset & 0x000000ff) == 0) {n += 8; bitset = bitset >> 8;} if ((bitset & 0x0000000f) == 0) {n += 4; bitset = bitset >> 4;} if ((bitset & 0x00000003) == 0) {n += 2; bitset = bitset >> 2;} return n - (bitset & 1); #endif } static zend_always_inline int zend_mm_bitset_find_zero(zend_mm_bitset *bitset, int size) { int i = 0; do { zend_mm_bitset tmp = bitset[i]; if (tmp != (zend_mm_bitset)-1) { return i * ZEND_MM_BITSET_LEN + zend_mm_bitset_nts(tmp); } i++; } while (i < size); return -1; } static zend_always_inline int zend_mm_bitset_find_one(zend_mm_bitset *bitset, int size) { int i = 0; do { zend_mm_bitset tmp = bitset[i]; if (tmp != 0) { return i * ZEND_MM_BITSET_LEN + zend_mm_bitset_ntz(tmp); } i++; } while (i < size); return -1; } static zend_always_inline int zend_mm_bitset_find_zero_and_set(zend_mm_bitset *bitset, int size) { int i = 0; do { zend_mm_bitset tmp = bitset[i]; if (tmp != (zend_mm_bitset)-1) { int n = zend_mm_bitset_nts(tmp); bitset[i] |= Z_UL(1) << n; return i * ZEND_MM_BITSET_LEN + n; } i++; } while (i < size); return -1; } static zend_always_inline int zend_mm_bitset_is_set(zend_mm_bitset *bitset, int bit) { return (bitset[bit / ZEND_MM_BITSET_LEN] & (Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1)))) != 0; } static zend_always_inline void zend_mm_bitset_set_bit(zend_mm_bitset *bitset, int bit) { bitset[bit / ZEND_MM_BITSET_LEN] |= (Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1))); } static zend_always_inline void zend_mm_bitset_reset_bit(zend_mm_bitset *bitset, int bit) { bitset[bit / ZEND_MM_BITSET_LEN] &= ~(Z_L(1) << (bit & (ZEND_MM_BITSET_LEN-1))); } static zend_always_inline void zend_mm_bitset_set_range(zend_mm_bitset *bitset, int start, int len) { if (len == 1) { zend_mm_bitset_set_bit(bitset, start); } else { int pos = start / ZEND_MM_BITSET_LEN; int end = (start + len - 1) / ZEND_MM_BITSET_LEN; int bit = start & (ZEND_MM_BITSET_LEN - 1); zend_mm_bitset tmp; if (pos != end) { /* set bits from "bit" to ZEND_MM_BITSET_LEN-1 */ tmp = (zend_mm_bitset)-1 << bit; bitset[pos++] |= tmp; while (pos != end) { /* set all bits */ bitset[pos++] = (zend_mm_bitset)-1; } end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* set bits from "0" to "end" */ tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); bitset[pos] |= tmp; } else { end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* set bits from "bit" to "end" */ tmp = (zend_mm_bitset)-1 << bit; tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); bitset[pos] |= tmp; } } } static zend_always_inline void zend_mm_bitset_reset_range(zend_mm_bitset *bitset, int start, int len) { if (len == 1) { zend_mm_bitset_reset_bit(bitset, start); } else { int pos = start / ZEND_MM_BITSET_LEN; int end = (start + len - 1) / ZEND_MM_BITSET_LEN; int bit = start & (ZEND_MM_BITSET_LEN - 1); zend_mm_bitset tmp; if (pos != end) { /* reset bits from "bit" to ZEND_MM_BITSET_LEN-1 */ tmp = ~((Z_L(1) << bit) - 1); bitset[pos++] &= ~tmp; while (pos != end) { /* set all bits */ bitset[pos++] = 0; } end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* reset bits from "0" to "end" */ tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); bitset[pos] &= ~tmp; } else { end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* reset bits from "bit" to "end" */ tmp = (zend_mm_bitset)-1 << bit; tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); bitset[pos] &= ~tmp; } } } static zend_always_inline int zend_mm_bitset_is_free_range(zend_mm_bitset *bitset, int start, int len) { if (len == 1) { return !zend_mm_bitset_is_set(bitset, start); } else { int pos = start / ZEND_MM_BITSET_LEN; int end = (start + len - 1) / ZEND_MM_BITSET_LEN; int bit = start & (ZEND_MM_BITSET_LEN - 1); zend_mm_bitset tmp; if (pos != end) { /* set bits from "bit" to ZEND_MM_BITSET_LEN-1 */ tmp = (zend_mm_bitset)-1 << bit; if ((bitset[pos++] & tmp) != 0) { return 0; } while (pos != end) { /* set all bits */ if (bitset[pos++] != 0) { return 0; } } end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* set bits from "0" to "end" */ tmp = (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); return (bitset[pos] & tmp) == 0; } else { end = (start + len - 1) & (ZEND_MM_BITSET_LEN - 1); /* set bits from "bit" to "end" */ tmp = (zend_mm_bitset)-1 << bit; tmp &= (zend_mm_bitset)-1 >> ((ZEND_MM_BITSET_LEN - 1) - end); return (bitset[pos] & tmp) == 0; } } } /**********/ /* Chunks */ /**********/ static void *zend_mm_chunk_alloc_int(size_t size, size_t alignment) { void *ptr = zend_mm_mmap(size); if (ptr == NULL) { return NULL; } else if (ZEND_MM_ALIGNED_OFFSET(ptr, alignment) == 0) { #ifdef MADV_HUGEPAGE madvise(ptr, size, MADV_HUGEPAGE); #endif return ptr; } else { size_t offset; /* chunk has to be aligned */ zend_mm_munmap(ptr, size); ptr = zend_mm_mmap(size + alignment - REAL_PAGE_SIZE); #ifdef _WIN32 offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment); zend_mm_munmap(ptr, size + alignment - REAL_PAGE_SIZE); ptr = zend_mm_mmap_fixed((void*)((char*)ptr + (alignment - offset)), size); offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment); if (offset != 0) { zend_mm_munmap(ptr, size); return NULL; } return ptr; #else offset = ZEND_MM_ALIGNED_OFFSET(ptr, alignment); if (offset != 0) { offset = alignment - offset; zend_mm_munmap(ptr, offset); ptr = (char*)ptr + offset; alignment -= offset; } if (alignment > REAL_PAGE_SIZE) { zend_mm_munmap((char*)ptr + size, alignment - REAL_PAGE_SIZE); } # ifdef MADV_HUGEPAGE madvise(ptr, size, MADV_HUGEPAGE); # endif #endif return ptr; } } static void *zend_mm_chunk_alloc(zend_mm_heap *heap, size_t size, size_t alignment) { #if ZEND_MM_STORAGE if (UNEXPECTED(heap->storage)) { void *ptr = heap->storage->handlers.chunk_alloc(heap->storage, size, alignment); ZEND_ASSERT(((zend_uintptr_t)((char*)ptr + (alignment-1)) & (alignment-1)) == (zend_uintptr_t)ptr); return ptr; } #endif return zend_mm_chunk_alloc_int(size, alignment); } static void zend_mm_chunk_free(zend_mm_heap *heap, void *addr, size_t size) { #if ZEND_MM_STORAGE if (UNEXPECTED(heap->storage)) { heap->storage->handlers.chunk_free(heap->storage, addr, size); return; } #endif zend_mm_munmap(addr, size); } static int zend_mm_chunk_truncate(zend_mm_heap *heap, void *addr, size_t old_size, size_t new_size) { #if ZEND_MM_STORAGE if (UNEXPECTED(heap->storage)) { if (heap->storage->handlers.chunk_truncate) { return heap->storage->handlers.chunk_truncate(heap->storage, addr, old_size, new_size); } else { return 0; } } #endif #ifndef _WIN32 zend_mm_munmap((char*)addr + new_size, old_size - new_size); return 1; #else return 0; #endif } static int zend_mm_chunk_extend(zend_mm_heap *heap, void *addr, size_t old_size, size_t new_size) { #if ZEND_MM_STORAGE if (UNEXPECTED(heap->storage)) { if (heap->storage->handlers.chunk_extend) { return heap->storage->handlers.chunk_extend(heap->storage, addr, old_size, new_size); } else { return 0; } } #endif #ifndef _WIN32 return (zend_mm_mmap_fixed((char*)addr + old_size, new_size - old_size) != NULL); #else return 0; #endif } static zend_always_inline void zend_mm_chunk_init(zend_mm_heap *heap, zend_mm_chunk *chunk) { chunk->heap = heap; chunk->next = heap->main_chunk; chunk->prev = heap->main_chunk->prev; chunk->prev->next = chunk; chunk->next->prev = chunk; /* mark first pages as allocated */ chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE; chunk->free_tail = ZEND_MM_FIRST_PAGE; /* the younger chunks have bigger number */ chunk->num = chunk->prev->num + 1; /* mark first pages as allocated */ chunk->free_map[0] = (1L << ZEND_MM_FIRST_PAGE) - 1; chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE); } /***********************/ /* Huge Runs (forward) */ /***********************/ static size_t zend_mm_get_huge_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); static void zend_mm_free_huge(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); #if ZEND_DEBUG static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); #else static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC); #endif /**************/ /* Large Runs */ /**************/ #if ZEND_DEBUG static void *zend_mm_alloc_pages(zend_mm_heap *heap, int pages_count, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #else static void *zend_mm_alloc_pages(zend_mm_heap *heap, int pages_count ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #endif { zend_mm_chunk *chunk = heap->main_chunk; int page_num, len; while (1) { if (UNEXPECTED(chunk->free_pages < pages_count)) { goto not_found; #if 0 } else if (UNEXPECTED(chunk->free_pages + chunk->free_tail == ZEND_MM_PAGES)) { if (UNEXPECTED(ZEND_MM_PAGES - chunk->free_tail < pages_count)) { goto not_found; } else { page_num = chunk->free_tail; goto found; } } else if (0) { /* First-Fit Search */ int free_tail = chunk->free_tail; zend_mm_bitset *bitset = chunk->free_map; zend_mm_bitset tmp = *(bitset++); int i = 0; while (1) { /* skip allocated blocks */ while (tmp == (zend_mm_bitset)-1) { i += ZEND_MM_BITSET_LEN; if (i == ZEND_MM_PAGES) { goto not_found; } tmp = *(bitset++); } /* find first 0 bit */ page_num = i + zend_mm_bitset_nts(tmp); /* reset bits from 0 to "bit" */ tmp &= tmp + 1; /* skip free blocks */ while (tmp == 0) { i += ZEND_MM_BITSET_LEN; len = i - page_num; if (len >= pages_count) { goto found; } else if (i >= free_tail) { goto not_found; } tmp = *(bitset++); } /* find first 1 bit */ len = (i + zend_mm_bitset_ntz(tmp)) - page_num; if (len >= pages_count) { goto found; } /* set bits from 0 to "bit" */ tmp |= tmp - 1; } #endif } else { /* Best-Fit Search */ int best = -1; int best_len = ZEND_MM_PAGES; int free_tail = chunk->free_tail; zend_mm_bitset *bitset = chunk->free_map; zend_mm_bitset tmp = *(bitset++); int i = 0; while (1) { /* skip allocated blocks */ while (tmp == (zend_mm_bitset)-1) { i += ZEND_MM_BITSET_LEN; if (i == ZEND_MM_PAGES) { if (best > 0) { page_num = best; goto found; } else { goto not_found; } } tmp = *(bitset++); } /* find first 0 bit */ page_num = i + zend_mm_bitset_nts(tmp); /* reset bits from 0 to "bit" */ tmp &= tmp + 1; /* skip free blocks */ while (tmp == 0) { i += ZEND_MM_BITSET_LEN; if (i >= free_tail || i == ZEND_MM_PAGES) { len = ZEND_MM_PAGES - page_num; if (len >= pages_count && len < best_len) { chunk->free_tail = page_num + pages_count; goto found; } else { /* set accurate value */ chunk->free_tail = page_num; if (best > 0) { page_num = best; goto found; } else { goto not_found; } } } tmp = *(bitset++); } /* find first 1 bit */ len = i + zend_mm_bitset_ntz(tmp) - page_num; if (len >= pages_count) { if (len == pages_count) { goto found; } else if (len < best_len) { best_len = len; best = page_num; } } /* set bits from 0 to "bit" */ tmp |= tmp - 1; } } not_found: if (chunk->next == heap->main_chunk) { get_chunk: if (heap->cached_chunks) { heap->cached_chunks_count--; chunk = heap->cached_chunks; heap->cached_chunks = chunk->next; } else { #if ZEND_MM_LIMIT if (UNEXPECTED(heap->real_size + ZEND_MM_CHUNK_SIZE > heap->limit)) { if (zend_mm_gc(heap)) { goto get_chunk; } else if (heap->overflow == 0) { #if ZEND_DEBUG zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, ZEND_MM_PAGE_SIZE * pages_count); #endif return NULL; } } #endif chunk = (zend_mm_chunk*)zend_mm_chunk_alloc(heap, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(chunk == NULL)) { /* insufficient memory */ if (zend_mm_gc(heap) && (chunk = (zend_mm_chunk*)zend_mm_chunk_alloc(heap, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE)) != NULL) { /* pass */ } else { #if !ZEND_MM_LIMIT zend_mm_safe_error(heap, "Out of memory"); #elif ZEND_DEBUG zend_mm_safe_error(heap, "Out of memory (allocated %zu) at %s:%d (tried to allocate %zu bytes)", heap->real_size, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Out of memory (allocated %zu) (tried to allocate %zu bytes)", heap->real_size, ZEND_MM_PAGE_SIZE * pages_count); #endif return NULL; } } #if ZEND_MM_STAT do { size_t size = heap->real_size + ZEND_MM_CHUNK_SIZE; size_t peak = MAX(heap->real_peak, size); heap->real_size = size; heap->real_peak = peak; } while (0); #elif ZEND_MM_LIMIT heap->real_size += ZEND_MM_CHUNK_SIZE; #endif } heap->chunks_count++; if (heap->chunks_count > heap->peak_chunks_count) { heap->peak_chunks_count = heap->chunks_count; } zend_mm_chunk_init(heap, chunk); page_num = ZEND_MM_FIRST_PAGE; len = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE; goto found; } else { chunk = chunk->next; } } found: /* mark run as allocated */ chunk->free_pages -= pages_count; zend_mm_bitset_set_range(chunk->free_map, page_num, pages_count); chunk->map[page_num] = ZEND_MM_LRUN(pages_count); if (page_num == chunk->free_tail) { chunk->free_tail = page_num + pages_count; } return ZEND_MM_PAGE_ADDR(chunk, page_num); } static zend_always_inline void *zend_mm_alloc_large(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { int pages_count = (int)ZEND_MM_SIZE_TO_NUM(size, ZEND_MM_PAGE_SIZE); #if ZEND_DEBUG void *ptr = zend_mm_alloc_pages(heap, pages_count, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else void *ptr = zend_mm_alloc_pages(heap, pages_count ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif #if ZEND_MM_STAT do { size_t size = heap->size + pages_count * ZEND_MM_PAGE_SIZE; size_t peak = MAX(heap->peak, size); heap->size = size; heap->peak = peak; } while (0); #endif return ptr; } static zend_always_inline void zend_mm_delete_chunk(zend_mm_heap *heap, zend_mm_chunk *chunk) { chunk->next->prev = chunk->prev; chunk->prev->next = chunk->next; heap->chunks_count--; if (heap->chunks_count + heap->cached_chunks_count < heap->avg_chunks_count + 0.1) { /* delay deletion */ heap->cached_chunks_count++; chunk->next = heap->cached_chunks; heap->cached_chunks = chunk; } else { #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size -= ZEND_MM_CHUNK_SIZE; #endif if (!heap->cached_chunks || chunk->num > heap->cached_chunks->num) { zend_mm_chunk_free(heap, chunk, ZEND_MM_CHUNK_SIZE); } else { //TODO: select the best chunk to delete??? chunk->next = heap->cached_chunks->next; zend_mm_chunk_free(heap, heap->cached_chunks, ZEND_MM_CHUNK_SIZE); heap->cached_chunks = chunk; } } } static zend_always_inline void zend_mm_free_pages_ex(zend_mm_heap *heap, zend_mm_chunk *chunk, int page_num, int pages_count, int free_chunk) { chunk->free_pages += pages_count; zend_mm_bitset_reset_range(chunk->free_map, page_num, pages_count); chunk->map[page_num] = 0; if (chunk->free_tail == page_num + pages_count) { /* this setting may be not accurate */ chunk->free_tail = page_num; } if (free_chunk && chunk->free_pages == ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE) { zend_mm_delete_chunk(heap, chunk); } } static void zend_mm_free_pages(zend_mm_heap *heap, zend_mm_chunk *chunk, int page_num, int pages_count) { zend_mm_free_pages_ex(heap, chunk, page_num, pages_count, 1); } static zend_always_inline void zend_mm_free_large(zend_mm_heap *heap, zend_mm_chunk *chunk, int page_num, int pages_count) { #if ZEND_MM_STAT heap->size -= pages_count * ZEND_MM_PAGE_SIZE; #endif zend_mm_free_pages(heap, chunk, page_num, pages_count); } /**************/ /* Small Runs */ /**************/ /* higher set bit number (0->N/A, 1->1, 2->2, 4->3, 8->4, 127->7, 128->8 etc) */ static zend_always_inline int zend_mm_small_size_to_bit(int size) { #if (defined(__GNUC__) || __has_builtin(__builtin_clz)) && defined(PHP_HAVE_BUILTIN_CLZ) return (__builtin_clz(size) ^ 0x1f) + 1; #elif defined(_WIN32) unsigned long index; if (!BitScanReverse(&index, (unsigned long)size)) { /* undefined behavior */ return 64; } return (((31 - (int)index) ^ 0x1f) + 1); #else int n = 16; if (size <= 0x00ff) {n -= 8; size = size << 8;} if (size <= 0x0fff) {n -= 4; size = size << 4;} if (size <= 0x3fff) {n -= 2; size = size << 2;} if (size <= 0x7fff) {n -= 1;} return n; #endif } #ifndef MAX # define MAX(a, b) (((a) > (b)) ? (a) : (b)) #endif #ifndef MIN # define MIN(a, b) (((a) < (b)) ? (a) : (b)) #endif static zend_always_inline int zend_mm_small_size_to_bin(size_t size) { #if 0 int n; /*0, 1, 2, 3, 4, 5, 6, 7, 8, 9 10, 11, 12*/ static const int f1[] = { 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9}; static const int f2[] = { 0, 0, 0, 0, 0, 0, 0, 4, 8, 12, 16, 20, 24}; if (UNEXPECTED(size <= 2)) return 0; n = zend_mm_small_size_to_bit(size - 1); return ((size-1) >> f1[n]) + f2[n]; #else unsigned int t1, t2; if (size <= 64) { /* we need to support size == 0 ... */ return (size - !!size) >> 3; } else { t1 = size - 1; t2 = zend_mm_small_size_to_bit(t1) - 3; t1 = t1 >> t2; t2 = t2 - 3; t2 = t2 << 2; return (int)(t1 + t2); } #endif } #define ZEND_MM_SMALL_SIZE_TO_BIN(size) zend_mm_small_size_to_bin(size) static zend_never_inline void *zend_mm_alloc_small_slow(zend_mm_heap *heap, int bin_num ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { zend_mm_chunk *chunk; int page_num; zend_mm_bin *bin; zend_mm_free_slot *p, *end; #if ZEND_DEBUG bin = (zend_mm_bin*)zend_mm_alloc_pages(heap, bin_pages[bin_num], bin_data_size[bin_num] ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else bin = (zend_mm_bin*)zend_mm_alloc_pages(heap, bin_pages[bin_num] ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif if (UNEXPECTED(bin == NULL)) { /* insufficient memory */ return NULL; } chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(bin, ZEND_MM_CHUNK_SIZE); page_num = ZEND_MM_ALIGNED_OFFSET(bin, ZEND_MM_CHUNK_SIZE) / ZEND_MM_PAGE_SIZE; chunk->map[page_num] = ZEND_MM_SRUN(bin_num); if (bin_pages[bin_num] > 1) { int i = 1; do { chunk->map[page_num+i] = ZEND_MM_NRUN(bin_num, i); i++; } while (i < bin_pages[bin_num]); } /* create a linked list of elements from 1 to last */ end = (zend_mm_free_slot*)((char*)bin + (bin_data_size[bin_num] * (bin_elements[bin_num] - 1))); heap->free_slot[bin_num] = p = (zend_mm_free_slot*)((char*)bin + bin_data_size[bin_num]); do { p->next_free_slot = (zend_mm_free_slot*)((char*)p + bin_data_size[bin_num]);; #if ZEND_DEBUG do { zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); dbg->size = 0; } while (0); #endif p = (zend_mm_free_slot*)((char*)p + bin_data_size[bin_num]); } while (p != end); /* terminate list using NULL */ p->next_free_slot = NULL; #if ZEND_DEBUG do { zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); dbg->size = 0; } while (0); #endif /* return first element */ return (char*)bin; } static zend_always_inline void *zend_mm_alloc_small(zend_mm_heap *heap, size_t size, int bin_num ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { #if ZEND_MM_STAT do { size_t size = heap->size + bin_data_size[bin_num]; size_t peak = MAX(heap->peak, size); heap->size = size; heap->peak = peak; } while (0); #endif if (EXPECTED(heap->free_slot[bin_num] != NULL)) { zend_mm_free_slot *p = heap->free_slot[bin_num]; heap->free_slot[bin_num] = p->next_free_slot; return (void*)p; } else { return zend_mm_alloc_small_slow(heap, bin_num ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } } static zend_always_inline void zend_mm_free_small(zend_mm_heap *heap, void *ptr, int bin_num) { zend_mm_free_slot *p; #if ZEND_MM_STAT heap->size -= bin_data_size[bin_num]; #endif #if ZEND_DEBUG do { zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)ptr + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); dbg->size = 0; } while (0); #endif p = (zend_mm_free_slot*)ptr; p->next_free_slot = heap->free_slot[bin_num]; heap->free_slot[bin_num] = p; } /********/ /* Heap */ /********/ #if ZEND_DEBUG static zend_always_inline zend_mm_debug_info *zend_mm_get_debug_info(zend_mm_heap *heap, void *ptr) { size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); zend_mm_chunk *chunk; int page_num; zend_mm_page_info info; ZEND_MM_CHECK(page_offset != 0, "zend_mm_heap corrupted"); chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); info = chunk->map[page_num]; ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); if (EXPECTED(info & ZEND_MM_IS_SRUN)) { int bin_num = ZEND_MM_SRUN_BIN_NUM(info); return (zend_mm_debug_info*)((char*)ptr + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); } else /* if (info & ZEND_MM_IS_LRUN) */ { int pages_count = ZEND_MM_LRUN_PAGES(info); return (zend_mm_debug_info*)((char*)ptr + ZEND_MM_PAGE_SIZE * pages_count - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); } } #endif static zend_always_inline void *zend_mm_alloc_heap(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { void *ptr; #if ZEND_DEBUG size_t real_size = size; zend_mm_debug_info *dbg; /* special handling for zero-size allocation */ size = MAX(size, 1); size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)); if (UNEXPECTED(size < real_size)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu + %zu)", ZEND_MM_ALIGNED_SIZE(real_size), ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); return NULL; } #endif if (size <= ZEND_MM_MAX_SMALL_SIZE) { ptr = zend_mm_alloc_small(heap, size, ZEND_MM_SMALL_SIZE_TO_BIN(size) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } else if (size <= ZEND_MM_MAX_LARGE_SIZE) { ptr = zend_mm_alloc_large(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } else { #if ZEND_DEBUG size = real_size; #endif return zend_mm_alloc_huge(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } } static zend_always_inline void zend_mm_free_heap(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(page_offset == 0)) { if (ptr != NULL) { zend_mm_free_huge(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } } else { zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); int page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); zend_mm_page_info info = chunk->map[page_num]; ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); if (EXPECTED(info & ZEND_MM_IS_SRUN)) { zend_mm_free_small(heap, ptr, ZEND_MM_SRUN_BIN_NUM(info)); } else /* if (info & ZEND_MM_IS_LRUN) */ { int pages_count = ZEND_MM_LRUN_PAGES(info); ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted"); zend_mm_free_large(heap, chunk, page_num, pages_count); } } } static size_t zend_mm_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(page_offset == 0)) { return zend_mm_get_huge_block_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } else { zend_mm_chunk *chunk; #if 0 && ZEND_DEBUG zend_mm_debug_info *dbg = zend_mm_get_debug_info(heap, ptr); return dbg->size; #else int page_num; zend_mm_page_info info; chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); info = chunk->map[page_num]; ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); if (EXPECTED(info & ZEND_MM_IS_SRUN)) { return bin_data_size[ZEND_MM_SRUN_BIN_NUM(info)]; } else /* if (info & ZEND_MM_IS_LARGE_RUN) */ { return ZEND_MM_LRUN_PAGES(info) * ZEND_MM_PAGE_SIZE; } #endif } } static void *zend_mm_realloc_heap(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { size_t page_offset; size_t old_size; size_t new_size; void *ret; #if ZEND_DEBUG size_t real_size; zend_mm_debug_info *dbg; #endif page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(page_offset == 0)) { if (UNEXPECTED(ptr == NULL)) { return zend_mm_alloc_heap(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } old_size = zend_mm_get_huge_block_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #if ZEND_DEBUG real_size = size; size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)); #endif if (size > ZEND_MM_MAX_LARGE_SIZE) { #if ZEND_DEBUG size = real_size; #endif #ifdef ZEND_WIN32 /* On Windows we don't have ability to extend huge blocks in-place. * We allocate them with 2MB size granularity, to avoid many * reallocations when they are extended by small pieces */ new_size = ZEND_MM_ALIGNED_SIZE_EX(size, MAX(REAL_PAGE_SIZE, ZEND_MM_CHUNK_SIZE)); #else new_size = ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE); #endif if (new_size == old_size) { #if ZEND_DEBUG zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif return ptr; } else if (new_size < old_size) { /* unmup tail */ if (zend_mm_chunk_truncate(heap, ptr, old_size, new_size)) { #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size -= old_size - new_size; #endif #if ZEND_MM_STAT heap->size -= old_size - new_size; #endif #if ZEND_DEBUG zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif return ptr; } } else /* if (new_size > old_size) */ { #if ZEND_MM_LIMIT if (UNEXPECTED(heap->real_size + (new_size - old_size) > heap->limit)) { if (zend_mm_gc(heap) && heap->real_size + (new_size - old_size) <= heap->limit) { /* pass */ } else if (heap->overflow == 0) { #if ZEND_DEBUG zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, size); #endif return NULL; } } #endif /* try to map tail right after this block */ if (zend_mm_chunk_extend(heap, ptr, old_size, new_size)) { #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size += new_size - old_size; #endif #if ZEND_MM_STAT heap->real_peak = MAX(heap->real_peak, heap->real_size); heap->size += new_size - old_size; heap->peak = MAX(heap->peak, heap->size); #endif #if ZEND_DEBUG zend_mm_change_huge_block_size(heap, ptr, new_size, real_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else zend_mm_change_huge_block_size(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif return ptr; } } } } else { zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); int page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); zend_mm_page_info info = chunk->map[page_num]; #if ZEND_DEBUG size_t real_size = size; size = ZEND_MM_ALIGNED_SIZE(size) + ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info)); #endif ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); if (info & ZEND_MM_IS_SRUN) { int old_bin_num = ZEND_MM_SRUN_BIN_NUM(info); old_size = bin_data_size[old_bin_num]; if (size <= ZEND_MM_MAX_SMALL_SIZE) { int bin_num = ZEND_MM_SMALL_SIZE_TO_BIN(size); if (old_bin_num == bin_num) { #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } } } else /* if (info & ZEND_MM_IS_LARGE_RUN) */ { ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted"); old_size = ZEND_MM_LRUN_PAGES(info) * ZEND_MM_PAGE_SIZE; if (size > ZEND_MM_MAX_SMALL_SIZE && size <= ZEND_MM_MAX_LARGE_SIZE) { new_size = ZEND_MM_ALIGNED_SIZE_EX(size, ZEND_MM_PAGE_SIZE); if (new_size == old_size) { #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } else if (new_size < old_size) { /* free tail pages */ int new_pages_count = (int)(new_size / ZEND_MM_PAGE_SIZE); int rest_pages_count = (int)((old_size - new_size) / ZEND_MM_PAGE_SIZE); #if ZEND_MM_STAT heap->size -= rest_pages_count * ZEND_MM_PAGE_SIZE; #endif chunk->map[page_num] = ZEND_MM_LRUN(new_pages_count); chunk->free_pages += rest_pages_count; zend_mm_bitset_reset_range(chunk->free_map, page_num + new_pages_count, rest_pages_count); #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } else /* if (new_size > old_size) */ { int new_pages_count = (int)(new_size / ZEND_MM_PAGE_SIZE); int old_pages_count = (int)(old_size / ZEND_MM_PAGE_SIZE); /* try to allocate tail pages after this block */ if (page_num + new_pages_count <= ZEND_MM_PAGES && zend_mm_bitset_is_free_range(chunk->free_map, page_num + old_pages_count, new_pages_count - old_pages_count)) { #if ZEND_MM_STAT do { size_t size = heap->size + (new_size - old_size); size_t peak = MAX(heap->peak, size); heap->size = size; heap->peak = peak; } while (0); #endif chunk->free_pages -= new_pages_count - old_pages_count; zend_mm_bitset_set_range(chunk->free_map, page_num + old_pages_count, new_pages_count - old_pages_count); chunk->map[page_num] = ZEND_MM_LRUN(new_pages_count); #if ZEND_DEBUG dbg = zend_mm_get_debug_info(heap, ptr); dbg->size = real_size; dbg->filename = __zend_filename; dbg->orig_filename = __zend_orig_filename; dbg->lineno = __zend_lineno; dbg->orig_lineno = __zend_orig_lineno; #endif return ptr; } } } } #if ZEND_DEBUG size = real_size; #endif } /* Naive reallocation */ #if ZEND_MM_STAT do { size_t orig_peak = heap->peak; size_t orig_real_peak = heap->real_peak; #endif ret = zend_mm_alloc_heap(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); memcpy(ret, ptr, MIN(old_size, copy_size)); zend_mm_free_heap(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #if ZEND_MM_STAT heap->peak = MAX(orig_peak, heap->size); heap->real_peak = MAX(orig_real_peak, heap->real_size); } while (0); #endif return ret; } /*********************/ /* Huge Runs (again) */ /*********************/ #if ZEND_DEBUG static void zend_mm_add_huge_block(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #else static void zend_mm_add_huge_block(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #endif { zend_mm_huge_list *list = (zend_mm_huge_list*)zend_mm_alloc_heap(heap, sizeof(zend_mm_huge_list) ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); list->ptr = ptr; list->size = size; list->next = heap->huge_list; #if ZEND_DEBUG list->dbg.size = dbg_size; list->dbg.filename = __zend_filename; list->dbg.orig_filename = __zend_orig_filename; list->dbg.lineno = __zend_lineno; list->dbg.orig_lineno = __zend_orig_lineno; #endif heap->huge_list = list; } static size_t zend_mm_del_huge_block(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { zend_mm_huge_list *prev = NULL; zend_mm_huge_list *list = heap->huge_list; while (list != NULL) { if (list->ptr == ptr) { size_t size; if (prev) { prev->next = list->next; } else { heap->huge_list = list->next; } size = list->size; zend_mm_free_heap(heap, list ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); return size; } prev = list; list = list->next; } ZEND_MM_CHECK(0, "zend_mm_heap corrupted"); return 0; } static size_t zend_mm_get_huge_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { zend_mm_huge_list *list = heap->huge_list; while (list != NULL) { if (list->ptr == ptr) { return list->size; } list = list->next; } ZEND_MM_CHECK(0, "zend_mm_heap corrupted"); return 0; } #if ZEND_DEBUG static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size, size_t dbg_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #else static void zend_mm_change_huge_block_size(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) #endif { zend_mm_huge_list *list = heap->huge_list; while (list != NULL) { if (list->ptr == ptr) { list->size = size; #if ZEND_DEBUG list->dbg.size = dbg_size; list->dbg.filename = __zend_filename; list->dbg.orig_filename = __zend_orig_filename; list->dbg.lineno = __zend_lineno; list->dbg.orig_lineno = __zend_orig_lineno; #endif return; } list = list->next; } } static void *zend_mm_alloc_huge(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { #ifdef ZEND_WIN32 /* On Windows we don't have ability to extend huge blocks in-place. * We allocate them with 2MB size granularity, to avoid many * reallocations when they are extended by small pieces */ size_t new_size = ZEND_MM_ALIGNED_SIZE_EX(size, MAX(REAL_PAGE_SIZE, ZEND_MM_CHUNK_SIZE)); #else size_t new_size = ZEND_MM_ALIGNED_SIZE_EX(size, REAL_PAGE_SIZE); #endif void *ptr; #if ZEND_MM_LIMIT if (UNEXPECTED(heap->real_size + new_size > heap->limit)) { if (zend_mm_gc(heap) && heap->real_size + new_size <= heap->limit) { /* pass */ } else if (heap->overflow == 0) { #if ZEND_DEBUG zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)", heap->limit, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)", heap->limit, size); #endif return NULL; } } #endif ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(ptr == NULL)) { /* insufficient memory */ if (zend_mm_gc(heap) && (ptr = zend_mm_chunk_alloc(heap, new_size, ZEND_MM_CHUNK_SIZE)) != NULL) { /* pass */ } else { #if !ZEND_MM_LIMIT zend_mm_safe_error(heap, "Out of memory"); #elif ZEND_DEBUG zend_mm_safe_error(heap, "Out of memory (allocated %zu) at %s:%d (tried to allocate %zu bytes)", heap->real_size, __zend_filename, __zend_lineno, size); #else zend_mm_safe_error(heap, "Out of memory (allocated %zu) (tried to allocate %zu bytes)", heap->real_size, size); #endif return NULL; } } #if ZEND_DEBUG zend_mm_add_huge_block(heap, ptr, new_size, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #else zend_mm_add_huge_block(heap, ptr, new_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); #endif #if ZEND_MM_STAT do { size_t size = heap->real_size + new_size; size_t peak = MAX(heap->real_peak, size); heap->real_size = size; heap->real_peak = peak; } while (0); do { size_t size = heap->size + new_size; size_t peak = MAX(heap->peak, size); heap->size = size; heap->peak = peak; } while (0); #elif ZEND_MM_LIMIT heap->real_size += new_size; #endif return ptr; } static void zend_mm_free_huge(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { size_t size; ZEND_MM_CHECK(ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE) == 0, "zend_mm_heap corrupted"); size = zend_mm_del_huge_block(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); zend_mm_chunk_free(heap, ptr, size); #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size -= size; #endif #if ZEND_MM_STAT heap->size -= size; #endif } /******************/ /* Initialization */ /******************/ static zend_mm_heap *zend_mm_init(void) { zend_mm_chunk *chunk = (zend_mm_chunk*)zend_mm_chunk_alloc_int(ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE); zend_mm_heap *heap; if (UNEXPECTED(chunk == NULL)) { #if ZEND_MM_ERROR #ifdef _WIN32 stderr_last_error("Can't initialize heap"); #else fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno)); #endif #endif return NULL; } heap = &chunk->heap_slot; chunk->heap = heap; chunk->next = chunk; chunk->prev = chunk; chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE; chunk->free_tail = ZEND_MM_FIRST_PAGE; chunk->num = 0; chunk->free_map[0] = (Z_L(1) << ZEND_MM_FIRST_PAGE) - 1; chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE); heap->main_chunk = chunk; heap->cached_chunks = NULL; heap->chunks_count = 1; heap->peak_chunks_count = 1; heap->cached_chunks_count = 0; heap->avg_chunks_count = 1.0; #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size = ZEND_MM_CHUNK_SIZE; #endif #if ZEND_MM_STAT heap->real_peak = ZEND_MM_CHUNK_SIZE; heap->size = 0; heap->peak = 0; #endif #if ZEND_MM_LIMIT heap->limit = (Z_L(-1) >> Z_L(1)); heap->overflow = 0; #endif #if ZEND_MM_CUSTOM heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_NONE; #endif #if ZEND_MM_STORAGE heap->storage = NULL; #endif heap->huge_list = NULL; return heap; } ZEND_API size_t zend_mm_gc(zend_mm_heap *heap) { zend_mm_free_slot *p, **q; zend_mm_chunk *chunk; size_t page_offset; int page_num; zend_mm_page_info info; int i, has_free_pages, free_counter; size_t collected = 0; #if ZEND_MM_CUSTOM if (heap->use_custom_heap) { return 0; } #endif for (i = 0; i < ZEND_MM_BINS; i++) { has_free_pages = 0; p = heap->free_slot[i]; while (p != NULL) { chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(p, ZEND_MM_CHUNK_SIZE); ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); page_offset = ZEND_MM_ALIGNED_OFFSET(p, ZEND_MM_CHUNK_SIZE); ZEND_ASSERT(page_offset != 0); page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); info = chunk->map[page_num]; ZEND_ASSERT(info & ZEND_MM_IS_SRUN); if (info & ZEND_MM_IS_LRUN) { page_num -= ZEND_MM_NRUN_OFFSET(info); info = chunk->map[page_num]; ZEND_ASSERT(info & ZEND_MM_IS_SRUN); ZEND_ASSERT(!(info & ZEND_MM_IS_LRUN)); } ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(info) == i); free_counter = ZEND_MM_SRUN_FREE_COUNTER(info) + 1; if (free_counter == bin_elements[i]) { has_free_pages = 1; } chunk->map[page_num] = ZEND_MM_SRUN_EX(i, free_counter);; p = p->next_free_slot; } if (!has_free_pages) { continue; } q = &heap->free_slot[i]; p = *q; while (p != NULL) { chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(p, ZEND_MM_CHUNK_SIZE); ZEND_MM_CHECK(chunk->heap == heap, "zend_mm_heap corrupted"); page_offset = ZEND_MM_ALIGNED_OFFSET(p, ZEND_MM_CHUNK_SIZE); ZEND_ASSERT(page_offset != 0); page_num = (int)(page_offset / ZEND_MM_PAGE_SIZE); info = chunk->map[page_num]; ZEND_ASSERT(info & ZEND_MM_IS_SRUN); if (info & ZEND_MM_IS_LRUN) { page_num -= ZEND_MM_NRUN_OFFSET(info); info = chunk->map[page_num]; ZEND_ASSERT(info & ZEND_MM_IS_SRUN); ZEND_ASSERT(!(info & ZEND_MM_IS_LRUN)); } ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(info) == i); if (ZEND_MM_SRUN_FREE_COUNTER(info) == bin_elements[i]) { /* remove from cache */ p = p->next_free_slot;; *q = p; } else { q = &p->next_free_slot; p = *q; } } } chunk = heap->main_chunk; do { i = ZEND_MM_FIRST_PAGE; while (i < chunk->free_tail) { if (zend_mm_bitset_is_set(chunk->free_map, i)) { info = chunk->map[i]; if (info & ZEND_MM_IS_SRUN) { int bin_num = ZEND_MM_SRUN_BIN_NUM(info); int pages_count = bin_pages[bin_num]; if (ZEND_MM_SRUN_FREE_COUNTER(info) == bin_elements[bin_num]) { /* all elemens are free */ zend_mm_free_pages_ex(heap, chunk, i, pages_count, 0); collected += pages_count; } else { /* reset counter */ chunk->map[i] = ZEND_MM_SRUN(bin_num); } i += bin_pages[bin_num]; } else /* if (info & ZEND_MM_IS_LRUN) */ { i += ZEND_MM_LRUN_PAGES(info); } } else { i++; } } if (chunk->free_pages == ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE) { zend_mm_chunk *next_chunk = chunk->next; zend_mm_delete_chunk(heap, chunk); chunk = next_chunk; } else { chunk = chunk->next; } } while (chunk != heap->main_chunk); return collected * ZEND_MM_PAGE_SIZE; } #if ZEND_DEBUG /******************/ /* Leak detection */ /******************/ static zend_long zend_mm_find_leaks_small(zend_mm_chunk *p, int i, int j, zend_leak_info *leak) { int empty = 1; zend_long count = 0; int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]); zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] * (j + 1) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); while (j < bin_elements[bin_num]) { if (dbg->size != 0) { if (dbg->filename == leak->filename && dbg->lineno == leak->lineno) { count++; dbg->size = 0; dbg->filename = NULL; dbg->lineno = 0; } else { empty = 0; } } j++; dbg = (zend_mm_debug_info*)((char*)dbg + bin_data_size[bin_num]); } if (empty) { zend_mm_bitset_reset_range(p->free_map, i, bin_pages[bin_num]); } return count; } static zend_long zend_mm_find_leaks(zend_mm_heap *heap, zend_mm_chunk *p, int i, zend_leak_info *leak) { zend_long count = 0; do { while (i < p->free_tail) { if (zend_mm_bitset_is_set(p->free_map, i)) { if (p->map[i] & ZEND_MM_IS_SRUN) { int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]); count += zend_mm_find_leaks_small(p, i, 0, leak); i += bin_pages[bin_num]; } else /* if (p->map[i] & ZEND_MM_IS_LRUN) */ { int pages_count = ZEND_MM_LRUN_PAGES(p->map[i]); zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * (i + pages_count) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); if (dbg->filename == leak->filename && dbg->lineno == leak->lineno) { count++; } zend_mm_bitset_reset_range(p->free_map, i, pages_count); i += pages_count; } } else { i++; } } p = p->next; } while (p != heap->main_chunk); return count; } static zend_long zend_mm_find_leaks_huge(zend_mm_heap *heap, zend_mm_huge_list *list) { zend_long count = 0; zend_mm_huge_list *prev = list; zend_mm_huge_list *p = list->next; while (p) { if (p->dbg.filename == list->dbg.filename && p->dbg.lineno == list->dbg.lineno) { prev->next = p->next; zend_mm_chunk_free(heap, p->ptr, p->size); zend_mm_free_heap(heap, p, NULL, 0, NULL, 0); count++; } else { prev = p; } p = prev->next; } return count; } static void zend_mm_check_leaks(zend_mm_heap *heap) { zend_mm_huge_list *list; zend_mm_chunk *p; zend_leak_info leak; zend_long repeated = 0; uint32_t total = 0; int i, j; /* find leaked huge blocks and free them */ list = heap->huge_list; while (list) { zend_mm_huge_list *q = list; leak.addr = list->ptr; leak.size = list->dbg.size; leak.filename = list->dbg.filename; leak.orig_filename = list->dbg.orig_filename; leak.lineno = list->dbg.lineno; leak.orig_lineno = list->dbg.orig_lineno; zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL); zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak); repeated = zend_mm_find_leaks_huge(heap, list); total += 1 + repeated; if (repeated) { zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated); } heap->huge_list = list = list->next; zend_mm_chunk_free(heap, q->ptr, q->size); zend_mm_free_heap(heap, q, NULL, 0, NULL, 0); } /* for each chunk */ p = heap->main_chunk; do { i = ZEND_MM_FIRST_PAGE; while (i < p->free_tail) { if (zend_mm_bitset_is_set(p->free_map, i)) { if (p->map[i] & ZEND_MM_IS_SRUN) { int bin_num = ZEND_MM_SRUN_BIN_NUM(p->map[i]); zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); j = 0; while (j < bin_elements[bin_num]) { if (dbg->size != 0) { leak.addr = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * i + bin_data_size[bin_num] * j); leak.size = dbg->size; leak.filename = dbg->filename; leak.orig_filename = dbg->orig_filename; leak.lineno = dbg->lineno; leak.orig_lineno = dbg->orig_lineno; zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL); zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak); dbg->size = 0; dbg->filename = NULL; dbg->lineno = 0; repeated = zend_mm_find_leaks_small(p, i, j + 1, &leak) + zend_mm_find_leaks(heap, p, i + bin_pages[bin_num], &leak); total += 1 + repeated; if (repeated) { zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated); } } dbg = (zend_mm_debug_info*)((char*)dbg + bin_data_size[bin_num]); j++; } i += bin_pages[bin_num]; } else /* if (p->map[i] & ZEND_MM_IS_LRUN) */ { int pages_count = ZEND_MM_LRUN_PAGES(p->map[i]); zend_mm_debug_info *dbg = (zend_mm_debug_info*)((char*)p + ZEND_MM_PAGE_SIZE * (i + pages_count) - ZEND_MM_ALIGNED_SIZE(sizeof(zend_mm_debug_info))); leak.addr = (void*)((char*)p + ZEND_MM_PAGE_SIZE * i); leak.size = dbg->size; leak.filename = dbg->filename; leak.orig_filename = dbg->orig_filename; leak.lineno = dbg->lineno; leak.orig_lineno = dbg->orig_lineno; zend_message_dispatcher(ZMSG_LOG_SCRIPT_NAME, NULL); zend_message_dispatcher(ZMSG_MEMORY_LEAK_DETECTED, &leak); zend_mm_bitset_reset_range(p->free_map, i, pages_count); repeated = zend_mm_find_leaks(heap, p, i + pages_count, &leak); total += 1 + repeated; if (repeated) { zend_message_dispatcher(ZMSG_MEMORY_LEAK_REPEATED, (void *)(zend_uintptr_t)repeated); } i += pages_count; } } else { i++; } } p = p->next; } while (p != heap->main_chunk); if (total) { zend_message_dispatcher(ZMSG_MEMORY_LEAKS_GRAND_TOTAL, &total); } } #endif void zend_mm_shutdown(zend_mm_heap *heap, int full, int silent) { zend_mm_chunk *p; zend_mm_huge_list *list; #if ZEND_MM_CUSTOM if (heap->use_custom_heap) { if (full) { if (ZEND_DEBUG && heap->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { heap->custom_heap.debug._free(heap ZEND_FILE_LINE_CC ZEND_FILE_LINE_EMPTY_CC); } else { heap->custom_heap.std._free(heap); } } return; } #endif #if ZEND_DEBUG if (!silent) { zend_mm_check_leaks(heap); } #endif /* free huge blocks */ list = heap->huge_list; heap->huge_list = NULL; while (list) { zend_mm_huge_list *q = list; list = list->next; zend_mm_chunk_free(heap, q->ptr, q->size); } /* move all chunks except of the first one into the cache */ p = heap->main_chunk->next; while (p != heap->main_chunk) { zend_mm_chunk *q = p->next; p->next = heap->cached_chunks; heap->cached_chunks = p; p = q; heap->chunks_count--; heap->cached_chunks_count++; } if (full) { /* free all cached chunks */ while (heap->cached_chunks) { p = heap->cached_chunks; heap->cached_chunks = p->next; zend_mm_chunk_free(heap, p, ZEND_MM_CHUNK_SIZE); } /* free the first chunk */ zend_mm_chunk_free(heap, heap->main_chunk, ZEND_MM_CHUNK_SIZE); } else { zend_mm_heap old_heap; /* free some cached chunks to keep average count */ heap->avg_chunks_count = (heap->avg_chunks_count + (double)heap->peak_chunks_count) / 2.0; while ((double)heap->cached_chunks_count + 0.9 > heap->avg_chunks_count && heap->cached_chunks) { p = heap->cached_chunks; heap->cached_chunks = p->next; zend_mm_chunk_free(heap, p, ZEND_MM_CHUNK_SIZE); heap->cached_chunks_count--; } /* clear cached chunks */ p = heap->cached_chunks; while (p != NULL) { zend_mm_chunk *q = p->next; memset(p, 0, sizeof(zend_mm_chunk)); p->next = q; p = q; } /* reinitialize the first chunk and heap */ old_heap = *heap; p = heap->main_chunk; memset(p, 0, ZEND_MM_FIRST_PAGE * ZEND_MM_PAGE_SIZE); *heap = old_heap; memset(heap->free_slot, 0, sizeof(heap->free_slot)); heap->main_chunk = p; p->heap = &p->heap_slot; p->next = p; p->prev = p; p->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE; p->free_tail = ZEND_MM_FIRST_PAGE; p->free_map[0] = (1L << ZEND_MM_FIRST_PAGE) - 1; p->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE); heap->chunks_count = 1; heap->peak_chunks_count = 1; #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size = ZEND_MM_CHUNK_SIZE; #endif #if ZEND_MM_STAT heap->real_peak = ZEND_MM_CHUNK_SIZE; heap->size = heap->peak = 0; #endif } } /**************/ /* PUBLIC API */ /**************/ ZEND_API void* ZEND_FASTCALL _zend_mm_alloc(zend_mm_heap *heap, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return zend_mm_alloc_heap(heap, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API void ZEND_FASTCALL _zend_mm_free(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { zend_mm_free_heap(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } void* ZEND_FASTCALL _zend_mm_realloc(zend_mm_heap *heap, void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return zend_mm_realloc_heap(heap, ptr, size, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } void* ZEND_FASTCALL _zend_mm_realloc2(zend_mm_heap *heap, void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return zend_mm_realloc_heap(heap, ptr, size, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API size_t ZEND_FASTCALL _zend_mm_block_size(zend_mm_heap *heap, void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return zend_mm_size(heap, ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } /**********************/ /* Allocation Manager */ /**********************/ typedef struct _zend_alloc_globals { zend_mm_heap *mm_heap; } zend_alloc_globals; #ifdef ZTS static int alloc_globals_id; # define AG(v) ZEND_TSRMG(alloc_globals_id, zend_alloc_globals *, v) #else # define AG(v) (alloc_globals.v) static zend_alloc_globals alloc_globals; #endif ZEND_API int is_zend_mm(void) { #if ZEND_MM_CUSTOM return !AG(mm_heap)->use_custom_heap; #else return 1; #endif } #if !ZEND_DEBUG && (!defined(_WIN32) || defined(__clang__)) #undef _emalloc #if ZEND_MM_CUSTOM # define ZEND_MM_CUSTOM_ALLOCATOR(size) do { \ if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { \ if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { \ return AG(mm_heap)->custom_heap.debug._malloc(size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \ } else { \ return AG(mm_heap)->custom_heap.std._malloc(size); \ } \ } \ } while (0) # define ZEND_MM_CUSTOM_DEALLOCATOR(ptr) do { \ if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { \ if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { \ AG(mm_heap)->custom_heap.debug._free(ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \ } else { \ AG(mm_heap)->custom_heap.std._free(ptr); \ } \ return; \ } \ } while (0) #else # define ZEND_MM_CUSTOM_ALLOCATOR(size) # define ZEND_MM_CUSTOM_DEALLOCATOR(ptr) #endif # define _ZEND_BIN_ALLOCATOR(_num, _size, _elements, _pages, x, y) \ ZEND_API void* ZEND_FASTCALL _emalloc_ ## _size(void) { \ ZEND_MM_CUSTOM_ALLOCATOR(_size); \ return zend_mm_alloc_small(AG(mm_heap), _size, _num ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); \ } ZEND_MM_BINS_INFO(_ZEND_BIN_ALLOCATOR, x, y) ZEND_API void* ZEND_FASTCALL _emalloc_large(size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { ZEND_MM_CUSTOM_ALLOCATOR(size); return zend_mm_alloc_large(AG(mm_heap), size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API void* ZEND_FASTCALL _emalloc_huge(size_t size) { ZEND_MM_CUSTOM_ALLOCATOR(size); return zend_mm_alloc_huge(AG(mm_heap), size); } #if ZEND_DEBUG # define _ZEND_BIN_FREE(_num, _size, _elements, _pages, x, y) \ ZEND_API void ZEND_FASTCALL _efree_ ## _size(void *ptr) { \ ZEND_MM_CUSTOM_DEALLOCATOR(ptr); \ { \ size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); \ zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); \ int page_num = page_offset / ZEND_MM_PAGE_SIZE; \ ZEND_MM_CHECK(chunk->heap == AG(mm_heap), "zend_mm_heap corrupted"); \ ZEND_ASSERT(chunk->map[page_num] & ZEND_MM_IS_SRUN); \ ZEND_ASSERT(ZEND_MM_SRUN_BIN_NUM(chunk->map[page_num]) == _num); \ zend_mm_free_small(AG(mm_heap), ptr, _num); \ } \ } #else # define _ZEND_BIN_FREE(_num, _size, _elements, _pages, x, y) \ ZEND_API void ZEND_FASTCALL _efree_ ## _size(void *ptr) { \ ZEND_MM_CUSTOM_DEALLOCATOR(ptr); \ { \ zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); \ ZEND_MM_CHECK(chunk->heap == AG(mm_heap), "zend_mm_heap corrupted"); \ zend_mm_free_small(AG(mm_heap), ptr, _num); \ } \ } #endif ZEND_MM_BINS_INFO(_ZEND_BIN_FREE, x, y) ZEND_API void ZEND_FASTCALL _efree_large(void *ptr, size_t size) { ZEND_MM_CUSTOM_DEALLOCATOR(ptr); { size_t page_offset = ZEND_MM_ALIGNED_OFFSET(ptr, ZEND_MM_CHUNK_SIZE); zend_mm_chunk *chunk = (zend_mm_chunk*)ZEND_MM_ALIGNED_BASE(ptr, ZEND_MM_CHUNK_SIZE); int page_num = page_offset / ZEND_MM_PAGE_SIZE; int pages_count = ZEND_MM_ALIGNED_SIZE_EX(size, ZEND_MM_PAGE_SIZE) / ZEND_MM_PAGE_SIZE; ZEND_MM_CHECK(chunk->heap == AG(mm_heap) && ZEND_MM_ALIGNED_OFFSET(page_offset, ZEND_MM_PAGE_SIZE) == 0, "zend_mm_heap corrupted"); ZEND_ASSERT(chunk->map[page_num] & ZEND_MM_IS_LRUN); ZEND_ASSERT(ZEND_MM_LRUN_PAGES(chunk->map[page_num]) == pages_count); zend_mm_free_large(AG(mm_heap), chunk, page_num, pages_count); } } ZEND_API void ZEND_FASTCALL _efree_huge(void *ptr, size_t size) { ZEND_MM_CUSTOM_DEALLOCATOR(ptr); zend_mm_free_huge(AG(mm_heap), ptr); } #endif ZEND_API void* ZEND_FASTCALL _emalloc(size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { #if ZEND_MM_CUSTOM if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { return AG(mm_heap)->custom_heap.debug._malloc(size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } else { return AG(mm_heap)->custom_heap.std._malloc(size); } } #endif return zend_mm_alloc_heap(AG(mm_heap), size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API void ZEND_FASTCALL _efree(void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { #if ZEND_MM_CUSTOM if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { AG(mm_heap)->custom_heap.debug._free(ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } else { AG(mm_heap)->custom_heap.std._free(ptr); } return; } #endif zend_mm_free_heap(AG(mm_heap), ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API void* ZEND_FASTCALL _erealloc(void *ptr, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { return AG(mm_heap)->custom_heap.debug._realloc(ptr, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } else { return AG(mm_heap)->custom_heap.std._realloc(ptr, size); } } return zend_mm_realloc_heap(AG(mm_heap), ptr, size, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API void* ZEND_FASTCALL _erealloc2(void *ptr, size_t size, size_t copy_size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { if (ZEND_DEBUG && AG(mm_heap)->use_custom_heap == ZEND_MM_CUSTOM_HEAP_DEBUG) { return AG(mm_heap)->custom_heap.debug._realloc(ptr, size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } else { return AG(mm_heap)->custom_heap.std._realloc(ptr, size); } } return zend_mm_realloc_heap(AG(mm_heap), ptr, size, copy_size ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } ZEND_API size_t ZEND_FASTCALL _zend_mem_block_size(void *ptr ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) { return 0; } return zend_mm_size(AG(mm_heap), ptr ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); } static zend_always_inline size_t safe_address(size_t nmemb, size_t size, size_t offset) { int overflow; size_t ret = zend_safe_address(nmemb, size, offset, &overflow); if (UNEXPECTED(overflow)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", nmemb, size, offset); return 0; } return ret; } ZEND_API void* ZEND_FASTCALL _safe_emalloc(size_t nmemb, size_t size, size_t offset ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return emalloc_rel(safe_address(nmemb, size, offset)); } ZEND_API void* ZEND_FASTCALL _safe_malloc(size_t nmemb, size_t size, size_t offset) { return pemalloc(safe_address(nmemb, size, offset), 1); } ZEND_API void* ZEND_FASTCALL _safe_erealloc(void *ptr, size_t nmemb, size_t size, size_t offset ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { return erealloc_rel(ptr, safe_address(nmemb, size, offset)); } ZEND_API void* ZEND_FASTCALL _safe_realloc(void *ptr, size_t nmemb, size_t size, size_t offset) { return perealloc(ptr, safe_address(nmemb, size, offset), 1); } ZEND_API void* ZEND_FASTCALL _ecalloc(size_t nmemb, size_t size ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { void *p; p = _safe_emalloc(nmemb, size, 0 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); if (UNEXPECTED(p == NULL)) { return p; } memset(p, 0, size * nmemb); return p; } ZEND_API char* ZEND_FASTCALL _estrdup(const char *s ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { size_t length; char *p; length = strlen(s); if (UNEXPECTED(length + 1 == 0)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", 1, length, 1); } p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); if (UNEXPECTED(p == NULL)) { return p; } memcpy(p, s, length+1); return p; } ZEND_API char* ZEND_FASTCALL _estrndup(const char *s, size_t length ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC) { char *p; if (UNEXPECTED(length + 1 == 0)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", 1, length, 1); } p = (char *) _emalloc(length + 1 ZEND_FILE_LINE_RELAY_CC ZEND_FILE_LINE_ORIG_RELAY_CC); if (UNEXPECTED(p == NULL)) { return p; } memcpy(p, s, length); p[length] = 0; return p; } ZEND_API char* ZEND_FASTCALL zend_strndup(const char *s, size_t length) { char *p; if (UNEXPECTED(length + 1 == 0)) { zend_error_noreturn(E_ERROR, "Possible integer overflow in memory allocation (%zu * %zu + %zu)", 1, length, 1); } p = (char *) malloc(length + 1); if (UNEXPECTED(p == NULL)) { return p; } if (EXPECTED(length)) { memcpy(p, s, length); } p[length] = 0; return p; } ZEND_API int zend_set_memory_limit(size_t memory_limit) { #if ZEND_MM_LIMIT AG(mm_heap)->limit = (memory_limit >= ZEND_MM_CHUNK_SIZE) ? memory_limit : ZEND_MM_CHUNK_SIZE; #endif return SUCCESS; } ZEND_API size_t zend_memory_usage(int real_usage) { #if ZEND_MM_STAT if (real_usage) { return AG(mm_heap)->real_size; } else { size_t usage = AG(mm_heap)->size; return usage; } #endif return 0; } ZEND_API size_t zend_memory_peak_usage(int real_usage) { #if ZEND_MM_STAT if (real_usage) { return AG(mm_heap)->real_peak; } else { return AG(mm_heap)->peak; } #endif return 0; } ZEND_API void shutdown_memory_manager(int silent, int full_shutdown) { zend_mm_shutdown(AG(mm_heap), full_shutdown, silent); } static void alloc_globals_ctor(zend_alloc_globals *alloc_globals) { #if ZEND_MM_CUSTOM char *tmp = getenv("USE_ZEND_ALLOC"); if (tmp && !zend_atoi(tmp, 0)) { alloc_globals->mm_heap = malloc(sizeof(zend_mm_heap)); memset(alloc_globals->mm_heap, 0, sizeof(zend_mm_heap)); alloc_globals->mm_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_STD; alloc_globals->mm_heap->custom_heap.std._malloc = malloc; alloc_globals->mm_heap->custom_heap.std._free = free; alloc_globals->mm_heap->custom_heap.std._realloc = realloc; return; } #endif #ifdef MAP_HUGETLB tmp = getenv("USE_ZEND_ALLOC_HUGE_PAGES"); if (tmp && zend_atoi(tmp, 0)) { zend_mm_use_huge_pages = 1; } #endif ZEND_TSRMLS_CACHE_UPDATE(); alloc_globals->mm_heap = zend_mm_init(); } #ifdef ZTS static void alloc_globals_dtor(zend_alloc_globals *alloc_globals) { zend_mm_shutdown(alloc_globals->mm_heap, 1, 1); } #endif ZEND_API void start_memory_manager(void) { #ifdef ZTS ts_allocate_id(&alloc_globals_id, sizeof(zend_alloc_globals), (ts_allocate_ctor) alloc_globals_ctor, (ts_allocate_dtor) alloc_globals_dtor); #else alloc_globals_ctor(&alloc_globals); #endif #ifndef _WIN32 # if defined(_SC_PAGESIZE) REAL_PAGE_SIZE = sysconf(_SC_PAGESIZE); # elif defined(_SC_PAGE_SIZE) REAL_PAGE_SIZE = sysconf(_SC_PAGE_SIZE); # endif #endif } ZEND_API zend_mm_heap *zend_mm_set_heap(zend_mm_heap *new_heap) { zend_mm_heap *old_heap; old_heap = AG(mm_heap); AG(mm_heap) = (zend_mm_heap*)new_heap; return (zend_mm_heap*)old_heap; } ZEND_API zend_mm_heap *zend_mm_get_heap(void) { return AG(mm_heap); } ZEND_API int zend_mm_is_custom_heap(zend_mm_heap *new_heap) { #if ZEND_MM_CUSTOM return AG(mm_heap)->use_custom_heap; #else return 0; #endif } ZEND_API void zend_mm_set_custom_handlers(zend_mm_heap *heap, void* (*_malloc)(size_t), void (*_free)(void*), void* (*_realloc)(void*, size_t)) { #if ZEND_MM_CUSTOM zend_mm_heap *_heap = (zend_mm_heap*)heap; _heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_STD; _heap->custom_heap.std._malloc = _malloc; _heap->custom_heap.std._free = _free; _heap->custom_heap.std._realloc = _realloc; #endif } ZEND_API void zend_mm_get_custom_handlers(zend_mm_heap *heap, void* (**_malloc)(size_t), void (**_free)(void*), void* (**_realloc)(void*, size_t)) { #if ZEND_MM_CUSTOM zend_mm_heap *_heap = (zend_mm_heap*)heap; if (heap->use_custom_heap) { *_malloc = _heap->custom_heap.std._malloc; *_free = _heap->custom_heap.std._free; *_realloc = _heap->custom_heap.std._realloc; } else { *_malloc = NULL; *_free = NULL; *_realloc = NULL; } #else *_malloc = NULL; *_free = NULL; *_realloc = NULL; #endif } #if ZEND_DEBUG ZEND_API void zend_mm_set_custom_debug_handlers(zend_mm_heap *heap, void* (*_malloc)(size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC), void (*_free)(void* ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC), void* (*_realloc)(void*, size_t ZEND_FILE_LINE_DC ZEND_FILE_LINE_ORIG_DC)) { #if ZEND_MM_CUSTOM zend_mm_heap *_heap = (zend_mm_heap*)heap; _heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_DEBUG; _heap->custom_heap.debug._malloc = _malloc; _heap->custom_heap.debug._free = _free; _heap->custom_heap.debug._realloc = _realloc; #endif } #endif ZEND_API zend_mm_storage *zend_mm_get_storage(zend_mm_heap *heap) { #if ZEND_MM_STORAGE return heap->storage; #else return NULL #endif } ZEND_API zend_mm_heap *zend_mm_startup(void) { return zend_mm_init(); } ZEND_API zend_mm_heap *zend_mm_startup_ex(const zend_mm_handlers *handlers, void *data, size_t data_size) { #if ZEND_MM_STORAGE zend_mm_storage tmp_storage, *storage; zend_mm_chunk *chunk; zend_mm_heap *heap; memcpy((zend_mm_handlers*)&tmp_storage.handlers, handlers, sizeof(zend_mm_handlers)); tmp_storage.data = data; chunk = (zend_mm_chunk*)handlers->chunk_alloc(&tmp_storage, ZEND_MM_CHUNK_SIZE, ZEND_MM_CHUNK_SIZE); if (UNEXPECTED(chunk == NULL)) { #if ZEND_MM_ERROR #ifdef _WIN32 stderr_last_error("Can't initialize heap"); #else fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno)); #endif #endif return NULL; } heap = &chunk->heap_slot; chunk->heap = heap; chunk->next = chunk; chunk->prev = chunk; chunk->free_pages = ZEND_MM_PAGES - ZEND_MM_FIRST_PAGE; chunk->free_tail = ZEND_MM_FIRST_PAGE; chunk->num = 0; chunk->free_map[0] = (Z_L(1) << ZEND_MM_FIRST_PAGE) - 1; chunk->map[0] = ZEND_MM_LRUN(ZEND_MM_FIRST_PAGE); heap->main_chunk = chunk; heap->cached_chunks = NULL; heap->chunks_count = 1; heap->peak_chunks_count = 1; heap->cached_chunks_count = 0; heap->avg_chunks_count = 1.0; #if ZEND_MM_STAT || ZEND_MM_LIMIT heap->real_size = ZEND_MM_CHUNK_SIZE; #endif #if ZEND_MM_STAT heap->real_peak = ZEND_MM_CHUNK_SIZE; heap->size = 0; heap->peak = 0; #endif #if ZEND_MM_LIMIT heap->limit = (Z_L(-1) >> Z_L(1)); heap->overflow = 0; #endif #if ZEND_MM_CUSTOM heap->use_custom_heap = 0; #endif heap->storage = &tmp_storage; heap->huge_list = NULL; memset(heap->free_slot, 0, sizeof(heap->free_slot)); storage = _zend_mm_alloc(heap, sizeof(zend_mm_storage) + data_size ZEND_FILE_LINE_CC ZEND_FILE_LINE_CC); if (!storage) { handlers->chunk_free(&tmp_storage, chunk, ZEND_MM_CHUNK_SIZE); #if ZEND_MM_ERROR #ifdef _WIN32 stderr_last_error("Can't initialize heap"); #else fprintf(stderr, "\nCan't initialize heap: [%d] %s\n", errno, strerror(errno)); #endif #endif return NULL; } memcpy(storage, &tmp_storage, sizeof(zend_mm_storage)); if (data) { storage->data = (void*)(((char*)storage + sizeof(zend_mm_storage))); memcpy(storage->data, data, data_size); } heap->storage = storage; return heap; #else return NULL; #endif } static ZEND_COLD ZEND_NORETURN void zend_out_of_memory(void) { fprintf(stderr, "Out of memory\n"); exit(1); } ZEND_API void * __zend_malloc(size_t len) { void *tmp = malloc(len); if (EXPECTED(tmp)) { return tmp; } zend_out_of_memory(); } ZEND_API void * __zend_calloc(size_t nmemb, size_t len) { void *tmp = _safe_malloc(nmemb, len, 0); memset(tmp, 0, nmemb * len); return tmp; } ZEND_API void * __zend_realloc(void *p, size_t len) { p = realloc(p, len); if (EXPECTED(p)) { return p; } zend_out_of_memory(); } /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5262_0
crossvul-cpp_data_bad_3179_0
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * undo.c: multi level undo facility * * The saved lines are stored in a list of lists (one for each buffer): * * b_u_oldhead------------------------------------------------+ * | * V * +--------------+ +--------------+ +--------------+ * b_u_newhead--->| u_header | | u_header | | u_header | * | uh_next------>| uh_next------>| uh_next---->NULL * NULL<--------uh_prev |<---------uh_prev |<---------uh_prev | * | uh_entry | | uh_entry | | uh_entry | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ +--------------+ +--------------+ * | u_entry | | u_entry | | u_entry | * | ue_next | | ue_next | | ue_next | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ NULL NULL * | u_entry | * | ue_next | * +--------|-----+ * | * V * etc. * * Each u_entry list contains the information for one undo or redo. * curbuf->b_u_curhead points to the header of the last undo (the next redo), * or is NULL if nothing has been undone (end of the branch). * * For keeping alternate undo/redo branches the uh_alt field is used. Thus at * each point in the list a branch may appear for an alternate to redo. The * uh_seq field is numbered sequentially to be able to find a newer or older * branch. * * +---------------+ +---------------+ * b_u_oldhead --->| u_header | | u_header | * | uh_alt_next ---->| uh_alt_next ----> NULL * NULL <----- uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next | | uh_alt_next | * b_u_newhead --->| uh_alt_prev | | uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * NULL +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next ---->| uh_alt_next | * | uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * etc. etc. * * * All data is allocated and will all be freed when the buffer is unloaded. */ /* Uncomment the next line for including the u_check() function. This warns * for errors in the debug information. */ /* #define U_DEBUG 1 */ #define UH_MAGIC 0x18dade /* value for uh_magic when in use */ #define UE_MAGIC 0xabc123 /* value for ue_magic when in use */ /* Size of buffer used for encryption. */ #define CRYPT_BUF_SIZE 8192 #include "vim.h" /* Structure passed around between functions. * Avoids passing cryptstate_T when encryption not available. */ typedef struct { buf_T *bi_buf; FILE *bi_fp; #ifdef FEAT_CRYPT cryptstate_T *bi_state; char_u *bi_buffer; /* CRYPT_BUF_SIZE, NULL when not buffering */ size_t bi_used; /* bytes written to/read from bi_buffer */ size_t bi_avail; /* bytes available in bi_buffer */ #endif } bufinfo_T; static long get_undolevel(void); static void u_unch_branch(u_header_T *uhp); static u_entry_T *u_get_headentry(void); static void u_getbot(void); static void u_doit(int count); static void u_undoredo(int undo); static void u_undo_end(int did_undo, int absolute); static void u_add_time(char_u *buf, size_t buflen, time_t tt); static void u_freeheader(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freebranch(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentries(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentry(u_entry_T *, long); #ifdef FEAT_PERSISTENT_UNDO static void corruption_error(char *mesg, char_u *file_name); static void u_free_uhp(u_header_T *uhp); static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len); # ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi); # endif static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len); static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len); static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp); static int undo_read_4c(bufinfo_T *bi); static int undo_read_2c(bufinfo_T *bi); static int undo_read_byte(bufinfo_T *bi); static time_t undo_read_time(bufinfo_T *bi); static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size); static char_u *read_string_decrypt(bufinfo_T *bi, int len); static int serialize_header(bufinfo_T *bi, char_u *hash); static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp); static u_header_T *unserialize_uhp(bufinfo_T *bi, char_u *file_name); static int serialize_uep(bufinfo_T *bi, u_entry_T *uep); static u_entry_T *unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name); static void serialize_pos(bufinfo_T *bi, pos_T pos); static void unserialize_pos(bufinfo_T *bi, pos_T *pos); static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); #endif #define U_ALLOC_LINE(size) lalloc((long_u)(size), FALSE) static char_u *u_save_line(linenr_T); /* used in undo_end() to report number of added and deleted lines */ static long u_newcount, u_oldcount; /* * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember * the action that "u" should do. */ static int undo_undoes = FALSE; static int lastmark = 0; #if defined(U_DEBUG) || defined(PROTO) /* * Check the undo structures for being valid. Print a warning when something * looks wrong. */ static int seen_b_u_curhead; static int seen_b_u_newhead; static int header_count; static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) { u_entry_T *uep; if (uhp == NULL) return; ++header_count; if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1) { EMSG("b_u_curhead found twice (looping?)"); return; } if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1) { EMSG("b_u_newhead found twice (looping?)"); return; } if (uhp->uh_magic != UH_MAGIC) EMSG("uh_magic wrong (may be using freed memory)"); else { /* Check pointers back are correct. */ if (uhp->uh_next.ptr != exp_uh_next) { EMSG("uh_next wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_next, uhp->uh_next.ptr); } if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev) { EMSG("uh_alt_prev wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_alt_prev, uhp->uh_alt_prev.ptr); } /* Check the undo tree at this header. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { if (uep->ue_magic != UE_MAGIC) { EMSG("ue_magic wrong (may be using freed memory)"); break; } } /* Check the next alt tree. */ u_check_tree(uhp->uh_alt_next.ptr, uhp->uh_next.ptr, uhp); /* Check the next header in this branch. */ u_check_tree(uhp->uh_prev.ptr, uhp, NULL); } } static void u_check(int newhead_may_be_NULL) { seen_b_u_newhead = 0; seen_b_u_curhead = 0; header_count = 0; u_check_tree(curbuf->b_u_oldhead, NULL, NULL); if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL)) EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0) EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); if (header_count != curbuf->b_u_numhead) { EMSG("b_u_numhead invalid"); smsg((char_u *)"expected: %ld, actual: %ld", (long)header_count, (long)curbuf->b_u_numhead); } } #endif /* * Save the current line for both the "u" and "U" command. * Careful: may trigger autocommands that reload the buffer. * Returns OK or FAIL. */ int u_save_cursor(void) { return (u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + 1))); } /* * Save the lines between "top" and "bot" for both the "u" and "U" command. * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_save(linenr_T top, linenr_T bot) { if (undo_off) return OK; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) return FALSE; /* rely on caller to do error messages */ if (top + 2 == bot) u_saveline((linenr_T)(top + 1)); return (u_savecommon(top, bot, (linenr_T)0, FALSE)); } /* * Save the line "lnum" (used by ":s" and "~" command). * The line is replaced, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savesub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE)); } /* * A new line is inserted before line "lnum" (used by :s command). * The line is inserted, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_inssub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum, lnum + 1, FALSE)); } /* * Save the lines "lnum" - "lnum" + nlines (used by delete command). * The lines are deleted, so the new bottom line is lnum, unless the buffer * becomes empty. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savedel(linenr_T lnum, long nlines) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + nlines, nlines == curbuf->b_ml.ml_line_count ? 2 : lnum, FALSE)); } /* * Return TRUE when undo is allowed. Otherwise give an error message and * return FALSE. */ int undo_allowed(void) { /* Don't allow changes when 'modifiable' is off. */ if (!curbuf->b_p_ma) { EMSG(_(e_modifiable)); return FALSE; } #ifdef HAVE_SANDBOX /* In the sandbox it's not allowed to change the text. */ if (sandbox != 0) { EMSG(_(e_sandbox)); return FALSE; } #endif /* Don't allow changes in the buffer while editing the cmdline. The * caller of getcmdline() may get confused. */ if (textlock != 0) { EMSG(_(e_secure)); return FALSE; } return TRUE; } /* * Get the undolevle value for the current buffer. */ static long get_undolevel(void) { if (curbuf->b_p_ul == NO_LOCAL_UNDOLEVEL) return p_ul; return curbuf->b_p_ul; } /* * Common code for various ways to save text before a change. * "top" is the line above the first changed line. * "bot" is the line below the last changed line. * "newbot" is the new bottom line. Use zero when not known. * "reload" is TRUE when saving for a buffer reload. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savecommon( linenr_T top, linenr_T bot, linenr_T newbot, int reload) { linenr_T lnum; long i; u_header_T *uhp; u_header_T *old_curhead; u_entry_T *uep; u_entry_T *prev_uep; long size; if (!reload) { /* When making changes is not allowed return FAIL. It's a crude way * to make all change commands fail. */ if (!undo_allowed()) return FAIL; #ifdef FEAT_NETBEANS_INTG /* * Netbeans defines areas that cannot be modified. Bail out here when * trying to change text in a guarded area. */ if (netbeans_active()) { if (netbeans_is_guarded(top, bot)) { EMSG(_(e_guarded)); return FAIL; } if (curbuf->b_p_ro) { EMSG(_(e_nbreadonly)); return FAIL; } } #endif #ifdef FEAT_AUTOCMD /* * Saving text for undo means we are going to make a change. Give a * warning for a read-only file before making the change, so that the * FileChangedRO event can replace the buffer with a read-write version * (e.g., obtained from a source control system). */ change_warning(0); if (bot > curbuf->b_ml.ml_line_count + 1) { /* This happens when the FileChangedRO autocommand changes the * file in a way it becomes shorter. */ EMSG(_("E881: Line count changed unexpectedly")); return FAIL; } #endif } #ifdef U_DEBUG u_check(FALSE); #endif size = bot - top - 1; /* * If curbuf->b_u_synced == TRUE make a new header. */ if (curbuf->b_u_synced) { #ifdef FEAT_JUMPLIST /* Need to create new entry in b_changelist. */ curbuf->b_new_change = TRUE; #endif if (get_undolevel() >= 0) { /* * Make a new header entry. Do this first so that we don't mess * up the undo info when out of memory. */ uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) goto nomem; #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif } else uhp = NULL; /* * If we undid more than we redid, move the entry lists before and * including curbuf->b_u_curhead to an alternate branch. */ old_curhead = curbuf->b_u_curhead; if (old_curhead != NULL) { curbuf->b_u_newhead = old_curhead->uh_next.ptr; curbuf->b_u_curhead = NULL; } /* * free headers to keep the size right */ while (curbuf->b_u_numhead > get_undolevel() && curbuf->b_u_oldhead != NULL) { u_header_T *uhfree = curbuf->b_u_oldhead; if (uhfree == old_curhead) /* Can't reconnect the branch, delete all of it. */ u_freebranch(curbuf, uhfree, &old_curhead); else if (uhfree->uh_alt_next.ptr == NULL) /* There is no branch, only free one header. */ u_freeheader(curbuf, uhfree, &old_curhead); else { /* Free the oldest alternate branch as a whole. */ while (uhfree->uh_alt_next.ptr != NULL) uhfree = uhfree->uh_alt_next.ptr; u_freebranch(curbuf, uhfree, &old_curhead); } #ifdef U_DEBUG u_check(TRUE); #endif } if (uhp == NULL) /* no undo at all */ { if (old_curhead != NULL) u_freebranch(curbuf, old_curhead, NULL); curbuf->b_u_synced = FALSE; return OK; } uhp->uh_prev.ptr = NULL; uhp->uh_next.ptr = curbuf->b_u_newhead; uhp->uh_alt_next.ptr = old_curhead; if (old_curhead != NULL) { uhp->uh_alt_prev.ptr = old_curhead->uh_alt_prev.ptr; if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = uhp; old_curhead->uh_alt_prev.ptr = uhp; if (curbuf->b_u_oldhead == old_curhead) curbuf->b_u_oldhead = uhp; } else uhp->uh_alt_prev.ptr = NULL; if (curbuf->b_u_newhead != NULL) curbuf->b_u_newhead->uh_prev.ptr = uhp; uhp->uh_seq = ++curbuf->b_u_seq_last; curbuf->b_u_seq_cur = uhp->uh_seq; uhp->uh_time = vim_time(); uhp->uh_save_nr = 0; curbuf->b_u_time_cur = uhp->uh_time + 1; uhp->uh_walk = 0; uhp->uh_entry = NULL; uhp->uh_getbot_entry = NULL; uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */ #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curwin->w_cursor.coladd > 0) uhp->uh_cursor_vcol = getviscol(); else uhp->uh_cursor_vcol = -1; #endif /* save changed and buffer empty flag for undo */ uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); /* save named marks and Visual marks for undo */ mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); uhp->uh_visual = curbuf->b_visual; curbuf->b_u_newhead = uhp; if (curbuf->b_u_oldhead == NULL) curbuf->b_u_oldhead = uhp; ++curbuf->b_u_numhead; } else { if (get_undolevel() < 0) /* no undo at all */ return OK; /* * When saving a single line, and it has been saved just before, it * doesn't make sense saving it again. Saves a lot of memory when * making lots of changes inside the same line. * This is only possible if the previous change didn't increase or * decrease the number of lines. * Check the ten last changes. More doesn't make sense and takes too * long. */ if (size == 1) { uep = u_get_headentry(); prev_uep = NULL; for (i = 0; i < 10; ++i) { if (uep == NULL) break; /* If lines have been inserted/deleted we give up. * Also when the line was included in a multi-line save. */ if ((curbuf->b_u_newhead->uh_getbot_entry != uep ? (uep->ue_top + uep->ue_size + 1 != (uep->ue_bot == 0 ? curbuf->b_ml.ml_line_count + 1 : uep->ue_bot)) : uep->ue_lcount != curbuf->b_ml.ml_line_count) || (uep->ue_size > 1 && top >= uep->ue_top && top + 2 <= uep->ue_top + uep->ue_size + 1)) break; /* If it's the same line we can skip saving it again. */ if (uep->ue_size == 1 && uep->ue_top == top) { if (i > 0) { /* It's not the last entry: get ue_bot for the last * entry now. Following deleted/inserted lines go to * the re-used entry. */ u_getbot(); curbuf->b_u_synced = FALSE; /* Move the found entry to become the last entry. The * order of undo/redo doesn't matter for the entries * we move it over, since they don't change the line * count and don't include this line. It does matter * for the found entry if the line count is changed by * the executed command. */ prev_uep->ue_next = uep->ue_next; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; } /* The executed command may change the line count. */ if (newbot != 0) uep->ue_bot = newbot; else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } return OK; } prev_uep = uep; uep = uep->ue_next; } } /* find line number for ue_bot for previous u_save() */ u_getbot(); } #if !defined(UNIX) && !defined(WIN32) /* * With Amiga we can't handle big undo's, because * then u_alloc_line would have to allocate a block larger than 32K */ if (size >= 8000) goto nomem; #endif /* * add lines in front of entry list */ uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) goto nomem; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_size = size; uep->ue_top = top; if (newbot != 0) uep->ue_bot = newbot; /* * Use 0 for ue_bot if bot is below last line. * Otherwise we have to compute ue_bot later. */ else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } if (size > 0) { if ((uep->ue_array = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * size)) == NULL) { u_freeentry(uep, 0L); goto nomem; } for (i = 0, lnum = top + 1; i < size; ++i) { fast_breakcheck(); if (got_int) { u_freeentry(uep, i); return FAIL; } if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL) { u_freeentry(uep, i); goto nomem; } } } else uep->ue_array = NULL; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; curbuf->b_u_synced = FALSE; undo_undoes = FALSE; #ifdef U_DEBUG u_check(FALSE); #endif return OK; nomem: msg_silent = 0; /* must display the prompt */ if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE) == 'y') { undo_off = TRUE; /* will be reset when character typed */ return OK; } do_outofmem_msg((long_u)0); return FAIL; } #if defined(FEAT_PERSISTENT_UNDO) || defined(PROTO) # define UF_START_MAGIC "Vim\237UnDo\345" /* magic at start of undofile */ # define UF_START_MAGIC_LEN 9 # define UF_HEADER_MAGIC 0x5fd0 /* magic at start of header */ # define UF_HEADER_END_MAGIC 0xe7aa /* magic after last header */ # define UF_ENTRY_MAGIC 0xf518 /* magic at start of entry */ # define UF_ENTRY_END_MAGIC 0x3581 /* magic after last entry */ # define UF_VERSION 2 /* 2-byte undofile version number */ # define UF_VERSION_CRYPT 0x8002 /* idem, encrypted */ /* extra fields for header */ # define UF_LAST_SAVE_NR 1 /* extra fields for uhp */ # define UHP_SAVE_NR 1 static char_u e_not_open[] = N_("E828: Cannot open undo file for writing: %s"); /* * Compute the hash for the current buffer text into hash[UNDO_HASH_SIZE]. */ void u_compute_hash(char_u *hash) { context_sha256_T ctx; linenr_T lnum; char_u *p; sha256_start(&ctx); for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { p = ml_get(lnum); sha256_update(&ctx, p, (UINT32_T)(STRLEN(p) + 1)); } sha256_finish(&ctx, hash); } /* * Return an allocated string of the full path of the target undofile. * When "reading" is TRUE find the file to read, go over all directories in * 'undodir'. * When "reading" is FALSE use the first name where the directory exists. * Returns NULL when there is no place to write or no file to read. */ char_u * u_get_undo_file_name(char_u *buf_ffname, int reading) { char_u *dirp; char_u dir_name[IOSIZE + 1]; char_u *munged_name = NULL; char_u *undo_file_name = NULL; int dir_len; char_u *p; stat_T st; char_u *ffname = buf_ffname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif if (ffname == NULL) return NULL; #ifdef HAVE_READLINK /* Expand symlink in the file name, so that we put the undo file with the * actual file instead of with the symlink. */ if (resolve_symlink(ffname, fname_buf) == OK) ffname = fname_buf; #endif /* Loop over 'undodir'. When reading find the first file that exists. * When not reading use the first directory that exists or ".". */ dirp = p_udir; while (*dirp != NUL) { dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ","); if (dir_len == 1 && dir_name[0] == '.') { /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ undo_file_name = vim_strnsave(ffname, (int)(STRLEN(ffname) + 5)); if (undo_file_name == NULL) break; p = gettail(undo_file_name); #ifdef VMS /* VMS can not handle more than one dot in the filenames * use "dir/name" -> "dir/_un_name" - add _un_ * at the beginning to keep the extension */ mch_memmove(p + 4, p, STRLEN(p) + 1); mch_memmove(p, "_un_", 4); #else /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ mch_memmove(p + 1, p, STRLEN(p) + 1); *p = '.'; STRCAT(p, ".un~"); #endif } else { dir_name[dir_len] = NUL; if (mch_isdir(dir_name)) { if (munged_name == NULL) { munged_name = vim_strsave(ffname); if (munged_name == NULL) return NULL; for (p = munged_name; *p != NUL; mb_ptr_adv(p)) if (vim_ispathsep(*p)) *p = '%'; } undo_file_name = concat_fnames(dir_name, munged_name, TRUE); } } /* When reading check if the file exists. */ if (undo_file_name != NULL && (!reading || mch_stat((char *)undo_file_name, &st) >= 0)) break; vim_free(undo_file_name); undo_file_name = NULL; } vim_free(munged_name); return undo_file_name; } static void corruption_error(char *mesg, char_u *file_name) { EMSG3(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); } static void u_free_uhp(u_header_T *uhp) { u_entry_T *nuep; u_entry_T *uep; uep = uhp->uh_entry; while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } vim_free(uhp); } /* * Write a sequence of bytes to the undo file. * Buffers and encrypts as needed. * Returns OK or FAIL. */ static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { size_t len_todo = len; char_u *p = ptr; while (bi->bi_used + len_todo >= CRYPT_BUF_SIZE) { size_t n = CRYPT_BUF_SIZE - bi->bi_used; mch_memmove(bi->bi_buffer + bi->bi_used, p, n); len_todo -= n; p += n; bi->bi_used = CRYPT_BUF_SIZE; if (undo_flush(bi) == FAIL) return FAIL; } if (len_todo > 0) { mch_memmove(bi->bi_buffer + bi->bi_used, p, len_todo); bi->bi_used += len_todo; } return OK; } #endif if (fwrite(ptr, len, (size_t)1, bi->bi_fp) != 1) return FAIL; return OK; } #ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi) { if (bi->bi_buffer != NULL && bi->bi_used > 0) { crypt_encode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_used); if (fwrite(bi->bi_buffer, bi->bi_used, (size_t)1, bi->bi_fp) != 1) return FAIL; bi->bi_used = 0; } return OK; } #endif /* * Write "ptr[len]" and crypt the bytes when needed. * Returns OK or FAIL. */ static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT char_u *copy; char_u small_buf[100]; size_t i; if (bi->bi_state != NULL && bi->bi_buffer == NULL) { /* crypting every piece of text separately */ if (len < 100) copy = small_buf; /* no malloc()/free() for short strings */ else { copy = lalloc(len, FALSE); if (copy == NULL) return 0; } crypt_encode(bi->bi_state, ptr, len, copy); i = fwrite(copy, len, (size_t)1, bi->bi_fp); if (copy != small_buf) vim_free(copy); return i == 1 ? OK : FAIL; } #endif return undo_write(bi, ptr, len); } /* * Write a number, MSB first, in "len" bytes. * Must match with undo_read_?c() functions. * Returns OK or FAIL. */ static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len) { char_u buf[8]; int i; int bufi = 0; for (i = len - 1; i >= 0; --i) buf[bufi++] = (char_u)(nr >> (i * 8)); return undo_write(bi, buf, (size_t)len); } /* * Write the pointer to an undo header. Instead of writing the pointer itself * we use the sequence number of the header. This is converted back to * pointers when reading. */ static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp) { undo_write_bytes(bi, (long_u)(uhp != NULL ? uhp->uh_seq : 0), 4); } static int undo_read_4c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[4]; int n; undo_read(bi, buf, (size_t)4); n = ((unsigned)buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; return n; } #endif return get4c(bi->bi_fp); } static int undo_read_2c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[2]; int n; undo_read(bi, buf, (size_t)2); n = (buf[0] << 8) + buf[1]; return n; } #endif return get2c(bi->bi_fp); } static int undo_read_byte(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[1]; undo_read(bi, buf, (size_t)1); return buf[0]; } #endif return getc(bi->bi_fp); } static time_t undo_read_time(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[8]; time_t n = 0; int i; undo_read(bi, buf, (size_t)8); for (i = 0; i < 8; ++i) n = (n << 8) + buf[i]; return n; } #endif return get8ctime(bi->bi_fp); } /* * Read "buffer[size]" from the undo file. * Return OK or FAIL. */ static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { int size_todo = (int)size; char_u *p = buffer; while (size_todo > 0) { size_t n; if (bi->bi_used >= bi->bi_avail) { n = fread(bi->bi_buffer, 1, (size_t)CRYPT_BUF_SIZE, bi->bi_fp); if (n == 0) { /* Error may be checked for only later. Fill with zeros, * so that the reader won't use garbage. */ vim_memset(p, 0, size_todo); return FAIL; } bi->bi_avail = n; bi->bi_used = 0; crypt_decode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_avail); } n = size_todo; if (n > bi->bi_avail - bi->bi_used) n = bi->bi_avail - bi->bi_used; mch_memmove(p, bi->bi_buffer + bi->bi_used, n); bi->bi_used += n; size_todo -= (int)n; p += n; } return OK; } #endif if (fread(buffer, (size_t)size, 1, bi->bi_fp) != 1) return FAIL; return OK; } /* * Read a string of length "len" from "bi->bi_fd". * "len" can be zero to allocate an empty line. * Decrypt the bytes if needed. * Append a NUL. * Returns a pointer to allocated memory or NULL for failure. */ static char_u * read_string_decrypt(bufinfo_T *bi, int len) { char_u *ptr = alloc((unsigned)len + 1); if (ptr != NULL) { if (len > 0 && undo_read(bi, ptr, len) == FAIL) { vim_free(ptr); return NULL; } ptr[len] = NUL; #ifdef FEAT_CRYPT if (bi->bi_state != NULL && bi->bi_buffer == NULL) crypt_decode_inplace(bi->bi_state, ptr, len); #endif } return ptr; } /* * Writes the (not encrypted) header and initializes encryption if needed. */ static int serialize_header(bufinfo_T *bi, char_u *hash) { int len; buf_T *buf = bi->bi_buf; FILE *fp = bi->bi_fp; char_u time_buf[8]; /* Start writing, first the magic marker and undo info version. */ if (fwrite(UF_START_MAGIC, (size_t)UF_START_MAGIC_LEN, (size_t)1, fp) != 1) return FAIL; /* If the buffer is encrypted then all text bytes following will be * encrypted. Numbers and other info is not crypted. */ #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) { char_u *header; int header_len; undo_write_bytes(bi, (long_u)UF_VERSION_CRYPT, 2); bi->bi_state = crypt_create_for_writing(crypt_get_method_nr(buf), buf->b_p_key, &header, &header_len); if (bi->bi_state == NULL) return FAIL; len = (int)fwrite(header, (size_t)header_len, (size_t)1, fp); vim_free(header); if (len != 1) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } if (crypt_whole_undofile(crypt_get_method_nr(buf))) { bi->bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi->bi_buffer == NULL) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } bi->bi_used = 0; } } else #endif undo_write_bytes(bi, (long_u)UF_VERSION, 2); /* Write a hash of the buffer text, so that we can verify it is still the * same when reading the buffer text. */ if (undo_write(bi, hash, (size_t)UNDO_HASH_SIZE) == FAIL) return FAIL; /* buffer-specific data */ undo_write_bytes(bi, (long_u)buf->b_ml.ml_line_count, 4); len = buf->b_u_line_ptr != NULL ? (int)STRLEN(buf->b_u_line_ptr) : 0; undo_write_bytes(bi, (long_u)len, 4); if (len > 0 && fwrite_crypt(bi, buf->b_u_line_ptr, (size_t)len) == FAIL) return FAIL; undo_write_bytes(bi, (long_u)buf->b_u_line_lnum, 4); undo_write_bytes(bi, (long_u)buf->b_u_line_colnr, 4); /* Undo structures header data */ put_header_ptr(bi, buf->b_u_oldhead); put_header_ptr(bi, buf->b_u_newhead); put_header_ptr(bi, buf->b_u_curhead); undo_write_bytes(bi, (long_u)buf->b_u_numhead, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_last, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_cur, 4); time_to_bytes(buf->b_u_time_cur, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UF_LAST_SAVE_NR, 1); undo_write_bytes(bi, (long_u)buf->b_u_save_nr_last, 4); undo_write_bytes(bi, 0, 1); /* end marker */ return OK; } static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp) { int i; u_entry_T *uep; char_u time_buf[8]; if (undo_write_bytes(bi, (long_u)UF_HEADER_MAGIC, 2) == FAIL) return FAIL; put_header_ptr(bi, uhp->uh_next.ptr); put_header_ptr(bi, uhp->uh_prev.ptr); put_header_ptr(bi, uhp->uh_alt_next.ptr); put_header_ptr(bi, uhp->uh_alt_prev.ptr); undo_write_bytes(bi, uhp->uh_seq, 4); serialize_pos(bi, uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)uhp->uh_cursor_vcol, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif undo_write_bytes(bi, (long_u)uhp->uh_flags, 2); /* Assume NMARKS will stay the same. */ for (i = 0; i < NMARKS; ++i) serialize_pos(bi, uhp->uh_namedm[i]); serialize_visualinfo(bi, &uhp->uh_visual); time_to_bytes(uhp->uh_time, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UHP_SAVE_NR, 1); undo_write_bytes(bi, (long_u)uhp->uh_save_nr, 4); undo_write_bytes(bi, 0, 1); /* end marker */ /* Write all the entries. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { undo_write_bytes(bi, (long_u)UF_ENTRY_MAGIC, 2); if (serialize_uep(bi, uep) == FAIL) return FAIL; } undo_write_bytes(bi, (long_u)UF_ENTRY_END_MAGIC, 2); return OK; } static u_header_T * unserialize_uhp(bufinfo_T *bi, char_u *file_name) { u_header_T *uhp; int i; u_entry_T *uep, *last_uep; int c; int error; uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) return NULL; vim_memset(uhp, 0, sizeof(u_header_T)); #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif uhp->uh_next.seq = undo_read_4c(bi); uhp->uh_prev.seq = undo_read_4c(bi); uhp->uh_alt_next.seq = undo_read_4c(bi); uhp->uh_alt_prev.seq = undo_read_4c(bi); uhp->uh_seq = undo_read_4c(bi); if (uhp->uh_seq <= 0) { corruption_error("uh_seq", file_name); vim_free(uhp); return NULL; } unserialize_pos(bi, &uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT uhp->uh_cursor_vcol = undo_read_4c(bi); #else (void)undo_read_4c(bi); #endif uhp->uh_flags = undo_read_2c(bi); for (i = 0; i < NMARKS; ++i) unserialize_pos(bi, &uhp->uh_namedm[i]); unserialize_visualinfo(bi, &uhp->uh_visual); uhp->uh_time = undo_read_time(bi); /* Optional fields. */ for (;;) { int len = undo_read_byte(bi); int what; if (len == 0) break; what = undo_read_byte(bi); switch (what) { case UHP_SAVE_NR: uhp->uh_save_nr = undo_read_4c(bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(bi); } } /* Unserialize the uep list. */ last_uep = NULL; while ((c = undo_read_2c(bi)) == UF_ENTRY_MAGIC) { error = FALSE; uep = unserialize_uep(bi, &error, file_name); if (last_uep == NULL) uhp->uh_entry = uep; else last_uep->ue_next = uep; last_uep = uep; if (uep == NULL || error) { u_free_uhp(uhp); return NULL; } } if (c != UF_ENTRY_END_MAGIC) { corruption_error("entry end", file_name); u_free_uhp(uhp); return NULL; } return uhp; } /* * Serialize "uep". */ static int serialize_uep( bufinfo_T *bi, u_entry_T *uep) { int i; size_t len; undo_write_bytes(bi, (long_u)uep->ue_top, 4); undo_write_bytes(bi, (long_u)uep->ue_bot, 4); undo_write_bytes(bi, (long_u)uep->ue_lcount, 4); undo_write_bytes(bi, (long_u)uep->ue_size, 4); for (i = 0; i < uep->ue_size; ++i) { len = STRLEN(uep->ue_array[i]); if (undo_write_bytes(bi, (long_u)len, 4) == FAIL) return FAIL; if (len > 0 && fwrite_crypt(bi, uep->ue_array[i], len) == FAIL) return FAIL; } return OK; } static u_entry_T * unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name) { int i; u_entry_T *uep; char_u **array; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = undo_read_4c(bi); uep->ue_bot = undo_read_4c(bi); uep->ue_lcount = undo_read_4c(bi); uep->ue_size = undo_read_4c(bi); if (uep->ue_size > 0) { array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } else array = NULL; uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = undo_read_4c(bi); if (line_len >= 0) line = read_string_decrypt(bi, line_len); else { line = NULL; corruption_error("line length", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; } /* * Serialize "pos". */ static void serialize_pos(bufinfo_T *bi, pos_T pos) { undo_write_bytes(bi, (long_u)pos.lnum, 4); undo_write_bytes(bi, (long_u)pos.col, 4); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)pos.coladd, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif } /* * Unserialize the pos_T at the current position. */ static void unserialize_pos(bufinfo_T *bi, pos_T *pos) { pos->lnum = undo_read_4c(bi); if (pos->lnum < 0) pos->lnum = 0; pos->col = undo_read_4c(bi); if (pos->col < 0) pos->col = 0; #ifdef FEAT_VIRTUALEDIT pos->coladd = undo_read_4c(bi); if (pos->coladd < 0) pos->coladd = 0; #else (void)undo_read_4c(bi); #endif } /* * Serialize "info". */ static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { serialize_pos(bi, info->vi_start); serialize_pos(bi, info->vi_end); undo_write_bytes(bi, (long_u)info->vi_mode, 4); undo_write_bytes(bi, (long_u)info->vi_curswant, 4); } /* * Unserialize the visualinfo_T at the current position. */ static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { unserialize_pos(bi, &info->vi_start); unserialize_pos(bi, &info->vi_end); info->vi_mode = undo_read_4c(bi); info->vi_curswant = undo_read_4c(bi); } /* * Write the undo tree in an undo file. * When "name" is not NULL, use it as the name of the undo file. * Otherwise use buf->b_ffname to generate the undo file name. * "buf" must never be null, buf->b_ffname is used to obtain the original file * permissions. * "forceit" is TRUE for ":wundo!", FALSE otherwise. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_write_undo( char_u *name, int forceit, buf_T *buf, char_u *hash) { u_header_T *uhp; char_u *file_name; int mark; #ifdef U_DEBUG int headers_written = 0; #endif int fd; FILE *fp = NULL; int perm; int write_ok = FALSE; #ifdef UNIX int st_old_valid = FALSE; stat_T st_old; stat_T st_new; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(buf->b_ffname, FALSE); if (file_name == NULL) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *) _("Cannot write undo file in any directory in 'undodir'")); verbose_leave(); } return; } } else file_name = name; /* * Decide about the permission to use for the undo file. If the buffer * has a name use the permission of the original file. Otherwise only * allow the user to access the undo file. */ perm = 0600; if (buf->b_ffname != NULL) { #ifdef UNIX if (mch_stat((char *)buf->b_ffname, &st_old) >= 0) { perm = st_old.st_mode; st_old_valid = TRUE; } #else perm = mch_getperm(buf->b_ffname); if (perm < 0) perm = 0600; #endif } /* strip any s-bit and executable bit */ perm = perm & 0666; /* If the undo file already exists, verify that it actually is an undo * file, and delete it. */ if (mch_getperm(file_name) >= 0) { if (name == NULL || !forceit) { /* Check we can read it and it's an undo file. */ fd = mch_open((char *)file_name, O_RDONLY|O_EXTRA, 0); if (fd < 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite with undo file, cannot read: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } else { char_u mbuf[UF_START_MAGIC_LEN]; int len; len = read_eintr(fd, mbuf, UF_START_MAGIC_LEN); close(fd); if (len < UF_START_MAGIC_LEN || memcmp(mbuf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite, this is not an undo file: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } } } mch_remove(file_name); } /* If there is no undo information at all, quit here after deleting any * existing undo file. */ if (buf->b_u_numhead == 0 && buf->b_u_line_ptr == NULL) { if (p_verbose > 0) verb_msg((char_u *)_("Skipping undo file write, nothing to undo")); goto theend; } fd = mch_open((char *)file_name, O_CREAT|O_EXTRA|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) { EMSG2(_(e_not_open), file_name); goto theend; } (void)mch_setperm(file_name, perm); if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Writing undo file: %s"), file_name); verbose_leave(); } #ifdef U_DEBUG /* Check there is no problem in undo info before writing. */ u_check(FALSE); #endif #ifdef UNIX /* * Try to set the group of the undo file same as the original file. If * this fails, set the protection bits for the group same as the * protection bits for others. */ if (st_old_valid && mch_stat((char *)file_name, &st_new) >= 0 && st_new.st_gid != st_old.st_gid # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ && fchown(fd, (uid_t)-1, st_old.st_gid) != 0 # endif ) mch_setperm(file_name, (perm & 0707) | ((perm & 07) << 3)); # if defined(HAVE_SELINUX) || defined(HAVE_SMACK) if (buf->b_ffname != NULL) mch_copy_sec(buf->b_ffname, file_name); # endif #endif fp = fdopen(fd, "w"); if (fp == NULL) { EMSG2(_(e_not_open), file_name); close(fd); mch_remove(file_name); goto theend; } /* Undo must be synced. */ u_sync(TRUE); /* * Write the header. Initializes encryption, if enabled. */ bi.bi_buf = buf; bi.bi_fp = fp; if (serialize_header(&bi, hash) == FAIL) goto write_error; /* * Iteratively serialize UHPs and their UEPs from the top down. */ mark = ++lastmark; uhp = buf->b_u_oldhead; while (uhp != NULL) { /* Serialize current UHP if we haven't seen it */ if (uhp->uh_walk != mark) { uhp->uh_walk = mark; #ifdef U_DEBUG ++headers_written; #endif if (serialize_uhp(&bi, uhp) == FAIL) goto write_error; } /* Now walk through the tree - algorithm from undo_time(). */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != mark) uhp = uhp->uh_next.ptr; else if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } if (undo_write_bytes(&bi, (long_u)UF_HEADER_END_MAGIC, 2) == OK) write_ok = TRUE; #ifdef U_DEBUG if (headers_written != buf->b_u_numhead) { EMSGN("Written %ld headers, ...", headers_written); EMSGN("... but numhead is %ld", buf->b_u_numhead); } #endif #ifdef FEAT_CRYPT if (bi.bi_state != NULL && undo_flush(&bi) == FAIL) write_ok = FALSE; #endif write_error: fclose(fp); if (!write_ok) EMSG2(_("E829: write error in undo file: %s"), file_name); #if defined(MACOS_CLASSIC) || defined(WIN3264) /* Copy file attributes; for systems where this can only be done after * closing the file. */ if (buf->b_ffname != NULL) (void)mch_copy_file_attribute(buf->b_ffname, file_name); #endif #ifdef HAVE_ACL if (buf->b_ffname != NULL) { vim_acl_T acl; /* For systems that support ACL: get the ACL from the original file. */ acl = mch_get_acl(buf->b_ffname); mch_set_acl(file_name, acl); mch_free_acl(acl); } #endif theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (file_name != name) vim_free(file_name); } /* * Load the undo tree from an undo file. * If "name" is not NULL use it as the undo file name. This also means being * a bit more verbose. * Otherwise use curbuf->b_ffname to generate the undo file name. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_read_undo(char_u *name, char_u *hash, char_u *orig_name) { char_u *file_name; FILE *fp; long version, str_len; char_u *line_ptr = NULL; linenr_T line_lnum; colnr_T line_colnr; linenr_T line_count; long num_head = 0; long old_header_seq, new_header_seq, cur_header_seq; long seq_last, seq_cur; long last_save_nr = 0; short old_idx = -1, new_idx = -1, cur_idx = -1; long num_read_uhps = 0; time_t seq_time; int i, j; int c; u_header_T *uhp; u_header_T **uhp_table = NULL; char_u read_hash[UNDO_HASH_SIZE]; char_u magic_buf[UF_START_MAGIC_LEN]; #ifdef U_DEBUG int *uhp_table_used; #endif #ifdef UNIX stat_T st_orig; stat_T st_undo; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(curbuf->b_ffname, TRUE); if (file_name == NULL) return; #ifdef UNIX /* For safety we only read an undo file if the owner is equal to the * owner of the text file or equal to the current user. */ if (mch_stat((char *)orig_name, &st_orig) >= 0 && mch_stat((char *)file_name, &st_undo) >= 0 && st_orig.st_uid != st_undo.st_uid && st_undo.st_uid != getuid()) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Not reading undo file, owner differs: %s"), file_name); verbose_leave(); } return; } #endif } else file_name = name; if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Reading undo file: %s"), file_name); verbose_leave(); } fp = mch_fopen((char *)file_name, "r"); if (fp == NULL) { if (name != NULL || p_verbose > 0) EMSG2(_("E822: Cannot open undo file for reading: %s"), file_name); goto error; } bi.bi_buf = curbuf; bi.bi_fp = fp; /* * Read the undo file header. */ if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1 || memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { EMSG2(_("E823: Not an undo file: %s"), file_name); goto error; } version = get2c(fp); if (version == UF_VERSION_CRYPT) { #ifdef FEAT_CRYPT if (*curbuf->b_p_key == NUL) { EMSG2(_("E832: Non-encrypted file has encrypted undo file: %s"), file_name); goto error; } bi.bi_state = crypt_create_from_file(fp, curbuf->b_p_key); if (bi.bi_state == NULL) { EMSG2(_("E826: Undo file decryption failed: %s"), file_name); goto error; } if (crypt_whole_undofile(bi.bi_state->method_nr)) { bi.bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi.bi_buffer == NULL) { crypt_free_state(bi.bi_state); bi.bi_state = NULL; goto error; } bi.bi_avail = 0; bi.bi_used = 0; } #else EMSG2(_("E827: Undo file is encrypted: %s"), file_name); goto error; #endif } else if (version != UF_VERSION) { EMSG2(_("E824: Incompatible undo file: %s"), file_name); goto error; } if (undo_read(&bi, read_hash, (size_t)UNDO_HASH_SIZE) == FAIL) { corruption_error("hash", file_name); goto error; } line_count = (linenr_T)undo_read_4c(&bi); if (memcmp(hash, read_hash, UNDO_HASH_SIZE) != 0 || line_count != curbuf->b_ml.ml_line_count) { if (p_verbose > 0 || name != NULL) { if (name == NULL) verbose_enter(); give_warning((char_u *) _("File contents changed, cannot use undo info"), TRUE); if (name == NULL) verbose_leave(); } goto error; } /* Read undo data for "U" command. */ str_len = undo_read_4c(&bi); if (str_len < 0) goto error; if (str_len > 0) line_ptr = read_string_decrypt(&bi, str_len); line_lnum = (linenr_T)undo_read_4c(&bi); line_colnr = (colnr_T)undo_read_4c(&bi); if (line_lnum < 0 || line_colnr < 0) { corruption_error("line lnum/col", file_name); goto error; } /* Begin general undo data */ old_header_seq = undo_read_4c(&bi); new_header_seq = undo_read_4c(&bi); cur_header_seq = undo_read_4c(&bi); num_head = undo_read_4c(&bi); seq_last = undo_read_4c(&bi); seq_cur = undo_read_4c(&bi); seq_time = undo_read_time(&bi); /* Optional header fields. */ for (;;) { int len = undo_read_byte(&bi); int what; if (len == 0 || len == EOF) break; what = undo_read_byte(&bi); switch (what) { case UF_LAST_SAVE_NR: last_save_nr = undo_read_4c(&bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(&bi); } } /* uhp_table will store the freshly created undo headers we allocate * until we insert them into curbuf. The table remains sorted by the * sequence numbers of the headers. * When there are no headers uhp_table is NULL. */ if (num_head > 0) { if (num_head < LONG_MAX / (long)sizeof(u_header_T *)) uhp_table = (u_header_T **)U_ALLOC_LINE( num_head * sizeof(u_header_T *)); if (uhp_table == NULL) goto error; } while ((c = undo_read_2c(&bi)) == UF_HEADER_MAGIC) { if (num_read_uhps >= num_head) { corruption_error("num_head too small", file_name); goto error; } uhp = unserialize_uhp(&bi, file_name); if (uhp == NULL) goto error; uhp_table[num_read_uhps++] = uhp; } if (num_read_uhps != num_head) { corruption_error("num_head", file_name); goto error; } if (c != UF_HEADER_END_MAGIC) { corruption_error("end marker", file_name); goto error; } #ifdef U_DEBUG uhp_table_used = (int *)alloc_clear( (unsigned)(sizeof(int) * num_head + 1)); # define SET_FLAG(j) ++uhp_table_used[j] #else # define SET_FLAG(j) #endif /* We have put all of the headers into a table. Now we iterate through the * table and swizzle each sequence number we have stored in uh_*_seq into * a pointer corresponding to the header with that sequence number. */ for (i = 0; i < num_head; i++) { uhp = uhp_table[i]; if (uhp == NULL) continue; for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && i != j && uhp_table[i]->uh_seq == uhp_table[j]->uh_seq) { corruption_error("duplicate uh_seq", file_name); goto error; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_next.seq) { uhp->uh_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_prev.seq) { uhp->uh_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_next.seq) { uhp->uh_alt_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_prev.seq) { uhp->uh_alt_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq) { old_idx = i; SET_FLAG(i); } if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq) { new_idx = i; SET_FLAG(i); } if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq) { cur_idx = i; SET_FLAG(i); } } /* Now that we have read the undo info successfully, free the current undo * info and use the info from the file. */ u_blockfree(curbuf); curbuf->b_u_oldhead = old_idx < 0 ? NULL : uhp_table[old_idx]; curbuf->b_u_newhead = new_idx < 0 ? NULL : uhp_table[new_idx]; curbuf->b_u_curhead = cur_idx < 0 ? NULL : uhp_table[cur_idx]; curbuf->b_u_line_ptr = line_ptr; curbuf->b_u_line_lnum = line_lnum; curbuf->b_u_line_colnr = line_colnr; curbuf->b_u_numhead = num_head; curbuf->b_u_seq_last = seq_last; curbuf->b_u_seq_cur = seq_cur; curbuf->b_u_time_cur = seq_time; curbuf->b_u_save_nr_last = last_save_nr; curbuf->b_u_save_nr_cur = last_save_nr; curbuf->b_u_synced = TRUE; vim_free(uhp_table); #ifdef U_DEBUG for (i = 0; i < num_head; ++i) if (uhp_table_used[i] == 0) EMSGN("uhp_table entry %ld not used, leaking memory", i); vim_free(uhp_table_used); u_check(TRUE); #endif if (name != NULL) smsg((char_u *)_("Finished reading undo file %s"), file_name); goto theend; error: vim_free(line_ptr); if (uhp_table != NULL) { for (i = 0; i < num_read_uhps; i++) if (uhp_table[i] != NULL) u_free_uhp(uhp_table[i]); vim_free(uhp_table); } theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (fp != NULL) fclose(fp); if (file_name != name) vim_free(file_name); return; } #endif /* FEAT_PERSISTENT_UNDO */ /* * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible). * If 'cpoptions' does not contain 'u': Always undo. */ void u_undo(int count) { /* * If we get an undo command while executing a macro, we behave like the * original vi. If this happens twice in one macro the result will not * be compatible. */ if (curbuf->b_u_synced == FALSE) { u_sync(TRUE); count = 1; } if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = TRUE; else undo_undoes = !undo_undoes; u_doit(count); } /* * If 'cpoptions' contains 'u': Repeat the previous undo or redo. * If 'cpoptions' does not contain 'u': Always redo. */ void u_redo(int count) { if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = FALSE; u_doit(count); } /* * Undo or redo, depending on 'undo_undoes', 'count' times. */ static void u_doit(int startcount) { int count = startcount; if (!undo_allowed()) return; u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; while (count--) { /* Do the change warning now, so that it triggers FileChangedRO when * needed. This may cause the file to be reloaded, that must happen * before we do anything, because it may change curbuf->b_u_curhead * and more. */ change_warning(0); if (undo_undoes) { if (curbuf->b_u_curhead == NULL) /* first undo */ curbuf->b_u_curhead = curbuf->b_u_newhead; else if (get_undolevel() > 0) /* multi level undo */ /* get next undo */ curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next.ptr; /* nothing to undo */ if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL) { /* stick curbuf->b_u_curhead at end */ curbuf->b_u_curhead = curbuf->b_u_oldhead; beep_flush(); if (count == startcount - 1) { MSG(_("Already at oldest change")); return; } break; } u_undoredo(TRUE); } else { if (curbuf->b_u_curhead == NULL || get_undolevel() <= 0) { beep_flush(); /* nothing to redo */ if (count == startcount - 1) { MSG(_("Already at newest change")); return; } break; } u_undoredo(FALSE); /* Advance for next redo. Set "newhead" when at the end of the * redoable changes. */ if (curbuf->b_u_curhead->uh_prev.ptr == NULL) curbuf->b_u_newhead = curbuf->b_u_curhead; curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev.ptr; } } u_undo_end(undo_undoes, FALSE); } /* * Undo or redo over the timeline. * When "step" is negative go back in time, otherwise goes forward in time. * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as * seconds. * When "file" is TRUE use "step" as a number of file writes. * When "absolute" is TRUE use "step" as the sequence number to jump to. * "sec" must be FALSE then. */ void undo_time( long step, int sec, int file, int absolute) { long target; long closest; long closest_start; long closest_seq = 0; long val; u_header_T *uhp; u_header_T *last; int mark; int nomark; int round; int dosec = sec; int dofile = file; int above = FALSE; int did_undo = TRUE; /* First make sure the current undoable change is synced. */ if (curbuf->b_u_synced == FALSE) u_sync(TRUE); u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; /* "target" is the node below which we want to be. * Init "closest" to a value we can't reach. */ if (absolute) { if (step == 0) { /* target 0 does not exist, got to 1 and above it. */ target = 1; above = TRUE; } else target = step; closest = -1; } else { if (dosec) target = (long)(curbuf->b_u_time_cur) + step; else if (dofile) { if (step < 0) { /* Going back to a previous write. If there were changes after * the last write, count that as moving one file-write, so * that ":earlier 1f" undoes all changes since the last save. */ uhp = curbuf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = curbuf->b_u_newhead; if (uhp != NULL && uhp->uh_save_nr != 0) /* "uh_save_nr" was set in the last block, that means * there were no changes since the last write */ target = curbuf->b_u_save_nr_cur + step; else /* count the changes since the last write as one step */ target = curbuf->b_u_save_nr_cur + step + 1; if (target <= 0) /* Go to before first write: before the oldest change. Use * the sequence number for that. */ dofile = FALSE; } else { /* Moving forward to a newer write. */ target = curbuf->b_u_save_nr_cur + step; if (target > curbuf->b_u_save_nr_last) { /* Go to after last write: after the latest change. Use * the sequence number for that. */ target = curbuf->b_u_seq_last + 1; dofile = FALSE; } } } else target = curbuf->b_u_seq_cur + step; if (step < 0) { if (target < 0) target = 0; closest = -1; } else { if (dosec) closest = (long)(vim_time() + 1); else if (dofile) closest = curbuf->b_u_save_nr_last + 2; else closest = curbuf->b_u_seq_last + 2; if (target >= closest) target = closest - 1; } } closest_start = closest; closest_seq = curbuf->b_u_seq_cur; /* * May do this twice: * 1. Search for "target", update "closest" to the best match found. * 2. If "target" not found search for "closest". * * When using the closest time we use the sequence number in the second * round, because there may be several entries with the same time. */ for (round = 1; round <= 2; ++round) { /* Find the path from the current state to where we want to go. The * desired state can be anywhere in the undo tree, need to go all over * it. We put "nomark" in uh_walk where we have been without success, * "mark" where it could possibly be. */ mark = ++lastmark; nomark = ++lastmark; if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */ uhp = curbuf->b_u_newhead; else uhp = curbuf->b_u_curhead; while (uhp != NULL) { uhp->uh_walk = mark; if (dosec) val = (long)(uhp->uh_time); else if (dofile) val = uhp->uh_save_nr; else val = uhp->uh_seq; if (round == 1 && !(dofile && val == 0)) { /* Remember the header that is closest to the target. * It must be at least in the right direction (checked with * "b_u_seq_cur"). When the timestamp is equal find the * highest/lowest sequence number. */ if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur : uhp->uh_seq > curbuf->b_u_seq_cur) && ((dosec && val == closest) ? (step < 0 ? uhp->uh_seq < closest_seq : uhp->uh_seq > closest_seq) : closest == closest_start || (val > target ? (closest > target ? val - target <= closest - target : val - target <= target - closest) : (closest > target ? target - val <= closest - target : target - val <= target - closest)))) { closest = val; closest_seq = uhp->uh_seq; } } /* Quit searching when we found a match. But when searching for a * time we need to continue looking for the best uh_seq. */ if (target == val && !dosec) { target = uhp->uh_seq; break; } /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { /* If still at the start we don't go through this change. */ if (uhp == curbuf->b_u_curhead) uhp->uh_walk = nomark; uhp = uhp->uh_next.ptr; } else { /* need to backtrack; mark this node as useless */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } } if (uhp != NULL) /* found it */ break; if (absolute) { EMSGN(_("E830: Undo number %ld not found"), step); return; } if (closest == closest_start) { if (step < 0) MSG(_("Already at oldest change")); else MSG(_("Already at newest change")); return; } target = closest_seq; dosec = FALSE; dofile = FALSE; if (step < 0) above = TRUE; /* stop above the header */ } /* If we found it: Follow the path to go to where we want to be. */ if (uhp != NULL) { /* * First go up the tree as much as needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) uhp = curbuf->b_u_newhead; else uhp = uhp->uh_next.ptr; if (uhp == NULL || uhp->uh_walk != mark || (uhp->uh_seq == target && !above)) break; curbuf->b_u_curhead = uhp; u_undoredo(TRUE); uhp->uh_walk = nomark; /* don't go back down here */ } /* * And now go down the tree (redo), branching off where needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) break; /* Go back to the first branch with a mark. */ while (uhp->uh_alt_prev.ptr != NULL && uhp->uh_alt_prev.ptr->uh_walk == mark) uhp = uhp->uh_alt_prev.ptr; /* Find the last branch with a mark, that's the one. */ last = uhp; while (last->uh_alt_next.ptr != NULL && last->uh_alt_next.ptr->uh_walk == mark) last = last->uh_alt_next.ptr; if (last != uhp) { /* Make the used branch the first entry in the list of * alternatives to make "u" and CTRL-R take this branch. */ while (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; if (last->uh_alt_next.ptr != NULL) last->uh_alt_next.ptr->uh_alt_prev.ptr = last->uh_alt_prev.ptr; last->uh_alt_prev.ptr->uh_alt_next.ptr = last->uh_alt_next.ptr; last->uh_alt_prev.ptr = NULL; last->uh_alt_next.ptr = uhp; uhp->uh_alt_prev.ptr = last; if (curbuf->b_u_oldhead == uhp) curbuf->b_u_oldhead = last; uhp = last; if (uhp->uh_next.ptr != NULL) uhp->uh_next.ptr->uh_prev.ptr = uhp; } curbuf->b_u_curhead = uhp; if (uhp->uh_walk != mark) break; /* must have reached the target */ /* Stop when going backwards in time and didn't find the exact * header we were looking for. */ if (uhp->uh_seq == target && above) { curbuf->b_u_seq_cur = target - 1; break; } u_undoredo(FALSE); /* Advance "curhead" to below the header we last used. If it * becomes NULL then we need to set "newhead" to this leaf. */ if (uhp->uh_prev.ptr == NULL) curbuf->b_u_newhead = uhp; curbuf->b_u_curhead = uhp->uh_prev.ptr; did_undo = FALSE; if (uhp->uh_seq == target) /* found it! */ break; uhp = uhp->uh_prev.ptr; if (uhp == NULL || uhp->uh_walk != mark) { /* Need to redo more but can't find it... */ internal_error("undo_time()"); break; } } } u_undo_end(did_undo, absolute); } /* * u_undoredo: common code for undo and redo * * The lines in the file are replaced by the lines in the entry list at * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry * list for the next undo/redo. * * When "undo" is TRUE we go up in the tree, when FALSE we go down. */ static void u_undoredo(int undo) { char_u **newarray = NULL; linenr_T oldsize; linenr_T newsize; linenr_T top, bot; linenr_T lnum; linenr_T newlnum = MAXLNUM; long i; u_entry_T *uep, *nuep; u_entry_T *newlist = NULL; int old_flags; int new_flags; pos_T namedm[NMARKS]; visualinfo_T visualinfo; int empty_buffer; /* buffer became empty */ u_header_T *curhead = curbuf->b_u_curhead; #ifdef FEAT_AUTOCMD /* Don't want autocommands using the undo structures here, they are * invalid till the end. */ block_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif old_flags = curhead->uh_flags; new_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); setpcmark(); /* * save marks before undo/redo */ mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); visualinfo = curbuf->b_visual; curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count; curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = 0; curbuf->b_op_end.col = 0; for (uep = curhead->uh_entry; uep != NULL; uep = nuep) { top = uep->ue_top; bot = uep->ue_bot; if (bot == 0) bot = curbuf->b_ml.ml_line_count + 1; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) { #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif IEMSG(_("E438: u_undo: line numbers wrong")); changed(); /* don't want UNCHANGED now */ return; } oldsize = bot - top - 1; /* number of lines before undo */ newsize = uep->ue_size; /* number of lines after undo */ if (top < newlnum) { /* If the saved cursor is somewhere in this undo block, move it to * the remembered position. Makes "gwap" put the cursor back * where it was. */ lnum = curhead->uh_cursor.lnum; if (lnum >= top && lnum <= top + newsize + 1) { curwin->w_cursor = curhead->uh_cursor; newlnum = curwin->w_cursor.lnum - 1; } else { /* Use the first line that actually changed. Avoids that * undoing auto-formatting puts the cursor in the previous * line. */ for (i = 0; i < newsize && i < oldsize; ++i) if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0) break; if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL) { newlnum = top; curwin->w_cursor.lnum = newlnum + 1; } else if (i < newsize) { newlnum = top + i; curwin->w_cursor.lnum = newlnum + 1; } } } empty_buffer = FALSE; /* delete the lines between top and bot and save them in newarray */ if (oldsize > 0) { if ((newarray = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * oldsize)) == NULL) { do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize)); /* * We have messed up the entry list, repair is impossible. * we have to free the rest of the list. */ while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } break; } /* delete backwards, it goes faster in most cases */ for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum) { /* what can we do when we run out of memory? */ if ((newarray[i] = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); /* remember we deleted the last line in the buffer, and a * dummy empty line will be inserted */ if (curbuf->b_ml.ml_line_count == 1) empty_buffer = TRUE; ml_delete(lnum, FALSE); } } else newarray = NULL; /* insert the lines in u_array between top and bot */ if (newsize) { for (lnum = top, i = 0; i < newsize; ++i, ++lnum) { /* * If the file is empty, there is an empty line 1 that we * should get rid of, by replacing it with the new line */ if (empty_buffer && lnum == 0) ml_replace((linenr_T)1, uep->ue_array[i], TRUE); else ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE); vim_free(uep->ue_array[i]); } vim_free((char_u *)uep->ue_array); } /* adjust marks */ if (oldsize != newsize) { mark_adjust(top + 1, top + oldsize, (long)MAXLNUM, (long)newsize - (long)oldsize); if (curbuf->b_op_start.lnum > top + oldsize) curbuf->b_op_start.lnum += newsize - oldsize; if (curbuf->b_op_end.lnum > top + oldsize) curbuf->b_op_end.lnum += newsize - oldsize; } changed_lines(top + 1, 0, bot, newsize - oldsize); /* set '[ and '] mark */ if (top + 1 < curbuf->b_op_start.lnum) curbuf->b_op_start.lnum = top + 1; if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + 1; else if (top + newsize > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + newsize; u_newcount += newsize; u_oldcount += oldsize; uep->ue_size = oldsize; uep->ue_array = newarray; uep->ue_bot = top + newsize + 1; /* * insert this entry in front of the new entry list */ nuep = uep->ue_next; uep->ue_next = newlist; newlist = uep; } curhead->uh_entry = newlist; curhead->uh_flags = new_flags; if ((old_flags & UH_EMPTYBUF) && bufempty()) curbuf->b_ml.ml_flags |= ML_EMPTY; if (old_flags & UH_CHANGED) changed(); else #ifdef FEAT_NETBEANS_INTG /* per netbeans undo rules, keep it as modified */ if (!isNetbeansModified(curbuf)) #endif unchanged(curbuf, FALSE); /* * restore marks from before undo/redo */ for (i = 0; i < NMARKS; ++i) { if (curhead->uh_namedm[i].lnum != 0) curbuf->b_namedm[i] = curhead->uh_namedm[i]; if (namedm[i].lnum != 0) curhead->uh_namedm[i] = namedm[i]; else curhead->uh_namedm[i].lnum = 0; } if (curhead->uh_visual.vi_start.lnum != 0) { curbuf->b_visual = curhead->uh_visual; curhead->uh_visual = visualinfo; } /* * If the cursor is only off by one line, put it at the same position as * before starting the change (for the "o" command). * Otherwise the cursor should go to the first undone line. */ if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum && curwin->w_cursor.lnum > 1) --curwin->w_cursor.lnum; if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count) { if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = curhead->uh_cursor.col; #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curhead->uh_cursor_vcol >= 0) coladvance((colnr_T)curhead->uh_cursor_vcol); else curwin->w_cursor.coladd = 0; #endif } else beginline(BL_SOL | BL_FIX); } else { /* We get here with the current cursor line being past the end (eg * after adding lines at the end of the file, and then undoing it). * check_cursor() will move the cursor to the last line. Move it to * the first column here. */ curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif } /* Make sure the cursor is on an existing line and column. */ check_cursor(); /* Remember where we are for "g-" and ":earlier 10s". */ curbuf->b_u_seq_cur = curhead->uh_seq; if (undo) /* We are below the previous undo. However, to make ":earlier 1s" * work we compute this as being just above the just undone change. */ --curbuf->b_u_seq_cur; /* Remember where we are for ":earlier 1f" and ":later 1f". */ if (curhead->uh_save_nr != 0) { if (undo) curbuf->b_u_save_nr_cur = curhead->uh_save_nr - 1; else curbuf->b_u_save_nr_cur = curhead->uh_save_nr; } /* The timestamp can be the same for multiple changes, just use the one of * the undone/redone change. */ curbuf->b_u_time_cur = curhead->uh_time; #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif } /* * If we deleted or added lines, report the number of less/more lines. * Otherwise, report the number of changes (this may be incorrect * in some cases, but it's better than nothing). */ static void u_undo_end( int did_undo, /* just did an undo */ int absolute) /* used ":undo N" */ { char *msgstr; u_header_T *uhp; char_u msgbuf[80]; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_UNDO) && KeyTyped) foldOpenCursor(); #endif if (global_busy /* no messages now, wait until global is finished */ || !messaging()) /* 'lazyredraw' set, don't do messages now */ return; if (curbuf->b_ml.ml_flags & ML_EMPTY) --u_newcount; u_oldcount -= u_newcount; if (u_oldcount == -1) msgstr = N_("more line"); else if (u_oldcount < 0) msgstr = N_("more lines"); else if (u_oldcount == 1) msgstr = N_("line less"); else if (u_oldcount > 1) msgstr = N_("fewer lines"); else { u_oldcount = u_newcount; if (u_newcount == 1) msgstr = N_("change"); else msgstr = N_("changes"); } if (curbuf->b_u_curhead != NULL) { /* For ":undo N" we prefer a "after #N" message. */ if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL) { uhp = curbuf->b_u_curhead->uh_next.ptr; did_undo = FALSE; } else if (did_undo) uhp = curbuf->b_u_curhead; else uhp = curbuf->b_u_curhead->uh_next.ptr; } else uhp = curbuf->b_u_newhead; if (uhp == NULL) *msgbuf = NUL; else u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time); #ifdef FEAT_CONCEAL { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == curbuf && wp->w_p_cole > 0) redraw_win_later(wp, NOT_VALID); } } #endif smsg((char_u *)_("%ld %s; %s #%ld %s"), u_oldcount < 0 ? -u_oldcount : u_oldcount, _(msgstr), did_undo ? _("before") : _("after"), uhp == NULL ? 0L : uhp->uh_seq, msgbuf); } /* * u_sync: stop adding to the current entry list */ void u_sync( int force) /* Also sync when no_u_sync is set. */ { /* Skip it when already synced or syncing is disabled. */ if (curbuf->b_u_synced || (!force && no_u_sync > 0)) return; #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) if (im_is_preediting()) return; /* XIM is busy, don't break an undo sequence */ #endif if (get_undolevel() < 0) curbuf->b_u_synced = TRUE; /* no entries, nothing to do */ else { u_getbot(); /* compute ue_bot of previous u_save */ curbuf->b_u_curhead = NULL; } } /* * ":undolist": List the leafs of the undo tree */ void ex_undolist(exarg_T *eap UNUSED) { garray_T ga; u_header_T *uhp; int mark; int nomark; int changes = 1; int i; /* * 1: walk the tree to find all leafs, put the info in "ga". * 2: sort the lines * 3: display the list */ mark = ++lastmark; nomark = ++lastmark; ga_init2(&ga, (int)sizeof(char *), 20); uhp = curbuf->b_u_oldhead; while (uhp != NULL) { if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark && uhp->uh_walk != mark) { if (ga_grow(&ga, 1) == FAIL) break; vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ", uhp->uh_seq, changes); u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time); if (uhp->uh_save_nr > 0) { while (STRLEN(IObuff) < 33) STRCAT(IObuff, " "); vim_snprintf_add((char *)IObuff, IOSIZE, " %3ld", uhp->uh_save_nr); } ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff); } uhp->uh_walk = mark; /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) { uhp = uhp->uh_prev.ptr; ++changes; } /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { uhp = uhp->uh_next.ptr; --changes; } else { /* need to backtrack; mark this node as done */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else { uhp = uhp->uh_next.ptr; --changes; } } } if (ga.ga_len == 0) MSG(_("Nothing to undo")); else { sort_strings((char_u **)ga.ga_data, ga.ga_len); msg_start(); msg_puts_attr((char_u *)_("number changes when saved"), hl_attr(HLF_T)); for (i = 0; i < ga.ga_len && !got_int; ++i) { msg_putchar('\n'); if (got_int) break; msg_puts(((char_u **)ga.ga_data)[i]); } msg_end(); ga_clear_strings(&ga); } } /* * Put the timestamp of an undo header in "buf[buflen]" in a nice format. */ static void u_add_time(char_u *buf, size_t buflen, time_t tt) { #ifdef HAVE_STRFTIME struct tm *curtime; if (vim_time() - tt >= 100) { curtime = localtime(&tt); if (vim_time() - tt < (60L * 60L * 12L)) /* within 12 hours */ (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime); else /* longer ago */ (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime); } else #endif vim_snprintf((char *)buf, buflen, _("%ld seconds ago"), (long)(vim_time() - tt)); } /* * ":undojoin": continue adding to the last entry list */ void ex_undojoin(exarg_T *eap UNUSED) { if (curbuf->b_u_newhead == NULL) return; /* nothing changed before */ if (curbuf->b_u_curhead != NULL) { EMSG(_("E790: undojoin is not allowed after undo")); return; } if (!curbuf->b_u_synced) return; /* already unsynced */ if (get_undolevel() < 0) return; /* no entries, nothing to do */ else /* Append next change to the last entry */ curbuf->b_u_synced = FALSE; } /* * Called after writing or reloading the file and setting b_changed to FALSE. * Now an undo means that the buffer is modified. */ void u_unchanged(buf_T *buf) { u_unch_branch(buf->b_u_oldhead); buf->b_did_warn = FALSE; } /* * After reloading a buffer which was saved for 'undoreload': Find the first * line that was changed and set the cursor there. */ void u_find_first_changed(void) { u_header_T *uhp = curbuf->b_u_newhead; u_entry_T *uep; linenr_T lnum; if (curbuf->b_u_curhead != NULL || uhp == NULL) return; /* undid something in an autocmd? */ /* Check that the last undo block was for the whole file. */ uep = uhp->uh_entry; if (uep->ue_top != 0 || uep->ue_bot != 0) return; for (lnum = 1; lnum < curbuf->b_ml.ml_line_count && lnum <= uep->ue_size; ++lnum) if (STRCMP(ml_get_buf(curbuf, lnum, FALSE), uep->ue_array[lnum - 1]) != 0) { clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; return; } if (curbuf->b_ml.ml_line_count != uep->ue_size) { /* lines added or deleted at the end, put the cursor there */ clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; } } /* * Increase the write count, store it in the last undo header, what would be * used for "u". */ void u_update_save_nr(buf_T *buf) { u_header_T *uhp; ++buf->b_u_save_nr_last; buf->b_u_save_nr_cur = buf->b_u_save_nr_last; uhp = buf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = buf->b_u_newhead; if (uhp != NULL) uhp->uh_save_nr = buf->b_u_save_nr_last; } static void u_unch_branch(u_header_T *uhp) { u_header_T *uh; for (uh = uhp; uh != NULL; uh = uh->uh_prev.ptr) { uh->uh_flags |= UH_CHANGED; if (uh->uh_alt_next.ptr != NULL) u_unch_branch(uh->uh_alt_next.ptr); /* recursive */ } } /* * Get pointer to last added entry. * If it's not valid, give an error message and return NULL. */ static u_entry_T * u_get_headentry(void) { if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL) { IEMSG(_("E439: undo list corrupt")); return NULL; } return curbuf->b_u_newhead->uh_entry; } /* * u_getbot(): compute the line number of the previous u_save * It is called only when b_u_synced is FALSE. */ static void u_getbot(void) { u_entry_T *uep; linenr_T extra; uep = u_get_headentry(); /* check for corrupt undo list */ if (uep == NULL) return; uep = curbuf->b_u_newhead->uh_getbot_entry; if (uep != NULL) { /* * the new ue_bot is computed from the number of lines that has been * inserted (0 - deleted) since calling u_save. This is equal to the * old line count subtracted from the current line count. */ extra = curbuf->b_ml.ml_line_count - uep->ue_lcount; uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra; if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count) { IEMSG(_("E440: undo line missing")); uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will * get all the old lines back * without deleting the current * ones */ } curbuf->b_u_newhead->uh_getbot_entry = NULL; } curbuf->b_u_synced = TRUE; } /* * Free one header "uhp" and its entry list and adjust the pointers. */ static void u_freeheader( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *uhap; /* When there is an alternate redo list free that branch completely, * because we can never go there. */ if (uhp->uh_alt_next.ptr != NULL) u_freebranch(buf, uhp->uh_alt_next.ptr, uhpp); if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; /* Update the links in the list to remove the header. */ if (uhp->uh_next.ptr == NULL) buf->b_u_oldhead = uhp->uh_prev.ptr; else uhp->uh_next.ptr->uh_prev.ptr = uhp->uh_prev.ptr; if (uhp->uh_prev.ptr == NULL) buf->b_u_newhead = uhp->uh_next.ptr; else for (uhap = uhp->uh_prev.ptr; uhap != NULL; uhap = uhap->uh_alt_next.ptr) uhap->uh_next.ptr = uhp->uh_next.ptr; u_freeentries(buf, uhp, uhpp); } /* * Free an alternate branch and any following alternate branches. */ static void u_freebranch( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *tofree, *next; /* If this is the top branch we may need to use u_freeheader() to update * all the pointers. */ if (uhp == buf->b_u_oldhead) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, uhpp); return; } if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; next = uhp; while (next != NULL) { tofree = next; if (tofree->uh_alt_next.ptr != NULL) u_freebranch(buf, tofree->uh_alt_next.ptr, uhpp); /* recursive */ next = tofree->uh_prev.ptr; u_freeentries(buf, tofree, uhpp); } } /* * Free all the undo entries for one header and the header itself. * This means that "uhp" is invalid when returning. */ static void u_freeentries( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_entry_T *uep, *nuep; /* Check for pointers to the header that become invalid now. */ if (buf->b_u_curhead == uhp) buf->b_u_curhead = NULL; if (buf->b_u_newhead == uhp) buf->b_u_newhead = NULL; /* freeing the newest entry */ if (uhpp != NULL && uhp == *uhpp) *uhpp = NULL; for (uep = uhp->uh_entry; uep != NULL; uep = nuep) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); } #ifdef U_DEBUG uhp->uh_magic = 0; #endif vim_free((char_u *)uhp); --buf->b_u_numhead; } /* * free entry 'uep' and 'n' lines in uep->ue_array[] */ static void u_freeentry(u_entry_T *uep, long n) { while (n > 0) vim_free(uep->ue_array[--n]); vim_free((char_u *)uep->ue_array); #ifdef U_DEBUG uep->ue_magic = 0; #endif vim_free((char_u *)uep); } /* * invalidate the undo buffer; called when storage has already been released */ void u_clearall(buf_T *buf) { buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL; buf->b_u_synced = TRUE; buf->b_u_numhead = 0; buf->b_u_line_ptr = NULL; buf->b_u_line_lnum = 0; } /* * save the line "lnum" for the "U" command */ void u_saveline(linenr_T lnum) { if (lnum == curbuf->b_u_line_lnum) /* line is already saved */ return; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */ return; u_clearline(); curbuf->b_u_line_lnum = lnum; if (curwin->w_cursor.lnum == lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; else curbuf->b_u_line_colnr = 0; if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); } /* * clear the line saved for the "U" command * (this is used externally for crossing a line while in insert mode) */ void u_clearline(void) { if (curbuf->b_u_line_ptr != NULL) { vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = NULL; curbuf->b_u_line_lnum = 0; } } /* * Implementation of the "U" command. * Differentiation from vi: "U" can be undone with the next "U". * We also allow the cursor to be in another line. * Careful: may trigger autocommands that reload the buffer. */ void u_undoline(void) { colnr_T t; char_u *oldp; if (undo_off) return; if (curbuf->b_u_line_ptr == NULL || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count) { beep_flush(); return; } /* first save the line for the 'u' command */ if (u_savecommon(curbuf->b_u_line_lnum - 1, curbuf->b_u_line_lnum + 1, (linenr_T)0, FALSE) == FAIL) return; oldp = u_save_line(curbuf->b_u_line_lnum); if (oldp == NULL) { do_outofmem_msg((long_u)0); return; } ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE); changed_bytes(curbuf->b_u_line_lnum, 0); vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = oldp; t = curbuf->b_u_line_colnr; if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; curwin->w_cursor.col = t; curwin->w_cursor.lnum = curbuf->b_u_line_lnum; check_cursor_col(); } /* * Free all allocated memory blocks for the buffer 'buf'. */ void u_blockfree(buf_T *buf) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, NULL); vim_free(buf->b_u_line_ptr); } /* * u_save_line(): allocate memory and copy line 'lnum' into it. * Returns NULL when out of memory. */ static char_u * u_save_line(linenr_T lnum) { return vim_strsave(ml_get(lnum)); } /* * Check if the 'modified' flag is set, or 'ff' has changed (only need to * check the first character, because it can only be "dos", "unix" or "mac"). * "nofile" and "scratch" type buffers are considered to always be unchanged. */ int bufIsChanged(buf_T *buf) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(buf) && #endif (buf->b_changed || file_ff_differs(buf, TRUE)); } int curbufIsChanged(void) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(curbuf) && #endif (curbuf->b_changed || file_ff_differs(curbuf, TRUE)); } #if defined(FEAT_EVAL) || defined(PROTO) /* * For undotree(): Append the list of undo blocks at "first_uhp" to "list". * Recursive. */ void u_eval_tree(u_header_T *first_uhp, list_T *list) { u_header_T *uhp = first_uhp; dict_T *dict; while (uhp != NULL) { dict = dict_alloc(); if (dict == NULL) return; dict_add_nr_str(dict, "seq", uhp->uh_seq, NULL); dict_add_nr_str(dict, "time", (long)uhp->uh_time, NULL); if (uhp == curbuf->b_u_newhead) dict_add_nr_str(dict, "newhead", 1, NULL); if (uhp == curbuf->b_u_curhead) dict_add_nr_str(dict, "curhead", 1, NULL); if (uhp->uh_save_nr > 0) dict_add_nr_str(dict, "save", uhp->uh_save_nr, NULL); if (uhp->uh_alt_next.ptr != NULL) { list_T *alt_list = list_alloc(); if (alt_list != NULL) { /* Recursive call to add alternate undo tree. */ u_eval_tree(uhp->uh_alt_next.ptr, alt_list); dict_add_list(dict, "alt", alt_list); } } list_append_dict(list, dict); uhp = uhp->uh_prev.ptr; } } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/bad_3179_0
crossvul-cpp_data_good_5400_0
/* * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdarg.h> #include <stdio.h> #include "jasper/jas_types.h" #include "jasper/jas_debug.h" /******************************************************************************\ * Local data. \******************************************************************************/ static int jas_dbglevel = 0; /* The debug level. */ /******************************************************************************\ * Code for getting/setting the debug level. \******************************************************************************/ /* Set the library debug level. */ int jas_setdbglevel(int dbglevel) { int olddbglevel; /* Save the old debug level. */ olddbglevel = jas_dbglevel; /* Change the debug level. */ jas_dbglevel = dbglevel; /* Return the old debug level. */ return olddbglevel; } /* Get the library debug level. */ int jas_getdbglevel() { return jas_dbglevel; } /******************************************************************************\ * Code. \******************************************************************************/ /* Perform formatted output to standard error. */ int jas_eprintf(const char *fmt, ...) { int ret; va_list ap; va_start(ap, fmt); ret = vfprintf(stderr, fmt, ap); va_end(ap); return ret; } /* Dump memory to a stream. */ int jas_memdump(FILE *out, void *data, size_t len) { size_t i; size_t j; uchar *dp; dp = data; for (i = 0; i < len; i += 16) { fprintf(out, "%04zx:", i); for (j = 0; j < 16; ++j) { if (i + j < len) { fprintf(out, " %02x", dp[i + j]); } } fprintf(out, "\n"); } return 0; } /******************************************************************************\ * Code. \******************************************************************************/ void jas_deprecated(const char *s) { static char message[] = "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!! WARNING!!!\n" "YOUR CODE IS RELYING ON DEPRECATED FUNCTIONALTIY IN THE JASPER LIBRARY.\n" "THIS FUNCTIONALITY WILL BE REMOVED IN THE NEAR FUTURE.\n" "PLEASE FIX THIS PROBLEM BEFORE YOUR CODE STOPS WORKING!\n" ; jas_eprintf("%s", message); jas_eprintf("The specific problem is as follows:\n%s\n", s); //abort(); }
./CrossVul/dataset_final_sorted/CWE-190/c/good_5400_0
crossvul-cpp_data_good_5325_1
#ifdef HAVE_LIBWEBP #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include "gd.h" #include "gdhelpers.h" #include "webp/decode.h" #include "webp/encode.h" #define GD_WEBP_ALLOC_STEP (4*1024) gdImagePtr gdImageCreateFromWebp (FILE * inFile) { gdImagePtr im; gdIOCtx *in = gdNewFileCtx(inFile); if (!in) return 0; im = gdImageCreateFromWebpCtx(in); in->gd_free(in); return im; } gdImagePtr gdImageCreateFromWebpPtr (int size, void *data) { gdImagePtr im; gdIOCtx *in = gdNewDynamicCtxEx(size, data, 0); if (!in) return 0; im = gdImageCreateFromWebpCtx(in); in->gd_free(in); return im; } gdImagePtr gdImageCreateFromWebpCtx (gdIOCtx * infile) { int width, height; uint8_t *filedata = NULL; uint8_t *argb = NULL; size_t size = 0, n; gdImagePtr im; int x, y; uint8_t *p; do { unsigned char *read, *temp; temp = gdRealloc(filedata, size+GD_WEBP_ALLOC_STEP); if (temp) { filedata = temp; read = temp + size; } else { if (filedata) { gdFree(filedata); } zend_error(E_ERROR, "WebP decode: realloc failed"); return NULL; } n = gdGetBuf(read, GD_WEBP_ALLOC_STEP, infile); if (n>0 && n!=EOF) { size += n; } } while (n>0 && n!=EOF); if (WebPGetInfo(filedata,size, &width, &height) == 0) { zend_error(E_ERROR, "gd-webp cannot get webp info"); gdFree(filedata); return NULL; } im = gdImageCreateTrueColor(width, height); if (!im) { gdFree(filedata); return NULL; } argb = WebPDecodeARGB(filedata, size, &width, &height); if (!argb) { zend_error(E_ERROR, "gd-webp cannot allocate temporary buffer"); gdFree(filedata); gdImageDestroy(im); return NULL; } for (y = 0, p = argb; y < height; y++) { for (x = 0; x < width; x++) { register uint8_t a = gdAlphaMax - (*(p++) >> 1); register uint8_t r = *(p++); register uint8_t g = *(p++); register uint8_t b = *(p++); im->tpixels[y][x] = gdTrueColorAlpha(r, g, b, a); } } gdFree(filedata); /* do not use gdFree here, in case gdFree/alloc is mapped to something else than libc */ free(argb); im->saveAlphaFlag = 1; return im; } void gdImageWebpCtx (gdImagePtr im, gdIOCtx * outfile, int quantization) { uint8_t *argb; int x, y; uint8_t *p; uint8_t *out; size_t out_size; if (im == NULL) { return; } if (!gdImageTrueColor(im)) { zend_error(E_ERROR, "Paletter image not supported by webp"); return; } if (quantization == -1) { quantization = 80; } if (overflow2(gdImageSX(im), 4)) { return; } if (overflow2(gdImageSX(im) * 4, gdImageSY(im))) { return; } argb = (uint8_t *)gdMalloc(gdImageSX(im) * 4 * gdImageSY(im)); if (!argb) { return; } p = argb; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { register int c; register char a; c = im->tpixels[y][x]; a = gdTrueColorGetAlpha(c); if (a == 127) { a = 0; } else { a = 255 - ((a << 1) + (a >> 6)); } *(p++) = gdTrueColorGetRed(c); *(p++) = gdTrueColorGetGreen(c); *(p++) = gdTrueColorGetBlue(c); *(p++) = a; } } out_size = WebPEncodeRGBA(argb, gdImageSX(im), gdImageSY(im), gdImageSX(im) * 4, quantization, &out); if (out_size == 0) { zend_error(E_ERROR, "gd-webp encoding failed"); goto freeargb; } gdPutBuf(out, out_size, outfile); free(out); freeargb: gdFree(argb); } void gdImageWebpEx (gdImagePtr im, FILE * outFile, int quantization) { gdIOCtx *out = gdNewFileCtx(outFile); gdImageWebpCtx(im, out, quantization); out->gd_free(out); } void gdImageWebp (gdImagePtr im, FILE * outFile) { gdIOCtx *out = gdNewFileCtx(outFile); gdImageWebpCtx(im, out, -1); out->gd_free(out); } void * gdImageWebpPtr (gdImagePtr im, int *size) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); gdImageWebpCtx(im, out, -1); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } void * gdImageWebpPtrEx (gdImagePtr im, int *size, int quantization) { void *rv; gdIOCtx *out = gdNewDynamicCtx(2048, NULL); gdImageWebpCtx(im, out, quantization); rv = gdDPExtractData(out, size); out->gd_free(out); return rv; } #endif /* HAVE_LIBWEBP */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5325_1
crossvul-cpp_data_bad_23_0
/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ /* * memcached - memory caching daemon * * http://www.memcached.org/ * * Copyright 2003 Danga Interactive, Inc. All rights reserved. * * Use and distribution licensed under the BSD license. See * the LICENSE file for full text. * * Authors: * Anatoly Vorobey <mellon@pobox.com> * Brad Fitzpatrick <brad@danga.com> */ #include "memcached.h" #include <sys/stat.h> #include <sys/socket.h> #include <sys/un.h> #include <signal.h> #include <sys/param.h> #include <sys/resource.h> #include <sys/uio.h> #include <ctype.h> #include <stdarg.h> /* some POSIX systems need the following definition * to get mlockall flags out of sys/mman.h. */ #ifndef _P1003_1B_VISIBLE #define _P1003_1B_VISIBLE #endif /* need this to get IOV_MAX on some platforms. */ #ifndef __need_IOV_MAX #define __need_IOV_MAX #endif #include <pwd.h> #include <sys/mman.h> #include <fcntl.h> #include <netinet/tcp.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <time.h> #include <assert.h> #include <limits.h> #include <sysexits.h> #include <stddef.h> /* FreeBSD 4.x doesn't have IOV_MAX exposed. */ #ifndef IOV_MAX #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__GNU__) # define IOV_MAX 1024 /* GNU/Hurd don't set MAXPATHLEN * http://www.gnu.org/software/hurd/hurd/porting/guidelines.html#PATH_MAX_tt_MAX_PATH_tt_MAXPATHL */ #ifndef MAXPATHLEN #define MAXPATHLEN 4096 #endif #endif #endif /* * forward declarations */ static void drive_machine(conn *c); static int new_socket(struct addrinfo *ai); static int try_read_command(conn *c); enum try_read_result { READ_DATA_RECEIVED, READ_NO_DATA_RECEIVED, READ_ERROR, /** an error occurred (on the socket) (or client closed connection) */ READ_MEMORY_ERROR /** failed to allocate more memory */ }; static enum try_read_result try_read_network(conn *c); static enum try_read_result try_read_udp(conn *c); static void conn_set_state(conn *c, enum conn_states state); static int start_conn_timeout_thread(); /* stats */ static void stats_init(void); static void server_stats(ADD_STAT add_stats, conn *c); static void process_stat_settings(ADD_STAT add_stats, void *c); static void conn_to_str(const conn *c, char *buf); /* defaults */ static void settings_init(void); /* event handling, network IO */ static void event_handler(const int fd, const short which, void *arg); static void conn_close(conn *c); static void conn_init(void); static bool update_event(conn *c, const int new_flags); static void complete_nread(conn *c); static void process_command(conn *c, char *command); static void write_and_free(conn *c, char *buf, int bytes); static int ensure_iov_space(conn *c); static int add_iov(conn *c, const void *buf, int len); static int add_chunked_item_iovs(conn *c, item *it, int len); static int add_msghdr(conn *c); static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow); static void conn_free(conn *c); /** exported globals **/ struct stats stats; struct stats_state stats_state; struct settings settings; time_t process_started; /* when the process was started */ conn **conns; struct slab_rebalance slab_rebal; volatile int slab_rebalance_signal; /** file scope variables **/ static conn *listen_conn = NULL; static int max_fds; static struct event_base *main_base; enum transmit_result { TRANSMIT_COMPLETE, /** All done writing. */ TRANSMIT_INCOMPLETE, /** More data remaining to write. */ TRANSMIT_SOFT_ERROR, /** Can't write any more right now. */ TRANSMIT_HARD_ERROR /** Can't write (c->state is set to conn_closing) */ }; static enum transmit_result transmit(conn *c); /* This reduces the latency without adding lots of extra wiring to be able to * notify the listener thread of when to listen again. * Also, the clock timer could be broken out into its own thread and we * can block the listener via a condition. */ static volatile bool allow_new_conns = true; static struct event maxconnsevent; static void maxconns_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 0, .tv_usec = 10000}; if (fd == -42 || allow_new_conns == false) { /* reschedule in 10ms if we need to keep polling */ evtimer_set(&maxconnsevent, maxconns_handler, 0); event_base_set(main_base, &maxconnsevent); evtimer_add(&maxconnsevent, &t); } else { evtimer_del(&maxconnsevent); accept_new_conns(true); } } #define REALTIME_MAXDELTA 60*60*24*30 /* * given time value that's either unix time or delta from current unix time, return * unix time. Use the fact that delta can't exceed one month (and real time value can't * be that low). */ static rel_time_t realtime(const time_t exptime) { /* no. of seconds in 30 days - largest possible delta exptime */ if (exptime == 0) return 0; /* 0 means never expire */ if (exptime > REALTIME_MAXDELTA) { /* if item expiration is at/before the server started, give it an expiration time of 1 second after the server started. (because 0 means don't expire). without this, we'd underflow and wrap around to some large value way in the future, effectively making items expiring in the past really expiring never */ if (exptime <= process_started) return (rel_time_t)1; return (rel_time_t)(exptime - process_started); } else { return (rel_time_t)(exptime + current_time); } } static void stats_init(void) { memset(&stats, 0, sizeof(struct stats)); memset(&stats_state, 0, sizeof(struct stats_state)); stats_state.accepting_conns = true; /* assuming we start in this state. */ /* make the time we started always be 2 seconds before we really did, so time(0) - time.started is never zero. if so, things like 'settings.oldest_live' which act as booleans as well as values are now false in boolean context... */ process_started = time(0) - ITEM_UPDATE_INTERVAL - 2; stats_prefix_init(); } static void stats_reset(void) { STATS_LOCK(); memset(&stats, 0, sizeof(struct stats)); stats_prefix_clear(); STATS_UNLOCK(); threadlocal_stats_reset(); item_stats_reset(); } static void settings_init(void) { settings.use_cas = true; settings.access = 0700; settings.port = 11211; settings.udpport = 11211; /* By default this string should be NULL for getaddrinfo() */ settings.inter = NULL; settings.maxbytes = 64 * 1024 * 1024; /* default is 64MB */ settings.maxconns = 1024; /* to limit connections-related memory to about 5MB */ settings.verbose = 0; settings.oldest_live = 0; settings.oldest_cas = 0; /* supplements accuracy of oldest_live */ settings.evict_to_free = 1; /* push old items out of cache when memory runs out */ settings.socketpath = NULL; /* by default, not using a unix socket */ settings.factor = 1.25; settings.chunk_size = 48; /* space for a modest key and value */ settings.num_threads = 4; /* N workers */ settings.num_threads_per_udp = 0; settings.prefix_delimiter = ':'; settings.detail_enabled = 0; settings.reqs_per_event = 20; settings.backlog = 1024; settings.binding_protocol = negotiating_prot; settings.item_size_max = 1024 * 1024; /* The famous 1MB upper limit. */ settings.slab_page_size = 1024 * 1024; /* chunks are split from 1MB pages. */ settings.slab_chunk_size_max = settings.slab_page_size; settings.sasl = false; settings.maxconns_fast = false; settings.lru_crawler = false; settings.lru_crawler_sleep = 100; settings.lru_crawler_tocrawl = 0; settings.lru_maintainer_thread = false; settings.lru_segmented = false; settings.hot_lru_pct = 32; settings.warm_lru_pct = 32; settings.hot_max_age = 3600; settings.warm_max_factor = 2.0; settings.inline_ascii_response = true; settings.temp_lru = false; settings.temporary_ttl = 61; settings.idle_timeout = 0; /* disabled */ settings.hashpower_init = 0; settings.slab_reassign = false; settings.slab_automove = 0; settings.shutdown_command = false; settings.tail_repair_time = TAIL_REPAIR_TIME_DEFAULT; settings.flush_enabled = true; settings.dump_enabled = true; settings.crawls_persleep = 1000; settings.logger_watcher_buf_size = LOGGER_WATCHER_BUF_SIZE; settings.logger_buf_size = LOGGER_BUF_SIZE; } /* * Adds a message header to a connection. * * Returns 0 on success, -1 on out-of-memory. */ static int add_msghdr(conn *c) { struct msghdr *msg; assert(c != NULL); if (c->msgsize == c->msgused) { msg = realloc(c->msglist, c->msgsize * 2 * sizeof(struct msghdr)); if (! msg) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->msglist = msg; c->msgsize *= 2; } msg = c->msglist + c->msgused; /* this wipes msg_iovlen, msg_control, msg_controllen, and msg_flags, the last 3 of which aren't defined on solaris: */ memset(msg, 0, sizeof(struct msghdr)); msg->msg_iov = &c->iov[c->iovused]; if (IS_UDP(c->transport) && c->request_addr_size > 0) { msg->msg_name = &c->request_addr; msg->msg_namelen = c->request_addr_size; } c->msgbytes = 0; c->msgused++; if (IS_UDP(c->transport)) { /* Leave room for the UDP header, which we'll fill in later. */ return add_iov(c, NULL, UDP_HEADER_SIZE); } return 0; } extern pthread_mutex_t conn_lock; /* Connection timeout thread bits */ static pthread_t conn_timeout_tid; #define CONNS_PER_SLICE 100 #define TIMEOUT_MSG_SIZE (1 + sizeof(int)) static void *conn_timeout_thread(void *arg) { int i; conn *c; char buf[TIMEOUT_MSG_SIZE]; rel_time_t oldest_last_cmd; int sleep_time; useconds_t timeslice = 1000000 / (max_fds / CONNS_PER_SLICE); while(1) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread at top of connection list\n"); oldest_last_cmd = current_time; for (i = 0; i < max_fds; i++) { if ((i % CONNS_PER_SLICE) == 0) { if (settings.verbose > 2) fprintf(stderr, "idle timeout thread sleeping for %ulus\n", (unsigned int)timeslice); usleep(timeslice); } if (!conns[i]) continue; c = conns[i]; if (!IS_TCP(c->transport)) continue; if (c->state != conn_new_cmd && c->state != conn_read) continue; if ((current_time - c->last_cmd_time) > settings.idle_timeout) { buf[0] = 't'; memcpy(&buf[1], &i, sizeof(int)); if (write(c->thread->notify_send_fd, buf, TIMEOUT_MSG_SIZE) != TIMEOUT_MSG_SIZE) perror("Failed to write timeout to notify pipe"); } else { if (c->last_cmd_time < oldest_last_cmd) oldest_last_cmd = c->last_cmd_time; } } /* This is the soonest we could have another connection time out */ sleep_time = settings.idle_timeout - (current_time - oldest_last_cmd) + 1; if (sleep_time <= 0) sleep_time = 1; if (settings.verbose > 2) fprintf(stderr, "idle timeout thread finished pass, sleeping for %ds\n", sleep_time); usleep((useconds_t) sleep_time * 1000000); } return NULL; } static int start_conn_timeout_thread() { int ret; if (settings.idle_timeout == 0) return -1; if ((ret = pthread_create(&conn_timeout_tid, NULL, conn_timeout_thread, NULL)) != 0) { fprintf(stderr, "Can't create idle connection timeout thread: %s\n", strerror(ret)); return -1; } return 0; } /* * Initializes the connections array. We don't actually allocate connection * structures until they're needed, so as to avoid wasting memory when the * maximum connection count is much higher than the actual number of * connections. * * This does end up wasting a few pointers' worth of memory for FDs that are * used for things other than connections, but that's worth it in exchange for * being able to directly index the conns array by FD. */ static void conn_init(void) { /* We're unlikely to see an FD much higher than maxconns. */ int next_fd = dup(1); int headroom = 10; /* account for extra unexpected open FDs */ struct rlimit rl; max_fds = settings.maxconns + headroom + next_fd; /* But if possible, get the actual highest FD we can possibly ever see. */ if (getrlimit(RLIMIT_NOFILE, &rl) == 0) { max_fds = rl.rlim_max; } else { fprintf(stderr, "Failed to query maximum file descriptor; " "falling back to maxconns\n"); } close(next_fd); if ((conns = calloc(max_fds, sizeof(conn *))) == NULL) { fprintf(stderr, "Failed to allocate connection structures\n"); /* This is unrecoverable so bail out early. */ exit(1); } } static const char *prot_text(enum protocol prot) { char *rv = "unknown"; switch(prot) { case ascii_prot: rv = "ascii"; break; case binary_prot: rv = "binary"; break; case negotiating_prot: rv = "auto-negotiate"; break; } return rv; } void conn_close_idle(conn *c) { if (settings.idle_timeout > 0 && (current_time - c->last_cmd_time) > settings.idle_timeout) { if (c->state != conn_new_cmd && c->state != conn_read) { if (settings.verbose > 1) fprintf(stderr, "fd %d wants to timeout, but isn't in read state", c->sfd); return; } if (settings.verbose > 1) fprintf(stderr, "Closing idle fd %d\n", c->sfd); c->thread->stats.idle_kicks++; conn_set_state(c, conn_closing); drive_machine(c); } } /* bring conn back from a sidethread. could have had its event base moved. */ void conn_worker_readd(conn *c) { c->ev_flags = EV_READ | EV_PERSIST; event_set(&c->event, c->sfd, c->ev_flags, event_handler, (void *)c); event_base_set(c->thread->base, &c->event); c->state = conn_new_cmd; if (event_add(&c->event, 0) == -1) { perror("event_add"); } } conn *conn_new(const int sfd, enum conn_states init_state, const int event_flags, const int read_buffer_size, enum network_transport transport, struct event_base *base) { conn *c; assert(sfd >= 0 && sfd < max_fds); c = conns[sfd]; if (NULL == c) { if (!(c = (conn *)calloc(1, sizeof(conn)))) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate connection object\n"); return NULL; } MEMCACHED_CONN_CREATE(c); c->rbuf = c->wbuf = 0; c->ilist = 0; c->suffixlist = 0; c->iov = 0; c->msglist = 0; c->hdrbuf = 0; c->rsize = read_buffer_size; c->wsize = DATA_BUFFER_SIZE; c->isize = ITEM_LIST_INITIAL; c->suffixsize = SUFFIX_LIST_INITIAL; c->iovsize = IOV_LIST_INITIAL; c->msgsize = MSG_LIST_INITIAL; c->hdrsize = 0; c->rbuf = (char *)malloc((size_t)c->rsize); c->wbuf = (char *)malloc((size_t)c->wsize); c->ilist = (item **)malloc(sizeof(item *) * c->isize); c->suffixlist = (char **)malloc(sizeof(char *) * c->suffixsize); c->iov = (struct iovec *)malloc(sizeof(struct iovec) * c->iovsize); c->msglist = (struct msghdr *)malloc(sizeof(struct msghdr) * c->msgsize); if (c->rbuf == 0 || c->wbuf == 0 || c->ilist == 0 || c->iov == 0 || c->msglist == 0 || c->suffixlist == 0) { conn_free(c); STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); fprintf(stderr, "Failed to allocate buffers for connection\n"); return NULL; } STATS_LOCK(); stats_state.conn_structs++; STATS_UNLOCK(); c->sfd = sfd; conns[sfd] = c; } c->transport = transport; c->protocol = settings.binding_protocol; /* unix socket mode doesn't need this, so zeroed out. but why * is this done for every command? presumably for UDP * mode. */ if (!settings.socketpath) { c->request_addr_size = sizeof(c->request_addr); } else { c->request_addr_size = 0; } if (transport == tcp_transport && init_state == conn_new_cmd) { if (getpeername(sfd, (struct sockaddr *) &c->request_addr, &c->request_addr_size)) { perror("getpeername"); memset(&c->request_addr, 0, sizeof(c->request_addr)); } } if (settings.verbose > 1) { if (init_state == conn_listening) { fprintf(stderr, "<%d server listening (%s)\n", sfd, prot_text(c->protocol)); } else if (IS_UDP(transport)) { fprintf(stderr, "<%d server listening (udp)\n", sfd); } else if (c->protocol == negotiating_prot) { fprintf(stderr, "<%d new auto-negotiating client connection\n", sfd); } else if (c->protocol == ascii_prot) { fprintf(stderr, "<%d new ascii client connection.\n", sfd); } else if (c->protocol == binary_prot) { fprintf(stderr, "<%d new binary client connection.\n", sfd); } else { fprintf(stderr, "<%d new unknown (%d) client connection\n", sfd, c->protocol); assert(false); } } c->state = init_state; c->rlbytes = 0; c->cmd = -1; c->rbytes = c->wbytes = 0; c->wcurr = c->wbuf; c->rcurr = c->rbuf; c->ritem = 0; c->icurr = c->ilist; c->suffixcurr = c->suffixlist; c->ileft = 0; c->suffixleft = 0; c->iovused = 0; c->msgcurr = 0; c->msgused = 0; c->authenticated = false; c->last_cmd_time = current_time; /* initialize for idle kicker */ c->write_and_go = init_state; c->write_and_free = 0; c->item = 0; c->noreply = false; event_set(&c->event, sfd, event_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = event_flags; if (event_add(&c->event, 0) == -1) { perror("event_add"); return NULL; } STATS_LOCK(); stats_state.curr_conns++; stats.total_conns++; STATS_UNLOCK(); MEMCACHED_CONN_ALLOCATE(c->sfd); return c; } static void conn_release_items(conn *c) { assert(c != NULL); if (c->item) { item_remove(c->item); c->item = 0; } while (c->ileft > 0) { item *it = *(c->icurr); assert((it->it_flags & ITEM_SLABBED) == 0); item_remove(it); c->icurr++; c->ileft--; } if (c->suffixleft != 0) { for (; c->suffixleft > 0; c->suffixleft--, c->suffixcurr++) { do_cache_free(c->thread->suffix_cache, *(c->suffixcurr)); } } c->icurr = c->ilist; c->suffixcurr = c->suffixlist; } static void conn_cleanup(conn *c) { assert(c != NULL); conn_release_items(c); if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } if (c->sasl_conn) { assert(settings.sasl); sasl_dispose(&c->sasl_conn); c->sasl_conn = NULL; } if (IS_UDP(c->transport)) { conn_set_state(c, conn_read); } } /* * Frees a connection. */ void conn_free(conn *c) { if (c) { assert(c != NULL); assert(c->sfd >= 0 && c->sfd < max_fds); MEMCACHED_CONN_DESTROY(c); conns[c->sfd] = NULL; if (c->hdrbuf) free(c->hdrbuf); if (c->msglist) free(c->msglist); if (c->rbuf) free(c->rbuf); if (c->wbuf) free(c->wbuf); if (c->ilist) free(c->ilist); if (c->suffixlist) free(c->suffixlist); if (c->iov) free(c->iov); free(c); } } static void conn_close(conn *c) { assert(c != NULL); /* delete the event, the socket and the conn */ event_del(&c->event); if (settings.verbose > 1) fprintf(stderr, "<%d connection closed.\n", c->sfd); conn_cleanup(c); MEMCACHED_CONN_RELEASE(c->sfd); conn_set_state(c, conn_closed); close(c->sfd); pthread_mutex_lock(&conn_lock); allow_new_conns = true; pthread_mutex_unlock(&conn_lock); STATS_LOCK(); stats_state.curr_conns--; STATS_UNLOCK(); return; } /* * Shrinks a connection's buffers if they're too big. This prevents * periodic large "get" requests from permanently chewing lots of server * memory. * * This should only be called in between requests since it can wipe output * buffers! */ static void conn_shrink(conn *c) { assert(c != NULL); if (IS_UDP(c->transport)) return; if (c->rsize > READ_BUFFER_HIGHWAT && c->rbytes < DATA_BUFFER_SIZE) { char *newbuf; if (c->rcurr != c->rbuf) memmove(c->rbuf, c->rcurr, (size_t)c->rbytes); newbuf = (char *)realloc((void *)c->rbuf, DATA_BUFFER_SIZE); if (newbuf) { c->rbuf = newbuf; c->rsize = DATA_BUFFER_SIZE; } /* TODO check other branch... */ c->rcurr = c->rbuf; } if (c->isize > ITEM_LIST_HIGHWAT) { item **newbuf = (item**) realloc((void *)c->ilist, ITEM_LIST_INITIAL * sizeof(c->ilist[0])); if (newbuf) { c->ilist = newbuf; c->isize = ITEM_LIST_INITIAL; } /* TODO check error condition? */ } if (c->msgsize > MSG_LIST_HIGHWAT) { struct msghdr *newbuf = (struct msghdr *) realloc((void *)c->msglist, MSG_LIST_INITIAL * sizeof(c->msglist[0])); if (newbuf) { c->msglist = newbuf; c->msgsize = MSG_LIST_INITIAL; } /* TODO check error condition? */ } if (c->iovsize > IOV_LIST_HIGHWAT) { struct iovec *newbuf = (struct iovec *) realloc((void *)c->iov, IOV_LIST_INITIAL * sizeof(c->iov[0])); if (newbuf) { c->iov = newbuf; c->iovsize = IOV_LIST_INITIAL; } /* TODO check return value */ } } /** * Convert a state name to a human readable form. */ static const char *state_text(enum conn_states state) { const char* const statenames[] = { "conn_listening", "conn_new_cmd", "conn_waiting", "conn_read", "conn_parse_cmd", "conn_write", "conn_nread", "conn_swallow", "conn_closing", "conn_mwrite", "conn_closed", "conn_watch" }; return statenames[state]; } /* * Sets a connection's current state in the state machine. Any special * processing that needs to happen on certain state transitions can * happen here. */ static void conn_set_state(conn *c, enum conn_states state) { assert(c != NULL); assert(state >= conn_listening && state < conn_max_state); if (state != c->state) { if (settings.verbose > 2) { fprintf(stderr, "%d: going from %s to %s\n", c->sfd, state_text(c->state), state_text(state)); } if (state == conn_write || state == conn_mwrite) { MEMCACHED_PROCESS_COMMAND_END(c->sfd, c->wbuf, c->wbytes); } c->state = state; } } /* * Ensures that there is room for another struct iovec in a connection's * iov list. * * Returns 0 on success, -1 on out-of-memory. */ static int ensure_iov_space(conn *c) { assert(c != NULL); if (c->iovused >= c->iovsize) { int i, iovnum; struct iovec *new_iov = (struct iovec *)realloc(c->iov, (c->iovsize * 2) * sizeof(struct iovec)); if (! new_iov) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->iov = new_iov; c->iovsize *= 2; /* Point all the msghdr structures at the new list. */ for (i = 0, iovnum = 0; i < c->msgused; i++) { c->msglist[i].msg_iov = &c->iov[iovnum]; iovnum += c->msglist[i].msg_iovlen; } } return 0; } /* * Adds data to the list of pending data that will be written out to a * connection. * * Returns 0 on success, -1 on out-of-memory. * Note: This is a hot path for at least ASCII protocol. While there is * redundant code in splitting TCP/UDP handling, any reduction in steps has a * large impact for TCP connections. */ static int add_iov(conn *c, const void *buf, int len) { struct msghdr *m; int leftover; assert(c != NULL); if (IS_UDP(c->transport)) { do { m = &c->msglist[c->msgused - 1]; /* * Limit UDP packets to UDP_MAX_PAYLOAD_SIZE bytes. */ /* We may need to start a new msghdr if this one is full. */ if (m->msg_iovlen == IOV_MAX || (c->msgbytes >= UDP_MAX_PAYLOAD_SIZE)) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; /* If the fragment is too big to fit in the datagram, split it up */ if (len + c->msgbytes > UDP_MAX_PAYLOAD_SIZE) { leftover = len + c->msgbytes - UDP_MAX_PAYLOAD_SIZE; len -= leftover; } else { leftover = 0; } m = &c->msglist[c->msgused - 1]; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; buf = ((char *)buf) + len; len = leftover; } while (leftover > 0); } else { /* Optimized path for TCP connections */ m = &c->msglist[c->msgused - 1]; if (m->msg_iovlen == IOV_MAX) { add_msghdr(c); m = &c->msglist[c->msgused - 1]; } if (ensure_iov_space(c) != 0) return -1; m->msg_iov[m->msg_iovlen].iov_base = (void *)buf; m->msg_iov[m->msg_iovlen].iov_len = len; c->msgbytes += len; c->iovused++; m->msg_iovlen++; } return 0; } static int add_chunked_item_iovs(conn *c, item *it, int len) { assert(it->it_flags & ITEM_CHUNKED); item_chunk *ch = (item_chunk *) ITEM_data(it); while (ch) { int todo = (len > ch->used) ? ch->used : len; if (add_iov(c, ch->data, todo) != 0) { return -1; } ch = ch->next; len -= todo; } return 0; } /* * Constructs a set of UDP headers and attaches them to the outgoing messages. */ static int build_udp_headers(conn *c) { int i; unsigned char *hdr; assert(c != NULL); if (c->msgused > c->hdrsize) { void *new_hdrbuf; if (c->hdrbuf) { new_hdrbuf = realloc(c->hdrbuf, c->msgused * 2 * UDP_HEADER_SIZE); } else { new_hdrbuf = malloc(c->msgused * 2 * UDP_HEADER_SIZE); } if (! new_hdrbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); return -1; } c->hdrbuf = (unsigned char *)new_hdrbuf; c->hdrsize = c->msgused * 2; } hdr = c->hdrbuf; for (i = 0; i < c->msgused; i++) { c->msglist[i].msg_iov[0].iov_base = (void*)hdr; c->msglist[i].msg_iov[0].iov_len = UDP_HEADER_SIZE; *hdr++ = c->request_id / 256; *hdr++ = c->request_id % 256; *hdr++ = i / 256; *hdr++ = i % 256; *hdr++ = c->msgused / 256; *hdr++ = c->msgused % 256; *hdr++ = 0; *hdr++ = 0; assert((void *) hdr == (caddr_t)c->msglist[i].msg_iov[0].iov_base + UDP_HEADER_SIZE); } return 0; } static void out_string(conn *c, const char *str) { size_t len; assert(c != NULL); if (c->noreply) { if (settings.verbose > 1) fprintf(stderr, ">%d NOREPLY %s\n", c->sfd, str); c->noreply = false; conn_set_state(c, conn_new_cmd); return; } if (settings.verbose > 1) fprintf(stderr, ">%d %s\n", c->sfd, str); /* Nuke a partial output... */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; add_msghdr(c); len = strlen(str); if ((len + 2) > c->wsize) { /* ought to be always enough. just fail for simplicity */ str = "SERVER_ERROR output line too long"; len = strlen(str); } memcpy(c->wbuf, str, len); memcpy(c->wbuf + len, "\r\n", 2); c->wbytes = len + 2; c->wcurr = c->wbuf; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; return; } /* * Outputs a protocol-specific "out of memory" error. For ASCII clients, * this is equivalent to out_string(). */ static void out_of_memory(conn *c, char *ascii_error) { const static char error_prefix[] = "SERVER_ERROR "; const static int error_prefix_len = sizeof(error_prefix) - 1; if (c->protocol == binary_prot) { /* Strip off the generic error prefix; it's irrelevant in binary */ if (!strncmp(ascii_error, error_prefix, error_prefix_len)) { ascii_error += error_prefix_len; } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, ascii_error, 0); } else { out_string(c, ascii_error); } } /* * we get here after reading the value in set/add/replace commands. The command * has been stored in c->cmd, and the item is ready in c->item. */ static void complete_nread_ascii(conn *c) { assert(c != NULL); item *it = c->item; int comm = c->cmd; enum store_item_type ret; bool is_valid = false; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if ((it->it_flags & ITEM_CHUNKED) == 0) { if (strncmp(ITEM_data(it) + it->nbytes - 2, "\r\n", 2) == 0) { is_valid = true; } } else { char buf[2]; /* should point to the final item chunk */ item_chunk *ch = (item_chunk *) c->ritem; assert(ch->used != 0); /* :( We need to look at the last two bytes. This could span two * chunks. */ if (ch->used > 1) { buf[0] = ch->data[ch->used - 2]; buf[1] = ch->data[ch->used - 1]; } else { assert(ch->prev); assert(ch->used == 1); buf[0] = ch->prev->data[ch->prev->used - 1]; buf[1] = ch->data[ch->used - 1]; } if (strncmp(buf, "\r\n", 2) == 0) { is_valid = true; } else { assert(1 == 0); } } if (!is_valid) { out_string(c, "CLIENT_ERROR bad data chunk"); } else { ret = store_item(it, comm, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == 1) ? it->nbytes : -1, cas); break; case NREAD_CAS: MEMCACHED_COMMAND_CAS(c->sfd, ITEM_key(it), it->nkey, it->nbytes, cas); break; } #endif switch (ret) { case STORED: out_string(c, "STORED"); break; case EXISTS: out_string(c, "EXISTS"); break; case NOT_FOUND: out_string(c, "NOT_FOUND"); break; case NOT_STORED: out_string(c, "NOT_STORED"); break; default: out_string(c, "SERVER_ERROR Unhandled storage type."); } } item_remove(c->item); /* release the c->item reference */ c->item = 0; } /** * get a pointer to the start of the request struct for the current command */ static void* binary_get_request(conn *c) { char *ret = c->rcurr; ret -= (sizeof(c->binary_header) + c->binary_header.request.keylen + c->binary_header.request.extlen); assert(ret >= c->rbuf); return ret; } /** * get a pointer to the key in this request */ static char* binary_get_key(conn *c) { return c->rcurr - (c->binary_header.request.keylen); } static void add_bin_header(conn *c, uint16_t err, uint8_t hdr_len, uint16_t key_len, uint32_t body_len) { protocol_binary_response_header* header; assert(c); c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { /* This should never run out of memory because iov and msg lists * have minimum sizes big enough to hold an error response. */ out_of_memory(c, "SERVER_ERROR out of memory adding binary header"); return; } header = (protocol_binary_response_header *)c->wbuf; header->response.magic = (uint8_t)PROTOCOL_BINARY_RES; header->response.opcode = c->binary_header.request.opcode; header->response.keylen = (uint16_t)htons(key_len); header->response.extlen = (uint8_t)hdr_len; header->response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES; header->response.status = (uint16_t)htons(err); header->response.bodylen = htonl(body_len); header->response.opaque = c->opaque; header->response.cas = htonll(c->cas); if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d Writing bin response:", c->sfd); for (ii = 0; ii < sizeof(header->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n>%d ", c->sfd); } fprintf(stderr, " 0x%02x", header->bytes[ii]); } fprintf(stderr, "\n"); } add_iov(c, c->wbuf, sizeof(header->response)); } /** * Writes a binary error response. If errstr is supplied, it is used as the * error text; otherwise a generic description of the error status code is * included. */ static void write_bin_error(conn *c, protocol_binary_response_status err, const char *errstr, int swallow) { size_t len; if (!errstr) { switch (err) { case PROTOCOL_BINARY_RESPONSE_ENOMEM: errstr = "Out of memory"; break; case PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND: errstr = "Unknown command"; break; case PROTOCOL_BINARY_RESPONSE_KEY_ENOENT: errstr = "Not found"; break; case PROTOCOL_BINARY_RESPONSE_EINVAL: errstr = "Invalid arguments"; break; case PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS: errstr = "Data exists for key."; break; case PROTOCOL_BINARY_RESPONSE_E2BIG: errstr = "Too large."; break; case PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL: errstr = "Non-numeric server-side value for incr or decr"; break; case PROTOCOL_BINARY_RESPONSE_NOT_STORED: errstr = "Not stored."; break; case PROTOCOL_BINARY_RESPONSE_AUTH_ERROR: errstr = "Auth failure."; break; default: assert(false); errstr = "UNHANDLED ERROR"; fprintf(stderr, ">%d UNHANDLED ERROR: %d\n", c->sfd, err); } } if (settings.verbose > 1) { fprintf(stderr, ">%d Writing an error: %s\n", c->sfd, errstr); } len = strlen(errstr); add_bin_header(c, err, 0, 0, len); if (len > 0) { add_iov(c, errstr, len); } conn_set_state(c, conn_mwrite); if(swallow > 0) { c->sbytes = swallow; c->write_and_go = conn_swallow; } else { c->write_and_go = conn_new_cmd; } } /* Form and send a response to a command over the binary protocol */ static void write_bin_response(conn *c, void *d, int hlen, int keylen, int dlen) { if (!c->noreply || c->cmd == PROTOCOL_BINARY_CMD_GET || c->cmd == PROTOCOL_BINARY_CMD_GETK) { add_bin_header(c, 0, hlen, keylen, dlen); if(dlen > 0) { add_iov(c, d, dlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { conn_set_state(c, conn_new_cmd); } } static void complete_incr_bin(conn *c) { item *it; char *key; size_t nkey; /* Weird magic in add_delta forces me to pad here */ char tmpbuf[INCR_MAX_STORAGE_LEN]; uint64_t cas = 0; protocol_binary_response_incr* rsp = (protocol_binary_response_incr*)c->wbuf; protocol_binary_request_incr* req = binary_get_request(c); assert(c != NULL); assert(c->wsize >= sizeof(*rsp)); /* fix byteorder in the request */ req->message.body.delta = ntohll(req->message.body.delta); req->message.body.initial = ntohll(req->message.body.initial); req->message.body.expiration = ntohl(req->message.body.expiration); key = binary_get_key(c); nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int i; fprintf(stderr, "incr "); for (i = 0; i < nkey; i++) { fprintf(stderr, "%c", key[i]); } fprintf(stderr, " %lld, %llu, %d\n", (long long)req->message.body.delta, (long long)req->message.body.initial, req->message.body.expiration); } if (c->binary_header.request.cas != 0) { cas = c->binary_header.request.cas; } switch(add_delta(c, key, nkey, c->cmd == PROTOCOL_BINARY_CMD_INCREMENT, req->message.body.delta, tmpbuf, &cas)) { case OK: rsp->message.body.value = htonll(strtoull(tmpbuf, NULL, 10)); if (cas) { c->cas = cas; } write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); break; case NON_NUMERIC: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_DELTA_BADVAL, NULL, 0); break; case EOM: out_of_memory(c, "SERVER_ERROR Out of memory incrementing value"); break; case DELTA_ITEM_NOT_FOUND: if (req->message.body.expiration != 0xffffffff) { /* Save some room for the response */ rsp->message.body.value = htonll(req->message.body.initial); snprintf(tmpbuf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)req->message.body.initial); int res = strlen(tmpbuf); it = item_alloc(key, nkey, 0, realtime(req->message.body.expiration), res + 2); if (it != NULL) { memcpy(ITEM_data(it), tmpbuf, res); memcpy(ITEM_data(it) + res, "\r\n", 2); if (store_item(it, NREAD_ADD, c)) { c->cas = ITEM_get_cas(it); write_bin_response(c, &rsp->message.body, 0, 0, sizeof(rsp->message.body.value)); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_NOT_STORED, NULL, 0); } item_remove(it); /* release our reference */ } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating new item"); } } else { pthread_mutex_lock(&c->thread->stats.mutex); if (c->cmd == PROTOCOL_BINARY_CMD_INCREMENT) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } break; case DELTA_ITEM_CAS_MISMATCH: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; } } static void complete_update_bin(conn *c) { protocol_binary_response_status eno = PROTOCOL_BINARY_RESPONSE_EINVAL; enum store_item_type ret = NOT_STORED; assert(c != NULL); item *it = c->item; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].set_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); /* We don't actually receive the trailing two characters in the bin * protocol, so we're going to just set them here */ if ((it->it_flags & ITEM_CHUNKED) == 0) { *(ITEM_data(it) + it->nbytes - 2) = '\r'; *(ITEM_data(it) + it->nbytes - 1) = '\n'; } else { assert(c->ritem); item_chunk *ch = (item_chunk *) c->ritem; if (ch->size == ch->used) ch = ch->next; assert(ch->size - ch->used >= 2); ch->data[ch->used + 1] = '\r'; ch->data[ch->used + 2] = '\n'; ch->used += 2; } ret = store_item(it, c->cmd, c); #ifdef ENABLE_DTRACE uint64_t cas = ITEM_get_cas(it); switch (c->cmd) { case NREAD_ADD: MEMCACHED_COMMAND_ADD(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_REPLACE: MEMCACHED_COMMAND_REPLACE(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_APPEND: MEMCACHED_COMMAND_APPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_PREPEND: MEMCACHED_COMMAND_PREPEND(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; case NREAD_SET: MEMCACHED_COMMAND_SET(c->sfd, ITEM_key(it), it->nkey, (ret == STORED) ? it->nbytes : -1, cas); break; } #endif switch (ret) { case STORED: /* Stored */ write_bin_response(c, NULL, 0, 0, 0); break; case EXISTS: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); break; case NOT_FOUND: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); break; case NOT_STORED: case TOO_LARGE: case NO_MEMORY: if (c->cmd == NREAD_ADD) { eno = PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS; } else if(c->cmd == NREAD_REPLACE) { eno = PROTOCOL_BINARY_RESPONSE_KEY_ENOENT; } else { eno = PROTOCOL_BINARY_RESPONSE_NOT_STORED; } write_bin_error(c, eno, NULL, 0); } item_remove(c->item); /* release the c->item reference */ c->item = 0; } static void process_bin_get_or_touch(conn *c) { item *it; protocol_binary_response_get* rsp = (protocol_binary_response_get*)c->wbuf; char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; int should_touch = (c->cmd == PROTOCOL_BINARY_CMD_TOUCH || c->cmd == PROTOCOL_BINARY_CMD_GAT || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_key = (c->cmd == PROTOCOL_BINARY_CMD_GETK || c->cmd == PROTOCOL_BINARY_CMD_GATK); int should_return_value = (c->cmd != PROTOCOL_BINARY_CMD_TOUCH); if (settings.verbose > 1) { fprintf(stderr, "<%d %s ", c->sfd, should_touch ? "TOUCH" : "GET"); if (fwrite(key, 1, nkey, stderr)) {} fputc('\n', stderr); } if (should_touch) { protocol_binary_request_touch *t = binary_get_request(c); time_t exptime = ntohl(t->message.body.expiration); it = item_touch(key, nkey, realtime(exptime), c); } else { it = item_get(key, nkey, c, DO_UPDATE); } if (it) { /* the length has two unnecessary bytes ("\r\n") */ uint16_t keylen = 0; uint32_t bodylen = sizeof(rsp->message.body) + (it->nbytes - 2); pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; } else { c->thread->stats.get_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); } if (c->cmd == PROTOCOL_BINARY_CMD_TOUCH) { bodylen -= it->nbytes - 2; } else if (should_return_key) { bodylen += nkey; keylen = nkey; } add_bin_header(c, 0, sizeof(rsp->message.body), keylen, bodylen); rsp->message.header.response.cas = htonll(ITEM_get_cas(it)); // add the flags if (settings.inline_ascii_response) { rsp->message.body.flags = htonl(strtoul(ITEM_suffix(it), NULL, 10)); } else { rsp->message.body.flags = htonl(*((uint32_t *)ITEM_suffix(it))); } add_iov(c, &rsp->message.body, sizeof(rsp->message.body)); if (should_return_key) { add_iov(c, ITEM_key(it), nkey); } if (should_return_value) { /* Add the data minus the CRLF */ if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes - 2); } else { add_chunked_item_iovs(c, it, it->nbytes - 2); } } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; /* Remember this command so we can garbage collect it later */ c->item = it; } else { pthread_mutex_lock(&c->thread->stats.mutex); if (should_touch) { c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; } else { c->thread->stats.get_cmds++; c->thread->stats.get_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); if (should_touch) { MEMCACHED_COMMAND_TOUCH(c->sfd, key, nkey, -1, 0); } else { MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } if (c->noreply) { conn_set_state(c, conn_new_cmd); } else { if (should_return_key) { char *ofs = c->wbuf + sizeof(protocol_binary_response_header); add_bin_header(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, 0, nkey, nkey); memcpy(ofs, key, nkey); add_iov(c, ofs, nkey); conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } } } if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } } static void append_bin_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *buf = c->stats.buffer + c->stats.offset; uint32_t bodylen = klen + vlen; protocol_binary_response_header header = { .response.magic = (uint8_t)PROTOCOL_BINARY_RES, .response.opcode = PROTOCOL_BINARY_CMD_STAT, .response.keylen = (uint16_t)htons(klen), .response.datatype = (uint8_t)PROTOCOL_BINARY_RAW_BYTES, .response.bodylen = htonl(bodylen), .response.opaque = c->opaque }; memcpy(buf, header.bytes, sizeof(header.response)); buf += sizeof(header.response); if (klen > 0) { memcpy(buf, key, klen); buf += klen; if (vlen > 0) { memcpy(buf, val, vlen); } } c->stats.offset += sizeof(header.response) + bodylen; } static void append_ascii_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, conn *c) { char *pos = c->stats.buffer + c->stats.offset; uint32_t nbytes = 0; int remaining = c->stats.size - c->stats.offset; int room = remaining - 1; if (klen == 0 && vlen == 0) { nbytes = snprintf(pos, room, "END\r\n"); } else if (vlen == 0) { nbytes = snprintf(pos, room, "STAT %s\r\n", key); } else { nbytes = snprintf(pos, room, "STAT %s %s\r\n", key, val); } c->stats.offset += nbytes; } static bool grow_stats_buf(conn *c, size_t needed) { size_t nsize = c->stats.size; size_t available = nsize - c->stats.offset; bool rv = true; /* Special case: No buffer -- need to allocate fresh */ if (c->stats.buffer == NULL) { nsize = 1024; available = c->stats.size = c->stats.offset = 0; } while (needed > available) { assert(nsize > 0); nsize = nsize << 1; available = nsize - c->stats.offset; } if (nsize != c->stats.size) { char *ptr = realloc(c->stats.buffer, nsize); if (ptr) { c->stats.buffer = ptr; c->stats.size = nsize; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); rv = false; } } return rv; } static void append_stats(const char *key, const uint16_t klen, const char *val, const uint32_t vlen, const void *cookie) { /* value without a key is invalid */ if (klen == 0 && vlen > 0) { return ; } conn *c = (conn*)cookie; if (c->protocol == binary_prot) { size_t needed = vlen + klen + sizeof(protocol_binary_response_header); if (!grow_stats_buf(c, needed)) { return ; } append_bin_stats(key, klen, val, vlen, c); } else { size_t needed = vlen + klen + 10; // 10 == "STAT = \r\n" if (!grow_stats_buf(c, needed)) { return ; } append_ascii_stats(key, klen, val, vlen, c); } assert(c->stats.offset <= c->stats.size); } static void process_bin_stat(conn *c) { char *subcommand = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; if (settings.verbose > 1) { int ii; fprintf(stderr, "<%d STATS ", c->sfd); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", subcommand[ii]); } fprintf(stderr, "\n"); } if (nkey == 0) { /* request all statistics */ server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strncmp(subcommand, "reset", 5) == 0) { stats_reset(); } else if (strncmp(subcommand, "settings", 8) == 0) { process_stat_settings(&append_stats, c); } else if (strncmp(subcommand, "detail", 6) == 0) { char *subcmd_pos = subcommand + 6; if (strncmp(subcmd_pos, " dump", 5) == 0) { int len; char *dump_buf = stats_prefix_dump(&len); if (dump_buf == NULL || len <= 0) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); return ; } else { append_stats("detailed", strlen("detailed"), dump_buf, len, c); free(dump_buf); } } else if (strncmp(subcmd_pos, " on", 3) == 0) { settings.detail_enabled = 1; } else if (strncmp(subcmd_pos, " off", 4) == 0) { settings.detail_enabled = 0; } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); return; } } else { if (get_stats(subcommand, nkey, &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory generating stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); } return; } /* Append termination package and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR Out of memory preparing to send stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static void bin_read_key(conn *c, enum bin_substates next_substate, int extra) { assert(c); c->substate = next_substate; c->rlbytes = c->keylen + extra; /* Ok... do we have room for the extras and the key in the input buffer? */ ptrdiff_t offset = c->rcurr + sizeof(protocol_binary_request_header) - c->rbuf; if (c->rlbytes > c->rsize - offset) { size_t nsize = c->rsize; size_t size = c->rlbytes + sizeof(protocol_binary_request_header); while (size > nsize) { nsize *= 2; } if (nsize != c->rsize) { if (settings.verbose > 1) { fprintf(stderr, "%d: Need to grow buffer from %lu to %lu\n", c->sfd, (unsigned long)c->rsize, (unsigned long)nsize); } char *newm = realloc(c->rbuf, nsize); if (newm == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose) { fprintf(stderr, "%d: Failed to grow buffer.. closing connection\n", c->sfd); } conn_set_state(c, conn_closing); return; } c->rbuf= newm; /* rcurr should point to the same offset in the packet */ c->rcurr = c->rbuf + offset - sizeof(protocol_binary_request_header); c->rsize = nsize; } if (c->rbuf != c->rcurr) { memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Repack input buffer\n", c->sfd); } } } /* preserve the header in the buffer.. */ c->ritem = c->rcurr + sizeof(protocol_binary_request_header); conn_set_state(c, conn_nread); } /* Just write an error message and disconnect the client */ static void handle_binary_protocol_error(conn *c) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, 0); if (settings.verbose) { fprintf(stderr, "Protocol error (opcode %02x), close connection %d\n", c->binary_header.request.opcode, c->sfd); } c->write_and_go = conn_closing; } static void init_sasl_conn(conn *c) { assert(c); /* should something else be returned? */ if (!settings.sasl) return; c->authenticated = false; if (!c->sasl_conn) { int result=sasl_server_new("memcached", NULL, my_sasl_hostname[0] ? my_sasl_hostname : NULL, NULL, NULL, NULL, 0, &c->sasl_conn); if (result != SASL_OK) { if (settings.verbose) { fprintf(stderr, "Failed to initialize SASL conn.\n"); } c->sasl_conn = NULL; } } } static void bin_list_sasl_mechs(conn *c) { // Guard against a disabled SASL. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } init_sasl_conn(c); const char *result_string = NULL; unsigned int string_length = 0; int result=sasl_listmech(c->sasl_conn, NULL, "", /* What to prepend the string with */ " ", /* What to separate mechanisms with */ "", /* What to append to the string */ &result_string, &string_length, NULL); if (result != SASL_OK) { /* Perhaps there's a better error for this... */ if (settings.verbose) { fprintf(stderr, "Failed to list SASL mechanisms.\n"); } write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } write_bin_response(c, (char*)result_string, 0, 0, string_length); } static void process_bin_sasl_auth(conn *c) { // Guard for handling disabled SASL on the server. if (!settings.sasl) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, c->binary_header.request.bodylen - c->binary_header.request.keylen); return; } assert(c->binary_header.request.extlen == 0); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > MAX_SASL_MECH_LEN) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; return; } char *key = binary_get_key(c); assert(key); item *it = item_alloc(key, nkey, 0, 0, vlen+2); /* Can't use a chunked item for SASL authentication. */ if (it == 0 || (it->it_flags & ITEM_CHUNKED)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_ENOMEM, NULL, vlen); c->write_and_go = conn_swallow; return; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_reading_sasl_auth_data; } static void process_bin_complete_sasl_auth(conn *c) { assert(settings.sasl); const char *out = NULL; unsigned int outlen = 0; assert(c->item); init_sasl_conn(c); int nkey = c->binary_header.request.keylen; int vlen = c->binary_header.request.bodylen - nkey; if (nkey > ((item*) c->item)->nkey) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } char mech[nkey+1]; memcpy(mech, ITEM_key((item*)c->item), nkey); mech[nkey] = 0x00; if (settings.verbose) fprintf(stderr, "mech: ``%s'' with %d bytes of data\n", mech, vlen); const char *challenge = vlen == 0 ? NULL : ITEM_data((item*) c->item); if (vlen > ((item*) c->item)->nbytes) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_EINVAL, NULL, vlen); c->write_and_go = conn_swallow; item_unlink(c->item); return; } int result=-1; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_AUTH: result = sasl_server_start(c->sasl_conn, mech, challenge, vlen, &out, &outlen); break; case PROTOCOL_BINARY_CMD_SASL_STEP: result = sasl_server_step(c->sasl_conn, challenge, vlen, &out, &outlen); break; default: assert(false); /* CMD should be one of the above */ /* This code is pretty much impossible, but makes the compiler happier */ if (settings.verbose) { fprintf(stderr, "Unhandled command %d with challenge %s\n", c->cmd, challenge); } break; } item_unlink(c->item); if (settings.verbose) { fprintf(stderr, "sasl result code: %d\n", result); } switch(result) { case SASL_OK: c->authenticated = true; write_bin_response(c, "Authenticated", 0, 0, strlen("Authenticated")); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); break; case SASL_CONTINUE: add_bin_header(c, PROTOCOL_BINARY_RESPONSE_AUTH_CONTINUE, 0, 0, outlen); if(outlen > 0) { add_iov(c, out, outlen); } conn_set_state(c, conn_mwrite); c->write_and_go = conn_new_cmd; break; default: if (settings.verbose) fprintf(stderr, "Unknown sasl response: %d\n", result); write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.auth_cmds++; c->thread->stats.auth_errors++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static bool authenticated(conn *c) { assert(settings.sasl); bool rv = false; switch (c->cmd) { case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_AUTH: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_SASL_STEP: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_VERSION: /* FALLTHROUGH */ rv = true; break; default: rv = c->authenticated; } if (settings.verbose > 1) { fprintf(stderr, "authenticated() in cmd 0x%02x is %s\n", c->cmd, rv ? "true" : "false"); } return rv; } static void dispatch_bin_command(conn *c) { int protocol_error = 0; uint8_t extlen = c->binary_header.request.extlen; uint16_t keylen = c->binary_header.request.keylen; uint32_t bodylen = c->binary_header.request.bodylen; if (keylen > bodylen || keylen + extlen > bodylen) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, 0); c->write_and_go = conn_closing; return; } if (settings.sasl && !authenticated(c)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); c->write_and_go = conn_closing; return; } MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); c->noreply = true; /* binprot supports 16bit keys, but internals are still 8bit */ if (keylen > KEY_MAX_LENGTH) { handle_binary_protocol_error(c); return; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_SETQ: c->cmd = PROTOCOL_BINARY_CMD_SET; break; case PROTOCOL_BINARY_CMD_ADDQ: c->cmd = PROTOCOL_BINARY_CMD_ADD; break; case PROTOCOL_BINARY_CMD_REPLACEQ: c->cmd = PROTOCOL_BINARY_CMD_REPLACE; break; case PROTOCOL_BINARY_CMD_DELETEQ: c->cmd = PROTOCOL_BINARY_CMD_DELETE; break; case PROTOCOL_BINARY_CMD_INCREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_INCREMENT; break; case PROTOCOL_BINARY_CMD_DECREMENTQ: c->cmd = PROTOCOL_BINARY_CMD_DECREMENT; break; case PROTOCOL_BINARY_CMD_QUITQ: c->cmd = PROTOCOL_BINARY_CMD_QUIT; break; case PROTOCOL_BINARY_CMD_FLUSHQ: c->cmd = PROTOCOL_BINARY_CMD_FLUSH; break; case PROTOCOL_BINARY_CMD_APPENDQ: c->cmd = PROTOCOL_BINARY_CMD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPENDQ: c->cmd = PROTOCOL_BINARY_CMD_PREPEND; break; case PROTOCOL_BINARY_CMD_GETQ: c->cmd = PROTOCOL_BINARY_CMD_GET; break; case PROTOCOL_BINARY_CMD_GETKQ: c->cmd = PROTOCOL_BINARY_CMD_GETK; break; case PROTOCOL_BINARY_CMD_GATQ: c->cmd = PROTOCOL_BINARY_CMD_GAT; break; case PROTOCOL_BINARY_CMD_GATKQ: c->cmd = PROTOCOL_BINARY_CMD_GATK; break; default: c->noreply = false; } switch (c->cmd) { case PROTOCOL_BINARY_CMD_VERSION: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, VERSION, 0, 0, strlen(VERSION)); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_FLUSH: if (keylen == 0 && bodylen == extlen && (extlen == 0 || extlen == 4)) { bin_read_key(c, bin_read_flush_exptime, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_NOOP: if (extlen == 0 && keylen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_ADD: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_REPLACE: if (extlen == 8 && keylen != 0 && bodylen >= (keylen + 8)) { bin_read_key(c, bin_reading_set_header, 8); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_GETQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GET: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETKQ: /* FALLTHROUGH */ case PROTOCOL_BINARY_CMD_GETK: if (extlen == 0 && bodylen == keylen && keylen > 0) { bin_read_key(c, bin_reading_get_key, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_DELETE: if (keylen > 0 && extlen == 0 && bodylen == keylen) { bin_read_key(c, bin_reading_del_header, extlen); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_INCREMENT: case PROTOCOL_BINARY_CMD_DECREMENT: if (keylen > 0 && extlen == 20 && bodylen == (keylen + extlen)) { bin_read_key(c, bin_reading_incr_header, 20); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_APPEND: case PROTOCOL_BINARY_CMD_PREPEND: if (keylen > 0 && extlen == 0) { bin_read_key(c, bin_reading_set_header, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_STAT: if (extlen == 0) { bin_read_key(c, bin_reading_stat, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_QUIT: if (keylen == 0 && extlen == 0 && bodylen == 0) { write_bin_response(c, NULL, 0, 0, 0); c->write_and_go = conn_closing; if (c->noreply) { conn_set_state(c, conn_closing); } } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_LIST_MECHS: if (extlen == 0 && keylen == 0 && bodylen == 0) { bin_list_sasl_mechs(c); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_SASL_AUTH: case PROTOCOL_BINARY_CMD_SASL_STEP: if (extlen == 0 && keylen != 0) { bin_read_key(c, bin_reading_sasl_auth, 0); } else { protocol_error = 1; } break; case PROTOCOL_BINARY_CMD_TOUCH: case PROTOCOL_BINARY_CMD_GAT: case PROTOCOL_BINARY_CMD_GATQ: case PROTOCOL_BINARY_CMD_GATK: case PROTOCOL_BINARY_CMD_GATKQ: if (extlen == 4 && keylen != 0) { bin_read_key(c, bin_reading_touch_key, 4); } else { protocol_error = 1; } break; default: write_bin_error(c, PROTOCOL_BINARY_RESPONSE_UNKNOWN_COMMAND, NULL, bodylen); } if (protocol_error) handle_binary_protocol_error(c); } static void process_bin_update(conn *c) { char *key; int nkey; int vlen; item *it; protocol_binary_request_set* req = binary_get_request(c); assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; /* fix byteorder in the request */ req->message.body.flags = ntohl(req->message.body.flags); req->message.body.expiration = ntohl(req->message.body.expiration); vlen = c->binary_header.request.bodylen - (nkey + c->binary_header.request.extlen); if (settings.verbose > 1) { int ii; if (c->cmd == PROTOCOL_BINARY_CMD_ADD) { fprintf(stderr, "<%d ADD ", c->sfd); } else if (c->cmd == PROTOCOL_BINARY_CMD_SET) { fprintf(stderr, "<%d SET ", c->sfd); } else { fprintf(stderr, "<%d REPLACE ", c->sfd); } for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, " Value len is %d", vlen); fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, req->message.body.flags, realtime(req->message.body.expiration), vlen+2); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, req->message.body.flags, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* This error generating method eats the swallow value. Add here. */ c->sbytes = vlen; status = NO_MEMORY; } /* FIXME: losing c->cmd since it's translated below. refactor? */ LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, 0, key, nkey, it->exptime, ITEM_clsid(it)); /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (c->cmd == PROTOCOL_BINARY_CMD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); item_remove(it); } } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_ADD: c->cmd = NREAD_ADD; break; case PROTOCOL_BINARY_CMD_SET: c->cmd = NREAD_SET; break; case PROTOCOL_BINARY_CMD_REPLACE: c->cmd = NREAD_REPLACE; break; default: assert(0); } if (ITEM_get_cas(it) != 0) { c->cmd = NREAD_CAS; } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_append_prepend(conn *c) { char *key; int nkey; int vlen; item *it; assert(c != NULL); key = binary_get_key(c); nkey = c->binary_header.request.keylen; vlen = c->binary_header.request.bodylen - nkey; if (settings.verbose > 1) { fprintf(stderr, "Value len is %d\n", vlen); } if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, 0, 0, vlen+2); if (it == 0) { if (! item_size_ok(nkey, 0, vlen + 2)) { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_E2BIG, NULL, vlen); } else { out_of_memory(c, "SERVER_ERROR Out of memory allocating item"); /* OOM calls eat the swallow value. Add here. */ c->sbytes = vlen; } /* swallow the data line */ c->write_and_go = conn_swallow; return; } ITEM_set_cas(it, c->binary_header.request.cas); switch (c->cmd) { case PROTOCOL_BINARY_CMD_APPEND: c->cmd = NREAD_APPEND; break; case PROTOCOL_BINARY_CMD_PREPEND: c->cmd = NREAD_PREPEND; break; default: assert(0); } c->item = it; c->ritem = ITEM_data(it); c->rlbytes = vlen; conn_set_state(c, conn_nread); c->substate = bin_read_set_value; } static void process_bin_flush(conn *c) { time_t exptime = 0; protocol_binary_request_flush* req = binary_get_request(c); rel_time_t new_oldest = 0; if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats write_bin_error(c, PROTOCOL_BINARY_RESPONSE_AUTH_ERROR, NULL, 0); return; } if (c->binary_header.request.extlen == sizeof(req->message.body)) { exptime = ntohl(req->message.body.expiration); } if (exptime > 0) { new_oldest = realtime(exptime); } else { new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); write_bin_response(c, NULL, 0, 0, 0); } static void process_bin_delete(conn *c) { item *it; protocol_binary_request_delete* req = binary_get_request(c); char* key = binary_get_key(c); size_t nkey = c->binary_header.request.keylen; assert(c != NULL); if (settings.verbose > 1) { int ii; fprintf(stderr, "Deleting "); for (ii = 0; ii < nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get(key, nkey, c, DONT_UPDATE); if (it) { uint64_t cas = ntohll(req->message.header.request.cas); if (cas == 0 || cas == ITEM_get_cas(it)) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); item_unlink(it); write_bin_response(c, NULL, 0, 0, 0); } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_EEXISTS, NULL, 0); } item_remove(it); /* release our reference */ } else { write_bin_error(c, PROTOCOL_BINARY_RESPONSE_KEY_ENOENT, NULL, 0); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } } static void complete_nread_binary(conn *c) { assert(c != NULL); assert(c->cmd >= 0); switch(c->substate) { case bin_reading_set_header: if (c->cmd == PROTOCOL_BINARY_CMD_APPEND || c->cmd == PROTOCOL_BINARY_CMD_PREPEND) { process_bin_append_prepend(c); } else { process_bin_update(c); } break; case bin_read_set_value: complete_update_bin(c); break; case bin_reading_get_key: case bin_reading_touch_key: process_bin_get_or_touch(c); break; case bin_reading_stat: process_bin_stat(c); break; case bin_reading_del_header: process_bin_delete(c); break; case bin_reading_incr_header: complete_incr_bin(c); break; case bin_read_flush_exptime: process_bin_flush(c); break; case bin_reading_sasl_auth: process_bin_sasl_auth(c); break; case bin_reading_sasl_auth_data: process_bin_complete_sasl_auth(c); break; default: fprintf(stderr, "Not handling substate %d\n", c->substate); assert(0); } } static void reset_cmd_handler(conn *c) { c->cmd = -1; c->substate = bin_no_state; if(c->item != NULL) { item_remove(c->item); c->item = NULL; } conn_shrink(c); if (c->rbytes > 0) { conn_set_state(c, conn_parse_cmd); } else { conn_set_state(c, conn_waiting); } } static void complete_nread(conn *c) { assert(c != NULL); assert(c->protocol == ascii_prot || c->protocol == binary_prot); if (c->protocol == ascii_prot) { complete_nread_ascii(c); } else if (c->protocol == binary_prot) { complete_nread_binary(c); } } /* Destination must always be chunked */ /* This should be part of item.c */ static int _store_item_copy_chunks(item *d_it, item *s_it, const int len) { item_chunk *dch = (item_chunk *) ITEM_data(d_it); /* Advance dch until we find free space */ while (dch->size == dch->used) { if (dch->next) { dch = dch->next; } else { break; } } if (s_it->it_flags & ITEM_CHUNKED) { int remain = len; item_chunk *sch = (item_chunk *) ITEM_data(s_it); int copied = 0; /* Fills dch's to capacity, not straight copy sch in case data is * being added or removed (ie append/prepend) */ while (sch && dch && remain) { assert(dch->used <= dch->size); int todo = (dch->size - dch->used < sch->used - copied) ? dch->size - dch->used : sch->used - copied; if (remain < todo) todo = remain; memcpy(dch->data + dch->used, sch->data + copied, todo); dch->used += todo; copied += todo; remain -= todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, remain); if (tch) { dch = tch; } else { return -1; } } assert(copied <= sch->used); if (copied == sch->used) { copied = 0; sch = sch->next; } } /* assert that the destination had enough space for the source */ assert(remain == 0); } else { int done = 0; /* Fill dch's via a non-chunked item. */ while (len > done && dch) { int todo = (dch->size - dch->used < len - done) ? dch->size - dch->used : len - done; //assert(dch->size - dch->used != 0); memcpy(dch->data + dch->used, ITEM_data(s_it) + done, todo); done += todo; dch->used += todo; assert(dch->used <= dch->size); if (dch->size == dch->used) { item_chunk *tch = do_item_alloc_chunk(dch, len - done); if (tch) { dch = tch; } else { return -1; } } } assert(len == done); } return 0; } static int _store_item_copy_data(int comm, item *old_it, item *new_it, item *add_it) { if (comm == NREAD_APPEND) { if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, old_it, old_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, add_it, add_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(old_it), old_it->nbytes); memcpy(ITEM_data(new_it) + old_it->nbytes - 2 /* CRLF */, ITEM_data(add_it), add_it->nbytes); } } else { /* NREAD_PREPEND */ if (new_it->it_flags & ITEM_CHUNKED) { if (_store_item_copy_chunks(new_it, add_it, add_it->nbytes - 2) == -1 || _store_item_copy_chunks(new_it, old_it, old_it->nbytes) == -1) { return -1; } } else { memcpy(ITEM_data(new_it), ITEM_data(add_it), add_it->nbytes); memcpy(ITEM_data(new_it) + add_it->nbytes - 2 /* CRLF */, ITEM_data(old_it), old_it->nbytes); } } return 0; } /* * Stores an item in the cache according to the semantics of one of the set * commands. In threaded mode, this is protected by the cache lock. * * Returns the state of storage. */ enum store_item_type do_store_item(item *it, int comm, conn *c, const uint32_t hv) { char *key = ITEM_key(it); item *old_it = do_item_get(key, it->nkey, hv, c, DONT_UPDATE); enum store_item_type stored = NOT_STORED; item *new_it = NULL; uint32_t flags; if (old_it != NULL && comm == NREAD_ADD) { /* add only adds a nonexistent item, but promote to head of LRU */ do_item_update(old_it); } else if (!old_it && (comm == NREAD_REPLACE || comm == NREAD_APPEND || comm == NREAD_PREPEND)) { /* replace only replaces an existing value; don't store */ } else if (comm == NREAD_CAS) { /* validate cas operation */ if(old_it == NULL) { // LRU expired stored = NOT_FOUND; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.cas_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); } else if (ITEM_get_cas(it) == ITEM_get_cas(old_it)) { // cas validates // it and old_it may belong to different classes. // I'm updating the stats for the one that's getting pushed out pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); item_replace(old_it, it, hv); stored = STORED; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(old_it)].cas_badval++; pthread_mutex_unlock(&c->thread->stats.mutex); if(settings.verbose > 1) { fprintf(stderr, "CAS: failure: expected %llu, got %llu\n", (unsigned long long)ITEM_get_cas(old_it), (unsigned long long)ITEM_get_cas(it)); } stored = EXISTS; } } else { int failed_alloc = 0; /* * Append - combine new and old record into single one. Here it's * atomic and thread-safe. */ if (comm == NREAD_APPEND || comm == NREAD_PREPEND) { /* * Validate CAS */ if (ITEM_get_cas(it) != 0) { // CAS much be equal if (ITEM_get_cas(it) != ITEM_get_cas(old_it)) { stored = EXISTS; } } if (stored == NOT_STORED) { /* we have it and old_it here - alloc memory to hold both */ /* flags was already lost - so recover them from ITEM_suffix(it) */ if (settings.inline_ascii_response) { flags = (uint32_t) strtoul(ITEM_suffix(old_it), (char **) NULL, 10); } else { flags = *((uint32_t *)ITEM_suffix(old_it)); } new_it = do_item_alloc(key, it->nkey, flags, old_it->exptime, it->nbytes + old_it->nbytes - 2 /* CRLF */); /* copy data from it and old_it to new_it */ if (new_it == NULL || _store_item_copy_data(comm, old_it, new_it, it) == -1) { failed_alloc = 1; stored = NOT_STORED; // failed data copy, free up. if (new_it != NULL) item_remove(new_it); } else { it = new_it; } } } if (stored == NOT_STORED && failed_alloc == 0) { if (old_it != NULL) item_replace(old_it, it, hv); else do_item_link(it, hv); c->cas = ITEM_get_cas(it); stored = STORED; } } if (old_it != NULL) do_item_remove(old_it); /* release our reference */ if (new_it != NULL) do_item_remove(new_it); if (stored == STORED) { c->cas = ITEM_get_cas(it); } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, stored, comm, ITEM_key(it), it->nkey, it->exptime, ITEM_clsid(it)); return stored; } typedef struct token_s { char *value; size_t length; } token_t; #define COMMAND_TOKEN 0 #define SUBCOMMAND_TOKEN 1 #define KEY_TOKEN 1 #define MAX_TOKENS 8 /* * Tokenize the command string by replacing whitespace with '\0' and update * the token array tokens with pointer to start of each token and length. * Returns total number of tokens. The last valid token is the terminal * token (value points to the first unprocessed character of the string and * length zero). * * Usage example: * * while(tokenize_command(command, ncommand, tokens, max_tokens) > 0) { * for(int ix = 0; tokens[ix].length != 0; ix++) { * ... * } * ncommand = tokens[ix].value - command; * command = tokens[ix].value; * } */ static size_t tokenize_command(char *command, token_t *tokens, const size_t max_tokens) { char *s, *e; size_t ntokens = 0; size_t len = strlen(command); unsigned int i = 0; assert(command != NULL && tokens != NULL && max_tokens > 1); s = e = command; for (i = 0; i < len; i++) { if (*e == ' ') { if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; *e = '\0'; if (ntokens == max_tokens - 1) { e++; s = e; /* so we don't add an extra token */ break; } } s = e + 1; } e++; } if (s != e) { tokens[ntokens].value = s; tokens[ntokens].length = e - s; ntokens++; } /* * If we scanned the whole string, the terminal value pointer is null, * otherwise it is the first unprocessed character. */ tokens[ntokens].value = *e == '\0' ? NULL : e; tokens[ntokens].length = 0; ntokens++; return ntokens; } /* set up a connection to write a buffer then free it, used for stats */ static void write_and_free(conn *c, char *buf, int bytes) { if (buf) { c->write_and_free = buf; c->wcurr = buf; c->wbytes = bytes; conn_set_state(c, conn_write); c->write_and_go = conn_new_cmd; } else { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } } static inline bool set_noreply_maybe(conn *c, token_t *tokens, size_t ntokens) { int noreply_index = ntokens - 2; /* NOTE: this function is not the first place where we are going to send the reply. We could send it instead from process_command() if the request line has wrong number of tokens. However parsing malformed line for "noreply" option is not reliable anyway, so it can't be helped. */ if (tokens[noreply_index].value && strcmp(tokens[noreply_index].value, "noreply") == 0) { c->noreply = true; } return c->noreply; } void append_stat(const char *name, ADD_STAT add_stats, conn *c, const char *fmt, ...) { char val_str[STAT_VAL_LEN]; int vlen; va_list ap; assert(name); assert(add_stats); assert(c); assert(fmt); va_start(ap, fmt); vlen = vsnprintf(val_str, sizeof(val_str) - 1, fmt, ap); va_end(ap); add_stats(name, strlen(name), val_str, vlen, c); } inline static void process_stats_detail(conn *c, const char *command) { assert(c != NULL); if (strcmp(command, "on") == 0) { settings.detail_enabled = 1; out_string(c, "OK"); } else if (strcmp(command, "off") == 0) { settings.detail_enabled = 0; out_string(c, "OK"); } else if (strcmp(command, "dump") == 0) { int len; char *stats = stats_prefix_dump(&len); write_and_free(c, stats, len); } else { out_string(c, "CLIENT_ERROR usage: stats detail on|off|dump"); } } /* return server specific stats only */ static void server_stats(ADD_STAT add_stats, conn *c) { pid_t pid = getpid(); rel_time_t now = current_time; struct thread_stats thread_stats; threadlocal_stats_aggregate(&thread_stats); struct slab_stats slab_stats; slab_stats_aggregate(&thread_stats, &slab_stats); #ifndef WIN32 struct rusage usage; getrusage(RUSAGE_SELF, &usage); #endif /* !WIN32 */ STATS_LOCK(); APPEND_STAT("pid", "%lu", (long)pid); APPEND_STAT("uptime", "%u", now - ITEM_UPDATE_INTERVAL); APPEND_STAT("time", "%ld", now + (long)process_started); APPEND_STAT("version", "%s", VERSION); APPEND_STAT("libevent", "%s", event_get_version()); APPEND_STAT("pointer_size", "%d", (int)(8 * sizeof(void *))); #ifndef WIN32 append_stat("rusage_user", add_stats, c, "%ld.%06ld", (long)usage.ru_utime.tv_sec, (long)usage.ru_utime.tv_usec); append_stat("rusage_system", add_stats, c, "%ld.%06ld", (long)usage.ru_stime.tv_sec, (long)usage.ru_stime.tv_usec); #endif /* !WIN32 */ APPEND_STAT("curr_connections", "%llu", (unsigned long long)stats_state.curr_conns - 1); APPEND_STAT("total_connections", "%llu", (unsigned long long)stats.total_conns); if (settings.maxconns_fast) { APPEND_STAT("rejected_connections", "%llu", (unsigned long long)stats.rejected_conns); } APPEND_STAT("connection_structures", "%u", stats_state.conn_structs); APPEND_STAT("reserved_fds", "%u", stats_state.reserved_fds); APPEND_STAT("cmd_get", "%llu", (unsigned long long)thread_stats.get_cmds); APPEND_STAT("cmd_set", "%llu", (unsigned long long)slab_stats.set_cmds); APPEND_STAT("cmd_flush", "%llu", (unsigned long long)thread_stats.flush_cmds); APPEND_STAT("cmd_touch", "%llu", (unsigned long long)thread_stats.touch_cmds); APPEND_STAT("get_hits", "%llu", (unsigned long long)slab_stats.get_hits); APPEND_STAT("get_misses", "%llu", (unsigned long long)thread_stats.get_misses); APPEND_STAT("get_expired", "%llu", (unsigned long long)thread_stats.get_expired); APPEND_STAT("get_flushed", "%llu", (unsigned long long)thread_stats.get_flushed); APPEND_STAT("delete_misses", "%llu", (unsigned long long)thread_stats.delete_misses); APPEND_STAT("delete_hits", "%llu", (unsigned long long)slab_stats.delete_hits); APPEND_STAT("incr_misses", "%llu", (unsigned long long)thread_stats.incr_misses); APPEND_STAT("incr_hits", "%llu", (unsigned long long)slab_stats.incr_hits); APPEND_STAT("decr_misses", "%llu", (unsigned long long)thread_stats.decr_misses); APPEND_STAT("decr_hits", "%llu", (unsigned long long)slab_stats.decr_hits); APPEND_STAT("cas_misses", "%llu", (unsigned long long)thread_stats.cas_misses); APPEND_STAT("cas_hits", "%llu", (unsigned long long)slab_stats.cas_hits); APPEND_STAT("cas_badval", "%llu", (unsigned long long)slab_stats.cas_badval); APPEND_STAT("touch_hits", "%llu", (unsigned long long)slab_stats.touch_hits); APPEND_STAT("touch_misses", "%llu", (unsigned long long)thread_stats.touch_misses); APPEND_STAT("auth_cmds", "%llu", (unsigned long long)thread_stats.auth_cmds); APPEND_STAT("auth_errors", "%llu", (unsigned long long)thread_stats.auth_errors); if (settings.idle_timeout) { APPEND_STAT("idle_kicks", "%llu", (unsigned long long)thread_stats.idle_kicks); } APPEND_STAT("bytes_read", "%llu", (unsigned long long)thread_stats.bytes_read); APPEND_STAT("bytes_written", "%llu", (unsigned long long)thread_stats.bytes_written); APPEND_STAT("limit_maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("accepting_conns", "%u", stats_state.accepting_conns); APPEND_STAT("listen_disabled_num", "%llu", (unsigned long long)stats.listen_disabled_num); APPEND_STAT("time_in_listen_disabled_us", "%llu", stats.time_in_listen_disabled_us); APPEND_STAT("threads", "%d", settings.num_threads); APPEND_STAT("conn_yields", "%llu", (unsigned long long)thread_stats.conn_yields); APPEND_STAT("hash_power_level", "%u", stats_state.hash_power_level); APPEND_STAT("hash_bytes", "%llu", (unsigned long long)stats_state.hash_bytes); APPEND_STAT("hash_is_expanding", "%u", stats_state.hash_is_expanding); if (settings.slab_reassign) { APPEND_STAT("slab_reassign_rescues", "%llu", stats.slab_reassign_rescues); APPEND_STAT("slab_reassign_chunk_rescues", "%llu", stats.slab_reassign_chunk_rescues); APPEND_STAT("slab_reassign_evictions_nomem", "%llu", stats.slab_reassign_evictions_nomem); APPEND_STAT("slab_reassign_inline_reclaim", "%llu", stats.slab_reassign_inline_reclaim); APPEND_STAT("slab_reassign_busy_items", "%llu", stats.slab_reassign_busy_items); APPEND_STAT("slab_reassign_running", "%u", stats_state.slab_reassign_running); APPEND_STAT("slabs_moved", "%llu", stats.slabs_moved); } if (settings.lru_crawler) { APPEND_STAT("lru_crawler_running", "%u", stats_state.lru_crawler_running); APPEND_STAT("lru_crawler_starts", "%u", stats.lru_crawler_starts); } if (settings.lru_maintainer_thread) { APPEND_STAT("lru_maintainer_juggles", "%llu", (unsigned long long)stats.lru_maintainer_juggles); } APPEND_STAT("malloc_fails", "%llu", (unsigned long long)stats.malloc_fails); APPEND_STAT("log_worker_dropped", "%llu", (unsigned long long)stats.log_worker_dropped); APPEND_STAT("log_worker_written", "%llu", (unsigned long long)stats.log_worker_written); APPEND_STAT("log_watcher_skipped", "%llu", (unsigned long long)stats.log_watcher_skipped); APPEND_STAT("log_watcher_sent", "%llu", (unsigned long long)stats.log_watcher_sent); STATS_UNLOCK(); } static void process_stat_settings(ADD_STAT add_stats, void *c) { assert(add_stats); APPEND_STAT("maxbytes", "%llu", (unsigned long long)settings.maxbytes); APPEND_STAT("maxconns", "%d", settings.maxconns); APPEND_STAT("tcpport", "%d", settings.port); APPEND_STAT("udpport", "%d", settings.udpport); APPEND_STAT("inter", "%s", settings.inter ? settings.inter : "NULL"); APPEND_STAT("verbosity", "%d", settings.verbose); APPEND_STAT("oldest", "%lu", (unsigned long)settings.oldest_live); APPEND_STAT("evictions", "%s", settings.evict_to_free ? "on" : "off"); APPEND_STAT("domain_socket", "%s", settings.socketpath ? settings.socketpath : "NULL"); APPEND_STAT("umask", "%o", settings.access); APPEND_STAT("growth_factor", "%.2f", settings.factor); APPEND_STAT("chunk_size", "%d", settings.chunk_size); APPEND_STAT("num_threads", "%d", settings.num_threads); APPEND_STAT("num_threads_per_udp", "%d", settings.num_threads_per_udp); APPEND_STAT("stat_key_prefix", "%c", settings.prefix_delimiter); APPEND_STAT("detail_enabled", "%s", settings.detail_enabled ? "yes" : "no"); APPEND_STAT("reqs_per_event", "%d", settings.reqs_per_event); APPEND_STAT("cas_enabled", "%s", settings.use_cas ? "yes" : "no"); APPEND_STAT("tcp_backlog", "%d", settings.backlog); APPEND_STAT("binding_protocol", "%s", prot_text(settings.binding_protocol)); APPEND_STAT("auth_enabled_sasl", "%s", settings.sasl ? "yes" : "no"); APPEND_STAT("item_size_max", "%d", settings.item_size_max); APPEND_STAT("maxconns_fast", "%s", settings.maxconns_fast ? "yes" : "no"); APPEND_STAT("hashpower_init", "%d", settings.hashpower_init); APPEND_STAT("slab_reassign", "%s", settings.slab_reassign ? "yes" : "no"); APPEND_STAT("slab_automove", "%d", settings.slab_automove); APPEND_STAT("slab_chunk_max", "%d", settings.slab_chunk_size_max); APPEND_STAT("lru_crawler", "%s", settings.lru_crawler ? "yes" : "no"); APPEND_STAT("lru_crawler_sleep", "%d", settings.lru_crawler_sleep); APPEND_STAT("lru_crawler_tocrawl", "%lu", (unsigned long)settings.lru_crawler_tocrawl); APPEND_STAT("tail_repair_time", "%d", settings.tail_repair_time); APPEND_STAT("flush_enabled", "%s", settings.flush_enabled ? "yes" : "no"); APPEND_STAT("dump_enabled", "%s", settings.dump_enabled ? "yes" : "no"); APPEND_STAT("hash_algorithm", "%s", settings.hash_algorithm); APPEND_STAT("lru_maintainer_thread", "%s", settings.lru_maintainer_thread ? "yes" : "no"); APPEND_STAT("lru_segmented", "%s", settings.lru_segmented ? "yes" : "no"); APPEND_STAT("hot_lru_pct", "%d", settings.hot_lru_pct); APPEND_STAT("warm_lru_pct", "%d", settings.warm_lru_pct); APPEND_STAT("hot_max_age", "%u", settings.hot_max_age); APPEND_STAT("warm_max_factor", "%.2f", settings.warm_max_factor); APPEND_STAT("temp_lru", "%s", settings.temp_lru ? "yes" : "no"); APPEND_STAT("temporary_ttl", "%u", settings.temporary_ttl); APPEND_STAT("idle_timeout", "%d", settings.idle_timeout); APPEND_STAT("watcher_logbuf_size", "%u", settings.logger_watcher_buf_size); APPEND_STAT("worker_logbuf_size", "%u", settings.logger_buf_size); APPEND_STAT("track_sizes", "%s", item_stats_sizes_status() ? "yes" : "no"); APPEND_STAT("inline_ascii_response", "%s", settings.inline_ascii_response ? "yes" : "no"); } static void conn_to_str(const conn *c, char *buf) { char addr_text[MAXPATHLEN]; if (!c) { strcpy(buf, "<null>"); } else if (c->state == conn_closed) { strcpy(buf, "<closed>"); } else { const char *protoname = "?"; struct sockaddr_in6 local_addr; struct sockaddr *addr = (void *)&c->request_addr; int af; unsigned short port = 0; /* For listen ports and idle UDP ports, show listen address */ if (c->state == conn_listening || (IS_UDP(c->transport) && c->state == conn_read)) { socklen_t local_addr_len = sizeof(local_addr); if (getsockname(c->sfd, (struct sockaddr *)&local_addr, &local_addr_len) == 0) { addr = (struct sockaddr *)&local_addr; } } af = addr->sa_family; addr_text[0] = '\0'; switch (af) { case AF_INET: (void) inet_ntop(af, &((struct sockaddr_in *)addr)->sin_addr, addr_text, sizeof(addr_text) - 1); port = ntohs(((struct sockaddr_in *)addr)->sin_port); protoname = IS_UDP(c->transport) ? "udp" : "tcp"; break; case AF_INET6: addr_text[0] = '['; addr_text[1] = '\0'; if (inet_ntop(af, &((struct sockaddr_in6 *)addr)->sin6_addr, addr_text + 1, sizeof(addr_text) - 2)) { strcat(addr_text, "]"); } port = ntohs(((struct sockaddr_in6 *)addr)->sin6_port); protoname = IS_UDP(c->transport) ? "udp6" : "tcp6"; break; case AF_UNIX: strncpy(addr_text, ((struct sockaddr_un *)addr)->sun_path, sizeof(addr_text) - 1); addr_text[sizeof(addr_text)-1] = '\0'; protoname = "unix"; break; } if (strlen(addr_text) < 2) { /* Most likely this is a connected UNIX-domain client which * has no peer socket address, but there's no portable way * to tell for sure. */ sprintf(addr_text, "<AF %d>", af); } if (port) { sprintf(buf, "%s:%s:%u", protoname, addr_text, port); } else { sprintf(buf, "%s:%s", protoname, addr_text); } } } static void process_stats_conns(ADD_STAT add_stats, void *c) { int i; char key_str[STAT_KEY_LEN]; char val_str[STAT_VAL_LEN]; char conn_name[MAXPATHLEN + sizeof("unix:")]; int klen = 0, vlen = 0; assert(add_stats); for (i = 0; i < max_fds; i++) { if (conns[i]) { /* This is safe to do unlocked because conns are never freed; the * worst that'll happen will be a minor inconsistency in the * output -- not worth the complexity of the locking that'd be * required to prevent it. */ if (conns[i]->state != conn_closed) { conn_to_str(conns[i], conn_name); APPEND_NUM_STAT(i, "addr", "%s", conn_name); APPEND_NUM_STAT(i, "state", "%s", state_text(conns[i]->state)); APPEND_NUM_STAT(i, "secs_since_last_cmd", "%d", current_time - conns[i]->last_cmd_time); } } } } static void process_stat(conn *c, token_t *tokens, const size_t ntokens) { const char *subcommand = tokens[SUBCOMMAND_TOKEN].value; assert(c != NULL); if (ntokens < 2) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (ntokens == 2) { server_stats(&append_stats, c); (void)get_stats(NULL, 0, &append_stats, c); } else if (strcmp(subcommand, "reset") == 0) { stats_reset(); out_string(c, "RESET"); return ; } else if (strcmp(subcommand, "detail") == 0) { /* NOTE: how to tackle detail with binary? */ if (ntokens < 4) process_stats_detail(c, ""); /* outputs the error message */ else process_stats_detail(c, tokens[2].value); /* Output already generated */ return ; } else if (strcmp(subcommand, "settings") == 0) { process_stat_settings(&append_stats, c); } else if (strcmp(subcommand, "cachedump") == 0) { char *buf; unsigned int bytes, id, limit = 0; if (!settings.dump_enabled) { out_string(c, "CLIENT_ERROR stats cachedump not allowed"); return; } if (ntokens < 5) { out_string(c, "CLIENT_ERROR bad command line"); return; } if (!safe_strtoul(tokens[2].value, &id) || !safe_strtoul(tokens[3].value, &limit)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (id >= MAX_NUMBER_OF_SLAB_CLASSES) { out_string(c, "CLIENT_ERROR Illegal slab id"); return; } buf = item_cachedump(id, limit, &bytes); write_and_free(c, buf, bytes); return ; } else if (strcmp(subcommand, "conns") == 0) { process_stats_conns(&append_stats, c); } else { /* getting here means that the subcommand is either engine specific or is invalid. query the engine and see. */ if (get_stats(subcommand, strlen(subcommand), &append_stats, c)) { if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } else { out_string(c, "ERROR"); } return ; } /* append terminator and start the transfer */ append_stats(NULL, 0, NULL, 0, c); if (c->stats.buffer == NULL) { out_of_memory(c, "SERVER_ERROR out of memory writing stats"); } else { write_and_free(c, c->stats.buffer, c->stats.offset); c->stats.buffer = NULL; } } static inline int make_ascii_get_suffix(char *suffix, item *it, bool return_cas) { char *p; if (!settings.inline_ascii_response) { *suffix = ' '; p = itoa_u32(*((uint32_t *) ITEM_suffix(it)), suffix+1); *p = ' '; p = itoa_u32(it->nbytes-2, p+1); } else { p = suffix; } if (return_cas) { *p = ' '; p = itoa_u64(ITEM_get_cas(it), p+1); } *p = '\r'; *(p+1) = '\n'; *(p+2) = '\0'; return (p - suffix) + 2; } /* ntokens is overwritten here... shrug.. */ static inline void process_get_command(conn *c, token_t *tokens, size_t ntokens, bool return_cas) { char *key; size_t nkey; int i = 0; item *it; token_t *key_token = &tokens[KEY_TOKEN]; char *suffix; assert(c != NULL); do { while(key_token->length != 0) { key = key_token->value; nkey = key_token->length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } it = item_get(key, nkey, c, DO_UPDATE); if (settings.detail_enabled) { stats_prefix_record_get(key, nkey, NULL != it); } if (it) { if (i >= c->isize) { item **new_list = realloc(c->ilist, sizeof(item *) * c->isize * 2); if (new_list) { c->isize *= 2; c->ilist = new_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } /* * Construct the response. Each hit adds three elements to the * outgoing data list: * "VALUE " * key * " " + flags + " " + data length + "\r\n" + data (with \r\n) */ if (return_cas || !settings.inline_ascii_response) { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); /* Goofy mid-flight realloc. */ if (i >= c->suffixsize) { char **new_suffix_list = realloc(c->suffixlist, sizeof(char *) * c->suffixsize * 2); if (new_suffix_list) { c->suffixsize *= 2; c->suffixlist = new_suffix_list; } else { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); item_remove(it); break; } } suffix = do_cache_alloc(c->thread->suffix_cache); if (suffix == NULL) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); out_of_memory(c, "SERVER_ERROR out of memory making CAS suffix"); item_remove(it); while (i-- > 0) { item_remove(*(c->ilist + i)); } return; } *(c->suffixlist + i) = suffix; int suffix_len = make_ascii_get_suffix(suffix, it, return_cas); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0 || (settings.inline_ascii_response && add_iov(c, ITEM_suffix(it), it->nsuffix - 2) != 0) || add_iov(c, suffix, suffix_len) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { add_iov(c, ITEM_data(it), it->nbytes); } else if (add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } else { MEMCACHED_COMMAND_GET(c->sfd, ITEM_key(it), it->nkey, it->nbytes, ITEM_get_cas(it)); if (add_iov(c, "VALUE ", 6) != 0 || add_iov(c, ITEM_key(it), it->nkey) != 0) { item_remove(it); break; } if ((it->it_flags & ITEM_CHUNKED) == 0) { if (add_iov(c, ITEM_suffix(it), it->nsuffix + it->nbytes) != 0) { item_remove(it); break; } } else if (add_iov(c, ITEM_suffix(it), it->nsuffix) != 0 || add_chunked_item_iovs(c, it, it->nbytes) != 0) { item_remove(it); break; } } if (settings.verbose > 1) { int ii; fprintf(stderr, ">%d sending key ", c->sfd); for (ii = 0; ii < it->nkey; ++ii) { fprintf(stderr, "%c", key[ii]); } fprintf(stderr, "\n"); } /* item_get() has incremented it->refcount for us */ pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].get_hits++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); *(c->ilist + i) = it; i++; } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.get_misses++; c->thread->stats.get_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); MEMCACHED_COMMAND_GET(c->sfd, key, nkey, -1, 0); } key_token++; } /* * If the command string hasn't been fully processed, get the next set * of tokens. */ if(key_token->value != NULL) { ntokens = tokenize_command(key_token->value, tokens, MAX_TOKENS); key_token = tokens; } } while(key_token->value != NULL); c->icurr = c->ilist; c->ileft = i; if (return_cas || !settings.inline_ascii_response) { c->suffixcurr = c->suffixlist; c->suffixleft = i; } if (settings.verbose > 1) fprintf(stderr, ">%d END\n", c->sfd); /* If the loop was terminated because of out-of-memory, it is not reliable to add END\r\n to the buffer, because it might not end in \r\n. So we send SERVER_ERROR instead. */ if (key_token->value != NULL || add_iov(c, "END\r\n", 5) != 0 || (IS_UDP(c->transport) && build_udp_headers(c) != 0)) { out_of_memory(c, "SERVER_ERROR out of memory writing get response"); } else { conn_set_state(c, conn_mwrite); c->msgcurr = 0; } } static void process_update_command(conn *c, token_t *tokens, const size_t ntokens, int comm, bool handle_cas) { char *key; size_t nkey; unsigned int flags; int32_t exptime_int = 0; time_t exptime; int vlen; uint64_t req_cas_id=0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (! (safe_strtoul(tokens[2].value, (uint32_t *)&flags) && safe_strtol(tokens[3].value, &exptime_int) && safe_strtol(tokens[4].value, (int32_t *)&vlen))) { out_string(c, "CLIENT_ERROR bad command line format"); return; } /* Ubuntu 8.04 breaks when I pass exptime to safe_strtol */ exptime = exptime_int; /* Negative exptimes can underflow and end up immortal. realtime() will immediately expire values that are greater than REALTIME_MAXDELTA, but less than process_started, so lets aim for that. */ if (exptime < 0) exptime = REALTIME_MAXDELTA + 1; // does cas value exist? if (handle_cas) { if (!safe_strtoull(tokens[5].value, &req_cas_id)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } if (vlen < 0 || vlen > (INT_MAX - 2)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } vlen += 2; if (settings.detail_enabled) { stats_prefix_record_set(key, nkey); } it = item_alloc(key, nkey, flags, realtime(exptime), vlen); if (it == 0) { enum store_item_type status; if (! item_size_ok(nkey, flags, vlen)) { out_string(c, "SERVER_ERROR object too large for cache"); status = TOO_LARGE; } else { out_of_memory(c, "SERVER_ERROR out of memory storing object"); status = NO_MEMORY; } LOGGER_LOG(c->thread->l, LOG_MUTATIONS, LOGGER_ITEM_STORE, NULL, status, comm, key, nkey, 0, 0); /* swallow the data line */ c->write_and_go = conn_swallow; c->sbytes = vlen; /* Avoid stale data persisting in cache because we failed alloc. * Unacceptable for SET. Anywhere else too? */ if (comm == NREAD_SET) { it = item_get(key, nkey, c, DONT_UPDATE); if (it) { item_unlink(it); item_remove(it); } } return; } ITEM_set_cas(it, req_cas_id); c->item = it; c->ritem = ITEM_data(it); c->rlbytes = it->nbytes; c->cmd = comm; conn_set_state(c, conn_nread); } static void process_touch_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; int32_t exptime_int = 0; item *it; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtol(tokens[2].value, &exptime_int)) { out_string(c, "CLIENT_ERROR invalid exptime argument"); return; } it = item_touch(key, nkey, realtime(exptime_int), c); if (it) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.slab_stats[ITEM_clsid(it)].touch_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "TOUCHED"); item_remove(it); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.touch_cmds++; c->thread->stats.touch_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_arithmetic_command(conn *c, token_t *tokens, const size_t ntokens, const bool incr) { char temp[INCR_MAX_STORAGE_LEN]; uint64_t delta; char *key; size_t nkey; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (tokens[KEY_TOKEN].length > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if (!safe_strtoull(tokens[2].value, &delta)) { out_string(c, "CLIENT_ERROR invalid numeric delta argument"); return; } switch(add_delta(c, key, nkey, incr, delta, temp, NULL)) { case OK: out_string(c, temp); break; case NON_NUMERIC: out_string(c, "CLIENT_ERROR cannot increment or decrement non-numeric value"); break; case EOM: out_of_memory(c, "SERVER_ERROR out of memory"); break; case DELTA_ITEM_NOT_FOUND: pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.incr_misses++; } else { c->thread->stats.decr_misses++; } pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); break; case DELTA_ITEM_CAS_MISMATCH: break; /* Should never get here */ } } /* * adds a delta value to a numeric item. * * c connection requesting the operation * it item to adjust * incr true to increment value, false to decrement * delta amount to adjust value by * buf buffer for response string * * returns a response string to send back to the client. */ enum delta_result_type do_add_delta(conn *c, const char *key, const size_t nkey, const bool incr, const int64_t delta, char *buf, uint64_t *cas, const uint32_t hv) { char *ptr; uint64_t value; int res; item *it; it = do_item_get(key, nkey, hv, c, DONT_UPDATE); if (!it) { return DELTA_ITEM_NOT_FOUND; } /* Can't delta zero byte values. 2-byte are the "\r\n" */ /* Also can't delta for chunked items. Too large to be a number */ if (it->nbytes <= 2 || (it->it_flags & ITEM_CHUNKED) != 0) { return NON_NUMERIC; } if (cas != NULL && *cas != 0 && ITEM_get_cas(it) != *cas) { do_item_remove(it); return DELTA_ITEM_CAS_MISMATCH; } ptr = ITEM_data(it); if (!safe_strtoull(ptr, &value)) { do_item_remove(it); return NON_NUMERIC; } if (incr) { value += delta; MEMCACHED_COMMAND_INCR(c->sfd, ITEM_key(it), it->nkey, value); } else { if(delta > value) { value = 0; } else { value -= delta; } MEMCACHED_COMMAND_DECR(c->sfd, ITEM_key(it), it->nkey, value); } pthread_mutex_lock(&c->thread->stats.mutex); if (incr) { c->thread->stats.slab_stats[ITEM_clsid(it)].incr_hits++; } else { c->thread->stats.slab_stats[ITEM_clsid(it)].decr_hits++; } pthread_mutex_unlock(&c->thread->stats.mutex); snprintf(buf, INCR_MAX_STORAGE_LEN, "%llu", (unsigned long long)value); res = strlen(buf); /* refcount == 2 means we are the only ones holding the item, and it is * linked. We hold the item's lock in this function, so refcount cannot * increase. */ if (res + 2 <= it->nbytes && it->refcount == 2) { /* replace in-place */ /* When changing the value without replacing the item, we need to update the CAS on the existing item. */ /* We also need to fiddle it in the sizes tracker in case the tracking * was enabled at runtime, since it relies on the CAS value to know * whether to remove an item or not. */ item_stats_sizes_remove(it); ITEM_set_cas(it, (settings.use_cas) ? get_cas_id() : 0); item_stats_sizes_add(it); memcpy(ITEM_data(it), buf, res); memset(ITEM_data(it) + res, ' ', it->nbytes - res - 2); do_item_update(it); } else if (it->refcount > 1) { item *new_it; uint32_t flags; if (settings.inline_ascii_response) { flags = (uint32_t) strtoul(ITEM_suffix(it)+1, (char **) NULL, 10); } else { flags = *((uint32_t *)ITEM_suffix(it)); } new_it = do_item_alloc(ITEM_key(it), it->nkey, flags, it->exptime, res + 2); if (new_it == 0) { do_item_remove(it); return EOM; } memcpy(ITEM_data(new_it), buf, res); memcpy(ITEM_data(new_it) + res, "\r\n", 2); item_replace(it, new_it, hv); // Overwrite the older item's CAS with our new CAS since we're // returning the CAS of the old item below. ITEM_set_cas(it, (settings.use_cas) ? ITEM_get_cas(new_it) : 0); do_item_remove(new_it); /* release our reference */ } else { /* Should never get here. This means we somehow fetched an unlinked * item. TODO: Add a counter? */ if (settings.verbose) { fprintf(stderr, "Tried to do incr/decr on invalid item\n"); } if (it->refcount == 1) do_item_remove(it); return DELTA_ITEM_NOT_FOUND; } if (cas) { *cas = ITEM_get_cas(it); /* swap the incoming CAS value */ } do_item_remove(it); /* release our reference */ return OK; } static void process_delete_command(conn *c, token_t *tokens, const size_t ntokens) { char *key; size_t nkey; item *it; assert(c != NULL); if (ntokens > 3) { bool hold_is_zero = strcmp(tokens[KEY_TOKEN+1].value, "0") == 0; bool sets_noreply = set_noreply_maybe(c, tokens, ntokens); bool valid = (ntokens == 4 && (hold_is_zero || sets_noreply)) || (ntokens == 5 && hold_is_zero && sets_noreply); if (!valid) { out_string(c, "CLIENT_ERROR bad command line format. " "Usage: delete <key> [noreply]"); return; } } key = tokens[KEY_TOKEN].value; nkey = tokens[KEY_TOKEN].length; if(nkey > KEY_MAX_LENGTH) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (settings.detail_enabled) { stats_prefix_record_delete(key, nkey); } it = item_get(key, nkey, c, DONT_UPDATE); if (it) { MEMCACHED_COMMAND_DELETE(c->sfd, ITEM_key(it), it->nkey); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.slab_stats[ITEM_clsid(it)].delete_hits++; pthread_mutex_unlock(&c->thread->stats.mutex); item_unlink(it); item_remove(it); /* release our reference */ out_string(c, "DELETED"); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.delete_misses++; pthread_mutex_unlock(&c->thread->stats.mutex); out_string(c, "NOT_FOUND"); } } static void process_verbosity_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[1].value, NULL, 10); settings.verbose = level > MAX_VERBOSITY_LEVEL ? MAX_VERBOSITY_LEVEL : level; out_string(c, "OK"); return; } static void process_slabs_automove_command(conn *c, token_t *tokens, const size_t ntokens) { unsigned int level; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); level = strtoul(tokens[2].value, NULL, 10); if (level == 0) { settings.slab_automove = 0; } else if (level == 1 || level == 2) { settings.slab_automove = level; } else { out_string(c, "ERROR"); return; } out_string(c, "OK"); return; } /* TODO: decide on syntax for sampling? */ static void process_watch_command(conn *c, token_t *tokens, const size_t ntokens) { uint16_t f = 0; int x; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (ntokens > 2) { for (x = COMMAND_TOKEN + 1; x < ntokens - 1; x++) { if ((strcmp(tokens[x].value, "rawcmds") == 0)) { f |= LOG_RAWCMDS; } else if ((strcmp(tokens[x].value, "evictions") == 0)) { f |= LOG_EVICTIONS; } else if ((strcmp(tokens[x].value, "fetchers") == 0)) { f |= LOG_FETCHERS; } else if ((strcmp(tokens[x].value, "mutations") == 0)) { f |= LOG_MUTATIONS; } else if ((strcmp(tokens[x].value, "sysevents") == 0)) { f |= LOG_SYSEVENTS; } else { out_string(c, "ERROR"); return; } } } else { f |= LOG_FETCHERS; } switch(logger_add_watcher(c, c->sfd, f)) { case LOGGER_ADD_WATCHER_TOO_MANY: out_string(c, "WATCHER_TOO_MANY log watcher limit reached"); break; case LOGGER_ADD_WATCHER_FAILED: out_string(c, "WATCHER_FAILED failed to add log watcher"); break; case LOGGER_ADD_WATCHER_OK: conn_set_state(c, conn_watch); event_del(&c->event); break; } } static void process_memlimit_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t memlimit; assert(c != NULL); set_noreply_maybe(c, tokens, ntokens); if (!safe_strtoul(tokens[1].value, &memlimit)) { out_string(c, "ERROR"); } else { if (memlimit < 8) { out_string(c, "MEMLIMIT_TOO_SMALL cannot set maxbytes to less than 8m"); } else { if (memlimit > 1000000000) { out_string(c, "MEMLIMIT_ADJUST_FAILED input value is megabytes not bytes"); } else if (slabs_adjust_mem_limit((size_t) memlimit * 1024 * 1024)) { if (settings.verbose > 0) { fprintf(stderr, "maxbytes adjusted to %llum\n", (unsigned long long)memlimit); } out_string(c, "OK"); } else { out_string(c, "MEMLIMIT_ADJUST_FAILED out of bounds or unable to adjust"); } } } } static void process_lru_command(conn *c, token_t *tokens, const size_t ntokens) { uint32_t pct_hot; uint32_t pct_warm; uint32_t hot_age; int32_t ttl; double factor; set_noreply_maybe(c, tokens, ntokens); if (strcmp(tokens[1].value, "tune") == 0 && ntokens >= 7) { if (!safe_strtoul(tokens[2].value, &pct_hot) || !safe_strtoul(tokens[3].value, &pct_warm) || !safe_strtoul(tokens[4].value, &hot_age) || !safe_strtod(tokens[5].value, &factor)) { out_string(c, "ERROR"); } else { if (pct_hot + pct_warm > 80) { out_string(c, "ERROR hot and warm pcts must not exceed 80"); } else if (factor <= 0) { out_string(c, "ERROR cold age factor must be greater than 0"); } else { settings.hot_lru_pct = pct_hot; settings.warm_lru_pct = pct_warm; settings.hot_max_age = hot_age; settings.warm_max_factor = factor; out_string(c, "OK"); } } } else if (strcmp(tokens[1].value, "mode") == 0 && ntokens >= 3 && settings.lru_maintainer_thread) { if (strcmp(tokens[2].value, "flat") == 0) { settings.lru_segmented = false; out_string(c, "OK"); } else if (strcmp(tokens[2].value, "segmented") == 0) { settings.lru_segmented = true; out_string(c, "OK"); } else { out_string(c, "ERROR"); } } else if (strcmp(tokens[1].value, "temp_ttl") == 0 && ntokens >= 3 && settings.lru_maintainer_thread) { if (!safe_strtol(tokens[2].value, &ttl)) { out_string(c, "ERROR"); } else { if (ttl < 0) { settings.temp_lru = false; } else { settings.temp_lru = true; settings.temporary_ttl = ttl; } out_string(c, "OK"); } } else { out_string(c, "ERROR"); } } static void process_command(conn *c, char *command) { token_t tokens[MAX_TOKENS]; size_t ntokens; int comm; assert(c != NULL); MEMCACHED_PROCESS_COMMAND_START(c->sfd, c->rcurr, c->rbytes); if (settings.verbose > 1) fprintf(stderr, "<%d %s\n", c->sfd, command); /* * for commands set/add/replace, we build an item and read the data * directly into it, then continue in nread_complete(). */ c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR out of memory preparing response"); return; } ntokens = tokenize_command(command, tokens, MAX_TOKENS); if (ntokens >= 3 && ((strcmp(tokens[COMMAND_TOKEN].value, "get") == 0) || (strcmp(tokens[COMMAND_TOKEN].value, "bget") == 0))) { process_get_command(c, tokens, ntokens, false); } else if ((ntokens == 6 || ntokens == 7) && ((strcmp(tokens[COMMAND_TOKEN].value, "add") == 0 && (comm = NREAD_ADD)) || (strcmp(tokens[COMMAND_TOKEN].value, "set") == 0 && (comm = NREAD_SET)) || (strcmp(tokens[COMMAND_TOKEN].value, "replace") == 0 && (comm = NREAD_REPLACE)) || (strcmp(tokens[COMMAND_TOKEN].value, "prepend") == 0 && (comm = NREAD_PREPEND)) || (strcmp(tokens[COMMAND_TOKEN].value, "append") == 0 && (comm = NREAD_APPEND)) )) { process_update_command(c, tokens, ntokens, comm, false); } else if ((ntokens == 7 || ntokens == 8) && (strcmp(tokens[COMMAND_TOKEN].value, "cas") == 0 && (comm = NREAD_CAS))) { process_update_command(c, tokens, ntokens, comm, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "incr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 1); } else if (ntokens >= 3 && (strcmp(tokens[COMMAND_TOKEN].value, "gets") == 0)) { process_get_command(c, tokens, ntokens, true); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "decr") == 0)) { process_arithmetic_command(c, tokens, ntokens, 0); } else if (ntokens >= 3 && ntokens <= 5 && (strcmp(tokens[COMMAND_TOKEN].value, "delete") == 0)) { process_delete_command(c, tokens, ntokens); } else if ((ntokens == 4 || ntokens == 5) && (strcmp(tokens[COMMAND_TOKEN].value, "touch") == 0)) { process_touch_command(c, tokens, ntokens); } else if (ntokens >= 2 && (strcmp(tokens[COMMAND_TOKEN].value, "stats") == 0)) { process_stat(c, tokens, ntokens); } else if (ntokens >= 2 && ntokens <= 4 && (strcmp(tokens[COMMAND_TOKEN].value, "flush_all") == 0)) { time_t exptime = 0; rel_time_t new_oldest = 0; set_noreply_maybe(c, tokens, ntokens); pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.flush_cmds++; pthread_mutex_unlock(&c->thread->stats.mutex); if (!settings.flush_enabled) { // flush_all is not allowed but we log it on stats out_string(c, "CLIENT_ERROR flush_all not allowed"); return; } if (ntokens != (c->noreply ? 3 : 2)) { exptime = strtol(tokens[1].value, NULL, 10); if(errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } } /* If exptime is zero realtime() would return zero too, and realtime(exptime) - 1 would overflow to the max unsigned value. So we process exptime == 0 the same way we do when no delay is given at all. */ if (exptime > 0) { new_oldest = realtime(exptime); } else { /* exptime == 0 */ new_oldest = current_time; } if (settings.use_cas) { settings.oldest_live = new_oldest - 1; if (settings.oldest_live <= current_time) settings.oldest_cas = get_cas_id(); } else { settings.oldest_live = new_oldest; } out_string(c, "OK"); return; } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "version") == 0)) { out_string(c, "VERSION " VERSION); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "quit") == 0)) { conn_set_state(c, conn_closing); } else if (ntokens == 2 && (strcmp(tokens[COMMAND_TOKEN].value, "shutdown") == 0)) { if (settings.shutdown_command) { conn_set_state(c, conn_closing); raise(SIGINT); } else { out_string(c, "ERROR: shutdown not enabled"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "slabs") == 0) { if (ntokens == 5 && strcmp(tokens[COMMAND_TOKEN + 1].value, "reassign") == 0) { int src, dst, rv; if (settings.slab_reassign == false) { out_string(c, "CLIENT_ERROR slab reassignment disabled"); return; } src = strtol(tokens[2].value, NULL, 10); dst = strtol(tokens[3].value, NULL, 10); if (errno == ERANGE) { out_string(c, "CLIENT_ERROR bad command line format"); return; } rv = slabs_reassign(src, dst); switch (rv) { case REASSIGN_OK: out_string(c, "OK"); break; case REASSIGN_RUNNING: out_string(c, "BUSY currently processing reassign request"); break; case REASSIGN_BADCLASS: out_string(c, "BADCLASS invalid src or dst class id"); break; case REASSIGN_NOSPARE: out_string(c, "NOSPARE source class has no spare pages"); break; case REASSIGN_SRC_DST_SAME: out_string(c, "SAME src and dst class are identical"); break; } return; } else if (ntokens == 4 && (strcmp(tokens[COMMAND_TOKEN + 1].value, "automove") == 0)) { process_slabs_automove_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "lru_crawler") == 0) { if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "crawl") == 0) { int rv; if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } rv = lru_crawler_crawl(tokens[2].value, CRAWLER_EXPIRED, NULL, 0); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "metadump") == 0) { if (settings.lru_crawler == false) { out_string(c, "CLIENT_ERROR lru crawler disabled"); return; } if (!settings.dump_enabled) { out_string(c, "ERROR metadump not allowed"); return; } int rv = lru_crawler_crawl(tokens[2].value, CRAWLER_METADUMP, c, c->sfd); switch(rv) { case CRAWLER_OK: out_string(c, "OK"); // TODO: Don't reuse conn_watch here. conn_set_state(c, conn_watch); event_del(&c->event); break; case CRAWLER_RUNNING: out_string(c, "BUSY currently processing crawler request"); break; case CRAWLER_BADCLASS: out_string(c, "BADCLASS invalid class id"); break; case CRAWLER_NOTSTARTED: out_string(c, "NOTSTARTED no items to crawl"); break; case CRAWLER_ERROR: out_string(c, "ERROR an unknown error happened"); break; } return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "tocrawl") == 0) { uint32_t tocrawl; if (!safe_strtoul(tokens[2].value, &tocrawl)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } settings.lru_crawler_tocrawl = tocrawl; out_string(c, "OK"); return; } else if (ntokens == 4 && strcmp(tokens[COMMAND_TOKEN + 1].value, "sleep") == 0) { uint32_t tosleep; if (!safe_strtoul(tokens[2].value, &tosleep)) { out_string(c, "CLIENT_ERROR bad command line format"); return; } if (tosleep > 1000000) { out_string(c, "CLIENT_ERROR sleep must be one second or less"); return; } settings.lru_crawler_sleep = tosleep; out_string(c, "OK"); return; } else if (ntokens == 3) { if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "enable") == 0)) { if (start_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to start lru crawler thread"); } } else if ((strcmp(tokens[COMMAND_TOKEN + 1].value, "disable") == 0)) { if (stop_item_crawler_thread() == 0) { out_string(c, "OK"); } else { out_string(c, "ERROR failed to stop lru crawler thread"); } } else { out_string(c, "ERROR"); } return; } else { out_string(c, "ERROR"); } } else if (ntokens > 1 && strcmp(tokens[COMMAND_TOKEN].value, "watch") == 0) { process_watch_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "cache_memlimit") == 0)) { process_memlimit_command(c, tokens, ntokens); } else if ((ntokens == 3 || ntokens == 4) && (strcmp(tokens[COMMAND_TOKEN].value, "verbosity") == 0)) { process_verbosity_command(c, tokens, ntokens); } else if (ntokens >= 3 && strcmp(tokens[COMMAND_TOKEN].value, "lru") == 0) { process_lru_command(c, tokens, ntokens); } else { out_string(c, "ERROR"); } return; } /* * if we have a complete line in the buffer, process it. */ static int try_read_command(conn *c) { assert(c != NULL); assert(c->rcurr <= (c->rbuf + c->rsize)); assert(c->rbytes > 0); if (c->protocol == negotiating_prot || c->transport == udp_transport) { if ((unsigned char)c->rbuf[0] == (unsigned char)PROTOCOL_BINARY_REQ) { c->protocol = binary_prot; } else { c->protocol = ascii_prot; } if (settings.verbose > 1) { fprintf(stderr, "%d: Client using the %s protocol\n", c->sfd, prot_text(c->protocol)); } } if (c->protocol == binary_prot) { /* Do we have the complete packet header? */ if (c->rbytes < sizeof(c->binary_header)) { /* need more data! */ return 0; } else { #ifdef NEED_ALIGN if (((long)(c->rcurr)) % 8 != 0) { /* must realign input buffer */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; if (settings.verbose > 1) { fprintf(stderr, "%d: Realign input buffer\n", c->sfd); } } #endif protocol_binary_request_header* req; req = (protocol_binary_request_header*)c->rcurr; if (settings.verbose > 1) { /* Dump the packet before we convert it to host order */ int ii; fprintf(stderr, "<%d Read binary protocol data:", c->sfd); for (ii = 0; ii < sizeof(req->bytes); ++ii) { if (ii % 4 == 0) { fprintf(stderr, "\n<%d ", c->sfd); } fprintf(stderr, " 0x%02x", req->bytes[ii]); } fprintf(stderr, "\n"); } c->binary_header = *req; c->binary_header.request.keylen = ntohs(req->request.keylen); c->binary_header.request.bodylen = ntohl(req->request.bodylen); c->binary_header.request.cas = ntohll(req->request.cas); if (c->binary_header.request.magic != PROTOCOL_BINARY_REQ) { if (settings.verbose) { fprintf(stderr, "Invalid magic: %x\n", c->binary_header.request.magic); } conn_set_state(c, conn_closing); return -1; } c->msgcurr = 0; c->msgused = 0; c->iovused = 0; if (add_msghdr(c) != 0) { out_of_memory(c, "SERVER_ERROR Out of memory allocating headers"); return 0; } c->cmd = c->binary_header.request.opcode; c->keylen = c->binary_header.request.keylen; c->opaque = c->binary_header.request.opaque; /* clear the returned cas value */ c->cas = 0; dispatch_bin_command(c); c->rbytes -= sizeof(c->binary_header); c->rcurr += sizeof(c->binary_header); } } else { char *el, *cont; if (c->rbytes == 0) return 0; el = memchr(c->rcurr, '\n', c->rbytes); if (!el) { if (c->rbytes > 1024) { /* * We didn't have a '\n' in the first k. This _has_ to be a * large multiget, if not we should just nuke the connection. */ char *ptr = c->rcurr; while (*ptr == ' ') { /* ignore leading whitespaces */ ++ptr; } if (ptr - c->rcurr > 100 || (strncmp(ptr, "get ", 4) && strncmp(ptr, "gets ", 5))) { conn_set_state(c, conn_closing); return 1; } } return 0; } cont = el + 1; if ((el - c->rcurr) > 1 && *(el - 1) == '\r') { el--; } *el = '\0'; assert(cont <= (c->rcurr + c->rbytes)); c->last_cmd_time = current_time; process_command(c, c->rcurr); c->rbytes -= (cont - c->rcurr); c->rcurr = cont; assert(c->rcurr <= (c->rbuf + c->rsize)); } return 1; } /* * read a UDP request. */ static enum try_read_result try_read_udp(conn *c) { int res; assert(c != NULL); c->request_addr_size = sizeof(c->request_addr); res = recvfrom(c->sfd, c->rbuf, c->rsize, 0, (struct sockaddr *)&c->request_addr, &c->request_addr_size); if (res > 8) { unsigned char *buf = (unsigned char *)c->rbuf; pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* Beginning of UDP packet is the request ID; save it. */ c->request_id = buf[0] * 256 + buf[1]; /* If this is a multi-packet request, drop it. */ if (buf[4] != 0 || buf[5] != 1) { out_string(c, "SERVER_ERROR multi-packet request not supported"); return READ_NO_DATA_RECEIVED; } /* Don't care about any of the rest of the header. */ res -= 8; memmove(c->rbuf, c->rbuf + 8, res); c->rbytes = res; c->rcurr = c->rbuf; return READ_DATA_RECEIVED; } return READ_NO_DATA_RECEIVED; } /* * read from network as much as we can, handle buffer overflow and connection * close. * before reading, move the remaining incomplete fragment of a command * (if any) to the beginning of the buffer. * * To protect us from someone flooding a connection with bogus data causing * the connection to eat up all available memory, break out and start looking * at the data I've got after a number of reallocs... * * @return enum try_read_result */ static enum try_read_result try_read_network(conn *c) { enum try_read_result gotdata = READ_NO_DATA_RECEIVED; int res; int num_allocs = 0; assert(c != NULL); if (c->rcurr != c->rbuf) { if (c->rbytes != 0) /* otherwise there's nothing to copy */ memmove(c->rbuf, c->rcurr, c->rbytes); c->rcurr = c->rbuf; } while (1) { if (c->rbytes >= c->rsize) { if (num_allocs == 4) { return gotdata; } ++num_allocs; char *new_rbuf = realloc(c->rbuf, c->rsize * 2); if (!new_rbuf) { STATS_LOCK(); stats.malloc_fails++; STATS_UNLOCK(); if (settings.verbose > 0) { fprintf(stderr, "Couldn't realloc input buffer\n"); } c->rbytes = 0; /* ignore what we read */ out_of_memory(c, "SERVER_ERROR out of memory reading request"); c->write_and_go = conn_closing; return READ_MEMORY_ERROR; } c->rcurr = c->rbuf = new_rbuf; c->rsize *= 2; } int avail = c->rsize - c->rbytes; res = read(c->sfd, c->rbuf + c->rbytes, avail); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); gotdata = READ_DATA_RECEIVED; c->rbytes += res; if (res == avail) { continue; } else { break; } } if (res == 0) { return READ_ERROR; } if (res == -1) { if (errno == EAGAIN || errno == EWOULDBLOCK) { break; } return READ_ERROR; } } return gotdata; } static bool update_event(conn *c, const int new_flags) { assert(c != NULL); struct event_base *base = c->event.ev_base; if (c->ev_flags == new_flags) return true; if (event_del(&c->event) == -1) return false; event_set(&c->event, c->sfd, new_flags, event_handler, (void *)c); event_base_set(base, &c->event); c->ev_flags = new_flags; if (event_add(&c->event, 0) == -1) return false; return true; } /* * Sets whether we are listening for new connections or not. */ void do_accept_new_conns(const bool do_accept) { conn *next; for (next = listen_conn; next; next = next->next) { if (do_accept) { update_event(next, EV_READ | EV_PERSIST); if (listen(next->sfd, settings.backlog) != 0) { perror("listen"); } } else { update_event(next, 0); if (listen(next->sfd, 0) != 0) { perror("listen"); } } } if (do_accept) { struct timeval maxconns_exited; uint64_t elapsed_us; gettimeofday(&maxconns_exited,NULL); STATS_LOCK(); elapsed_us = (maxconns_exited.tv_sec - stats.maxconns_entered.tv_sec) * 1000000 + (maxconns_exited.tv_usec - stats.maxconns_entered.tv_usec); stats.time_in_listen_disabled_us += elapsed_us; stats_state.accepting_conns = true; STATS_UNLOCK(); } else { STATS_LOCK(); stats_state.accepting_conns = false; gettimeofday(&stats.maxconns_entered,NULL); stats.listen_disabled_num++; STATS_UNLOCK(); allow_new_conns = false; maxconns_handler(-42, 0, 0); } } /* * Transmit the next chunk of data from our list of msgbuf structures. * * Returns: * TRANSMIT_COMPLETE All done writing. * TRANSMIT_INCOMPLETE More data remaining to write. * TRANSMIT_SOFT_ERROR Can't write any more right now. * TRANSMIT_HARD_ERROR Can't write (c->state is set to conn_closing) */ static enum transmit_result transmit(conn *c) { assert(c != NULL); if (c->msgcurr < c->msgused && c->msglist[c->msgcurr].msg_iovlen == 0) { /* Finished writing the current msg; advance to the next. */ c->msgcurr++; } if (c->msgcurr < c->msgused) { ssize_t res; struct msghdr *m = &c->msglist[c->msgcurr]; res = sendmsg(c->sfd, m, 0); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_written += res; pthread_mutex_unlock(&c->thread->stats.mutex); /* We've written some of the data. Remove the completed iovec entries from the list of pending writes. */ while (m->msg_iovlen > 0 && res >= m->msg_iov->iov_len) { res -= m->msg_iov->iov_len; m->msg_iovlen--; m->msg_iov++; } /* Might have written just part of the last iovec entry; adjust it so the next write will do the rest. */ if (res > 0) { m->msg_iov->iov_base = (caddr_t)m->msg_iov->iov_base + res; m->msg_iov->iov_len -= res; } return TRANSMIT_INCOMPLETE; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } return TRANSMIT_SOFT_ERROR; } /* if res == 0 or res == -1 and error is not EAGAIN or EWOULDBLOCK, we have a real error, on which we close the connection */ if (settings.verbose > 0) perror("Failed to write, and not due to blocking"); if (IS_UDP(c->transport)) conn_set_state(c, conn_read); else conn_set_state(c, conn_closing); return TRANSMIT_HARD_ERROR; } else { return TRANSMIT_COMPLETE; } } /* Does a looped read to fill data chunks */ /* TODO: restrict number of times this can loop. * Also, benchmark using readv's. */ static int read_into_chunked_item(conn *c) { int total = 0; int res; assert(c->rcurr != c->ritem); while (c->rlbytes > 0) { item_chunk *ch = (item_chunk *)c->ritem; assert(ch->used <= ch->size); if (ch->size == ch->used) { // FIXME: ch->next is currently always 0. remove this? if (ch->next) { c->ritem = (char *) ch->next; } else { /* Allocate next chunk. Binary protocol needs 2b for \r\n */ c->ritem = (char *) do_item_alloc_chunk(ch, c->rlbytes + ((c->protocol == binary_prot) ? 2 : 0)); if (!c->ritem) { // We failed an allocation. Let caller handle cleanup. total = -2; break; } // ritem has new chunk, restart the loop. continue; //assert(c->rlbytes == 0); } } int unused = ch->size - ch->used; /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { total = 0; int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; tocopy = tocopy > unused ? unused : tocopy; if (c->ritem != c->rcurr) { memmove(ch->data + ch->used, c->rcurr, tocopy); } total += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; ch->used += tocopy; if (c->rlbytes == 0) { break; } } else { /* now try reading from the socket */ res = read(c->sfd, ch->data + ch->used, (unused > c->rlbytes ? c->rlbytes : unused)); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); ch->used += res; total += res; c->rlbytes -= res; } else { /* Reset total to the latest result so caller can handle it */ total = res; break; } } } /* At some point I will be able to ditch the \r\n from item storage and remove all of these kludges. The above binprot check ensures inline space for \r\n, but if we do exactly enough allocs there will be no additional chunk for \r\n. */ if (c->rlbytes == 0 && c->protocol == binary_prot && total >= 0) { item_chunk *ch = (item_chunk *)c->ritem; if (ch->size - ch->used < 2) { c->ritem = (char *) do_item_alloc_chunk(ch, 2); if (!c->ritem) { total = -2; } } } return total; } static void drive_machine(conn *c) { bool stop = false; int sfd; socklen_t addrlen; struct sockaddr_storage addr; int nreqs = settings.reqs_per_event; int res; const char *str; #ifdef HAVE_ACCEPT4 static int use_accept4 = 1; #else static int use_accept4 = 0; #endif assert(c != NULL); while (!stop) { switch(c->state) { case conn_listening: addrlen = sizeof(addr); #ifdef HAVE_ACCEPT4 if (use_accept4) { sfd = accept4(c->sfd, (struct sockaddr *)&addr, &addrlen, SOCK_NONBLOCK); } else { sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); } #else sfd = accept(c->sfd, (struct sockaddr *)&addr, &addrlen); #endif if (sfd == -1) { if (use_accept4 && errno == ENOSYS) { use_accept4 = 0; continue; } perror(use_accept4 ? "accept4()" : "accept()"); if (errno == EAGAIN || errno == EWOULDBLOCK) { /* these are transient, so don't log anything */ stop = true; } else if (errno == EMFILE) { if (settings.verbose > 0) fprintf(stderr, "Too many open connections\n"); accept_new_conns(false); stop = true; } else { perror("accept()"); stop = true; } break; } if (!use_accept4) { if (fcntl(sfd, F_SETFL, fcntl(sfd, F_GETFL) | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); break; } } if (settings.maxconns_fast && stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { str = "ERROR Too many open connections\r\n"; res = write(sfd, str, strlen(str)); close(sfd); STATS_LOCK(); stats.rejected_conns++; STATS_UNLOCK(); } else { dispatch_conn_new(sfd, conn_new_cmd, EV_READ | EV_PERSIST, DATA_BUFFER_SIZE, c->transport); } stop = true; break; case conn_waiting: if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } conn_set_state(c, conn_read); stop = true; break; case conn_read: res = IS_UDP(c->transport) ? try_read_udp(c) : try_read_network(c); switch (res) { case READ_NO_DATA_RECEIVED: conn_set_state(c, conn_waiting); break; case READ_DATA_RECEIVED: conn_set_state(c, conn_parse_cmd); break; case READ_ERROR: conn_set_state(c, conn_closing); break; case READ_MEMORY_ERROR: /* Failed to allocate more memory */ /* State already set by try_read_network */ break; } break; case conn_parse_cmd : if (try_read_command(c) == 0) { /* wee need more data! */ conn_set_state(c, conn_waiting); } break; case conn_new_cmd: /* Only process nreqs at a time to avoid starving other connections */ --nreqs; if (nreqs >= 0) { reset_cmd_handler(c); } else { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.conn_yields++; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rbytes > 0) { /* We have already read in data into the input buffer, so libevent will most likely not signal read events on the socket (unless more data is available. As a hack we should just put in a request to write data, because that should be possible ;-) */ if (!update_event(c, EV_WRITE | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } } stop = true; } break; case conn_nread: if (c->rlbytes == 0) { complete_nread(c); break; } /* Check if rbytes < 0, to prevent crash */ if (c->rlbytes < 0) { if (settings.verbose) { fprintf(stderr, "Invalid rlbytes to read: len %d\n", c->rlbytes); } conn_set_state(c, conn_closing); break; } if (!c->item || (((item *)c->item)->it_flags & ITEM_CHUNKED) == 0) { /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->rlbytes ? c->rlbytes : c->rbytes; if (c->ritem != c->rcurr) { memmove(c->ritem, c->rcurr, tocopy); } c->ritem += tocopy; c->rlbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; if (c->rlbytes == 0) { break; } } /* now try reading from the socket */ res = read(c->sfd, c->ritem, c->rlbytes); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); if (c->rcurr == c->ritem) { c->rcurr += res; } c->ritem += res; c->rlbytes -= res; break; } } else { res = read_into_chunked_item(c); if (res > 0) break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* Memory allocation failure */ if (res == -2) { out_of_memory(c, "SERVER_ERROR Out of memory during read"); c->sbytes = c->rlbytes; c->write_and_go = conn_swallow; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) { fprintf(stderr, "Failed to read, and not due to blocking:\n" "errno: %d %s \n" "rcurr=%lx ritem=%lx rbuf=%lx rlbytes=%d rsize=%d\n", errno, strerror(errno), (long)c->rcurr, (long)c->ritem, (long)c->rbuf, (int)c->rlbytes, (int)c->rsize); } conn_set_state(c, conn_closing); break; case conn_swallow: /* we are reading sbytes and throwing them away */ if (c->sbytes == 0) { conn_set_state(c, conn_new_cmd); break; } /* first check if we have leftovers in the conn_read buffer */ if (c->rbytes > 0) { int tocopy = c->rbytes > c->sbytes ? c->sbytes : c->rbytes; c->sbytes -= tocopy; c->rcurr += tocopy; c->rbytes -= tocopy; break; } /* now try reading from the socket */ res = read(c->sfd, c->rbuf, c->rsize > c->sbytes ? c->sbytes : c->rsize); if (res > 0) { pthread_mutex_lock(&c->thread->stats.mutex); c->thread->stats.bytes_read += res; pthread_mutex_unlock(&c->thread->stats.mutex); c->sbytes -= res; break; } if (res == 0) { /* end of stream */ conn_set_state(c, conn_closing); break; } if (res == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { if (!update_event(c, EV_READ | EV_PERSIST)) { if (settings.verbose > 0) fprintf(stderr, "Couldn't update event\n"); conn_set_state(c, conn_closing); break; } stop = true; break; } /* otherwise we have a real error, on which we close the connection */ if (settings.verbose > 0) fprintf(stderr, "Failed to read, and not due to blocking\n"); conn_set_state(c, conn_closing); break; case conn_write: /* * We want to write out a simple response. If we haven't already, * assemble it into a msgbuf list (this will be a single-entry * list for TCP or a two-entry list for UDP). */ if (c->iovused == 0 || (IS_UDP(c->transport) && c->iovused == 1)) { if (add_iov(c, c->wcurr, c->wbytes) != 0) { if (settings.verbose > 0) fprintf(stderr, "Couldn't build response\n"); conn_set_state(c, conn_closing); break; } } /* fall through... */ case conn_mwrite: if (IS_UDP(c->transport) && c->msgcurr == 0 && build_udp_headers(c) != 0) { if (settings.verbose > 0) fprintf(stderr, "Failed to build UDP headers\n"); conn_set_state(c, conn_closing); break; } switch (transmit(c)) { case TRANSMIT_COMPLETE: if (c->state == conn_mwrite) { conn_release_items(c); /* XXX: I don't know why this wasn't the general case */ if(c->protocol == binary_prot) { conn_set_state(c, c->write_and_go); } else { conn_set_state(c, conn_new_cmd); } } else if (c->state == conn_write) { if (c->write_and_free) { free(c->write_and_free); c->write_and_free = 0; } conn_set_state(c, c->write_and_go); } else { if (settings.verbose > 0) fprintf(stderr, "Unexpected state %d\n", c->state); conn_set_state(c, conn_closing); } break; case TRANSMIT_INCOMPLETE: case TRANSMIT_HARD_ERROR: break; /* Continue in state machine. */ case TRANSMIT_SOFT_ERROR: stop = true; break; } break; case conn_closing: if (IS_UDP(c->transport)) conn_cleanup(c); else conn_close(c); stop = true; break; case conn_closed: /* This only happens if dormando is an idiot. */ abort(); break; case conn_watch: /* We handed off our connection to the logger thread. */ stop = true; break; case conn_max_state: assert(false); break; } } return; } void event_handler(const int fd, const short which, void *arg) { conn *c; c = (conn *)arg; assert(c != NULL); c->which = which; /* sanity */ if (fd != c->sfd) { if (settings.verbose > 0) fprintf(stderr, "Catastrophic: event fd doesn't match conn fd!\n"); conn_close(c); return; } drive_machine(c); /* wait for next event */ return; } static int new_socket(struct addrinfo *ai) { int sfd; int flags; if ((sfd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol)) == -1) { return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } /* * Sets a socket's send buffer size to the maximum allowed by the system. */ static void maximize_sndbuf(const int sfd) { socklen_t intsize = sizeof(int); int last_good = 0; int min, max, avg; int old_size; /* Start with the default size. */ if (getsockopt(sfd, SOL_SOCKET, SO_SNDBUF, &old_size, &intsize) != 0) { if (settings.verbose > 0) perror("getsockopt(SO_SNDBUF)"); return; } /* Binary-search for the real maximum. */ min = old_size; max = MAX_SENDBUF_SIZE; while (min <= max) { avg = ((unsigned int)(min + max)) / 2; if (setsockopt(sfd, SOL_SOCKET, SO_SNDBUF, (void *)&avg, intsize) == 0) { last_good = avg; min = avg + 1; } else { max = avg - 1; } } if (settings.verbose > 1) fprintf(stderr, "<%d send buffer was %d, now %d\n", sfd, old_size, last_good); } /** * Create a socket and bind it to a specific port number * @param interface the interface to bind to * @param port the port number to bind to * @param transport the transport protocol (TCP / UDP) * @param portnumber_file A filepointer to write the port numbers to * when they are successfully added to the list of ports we * listen on. */ static int server_socket(const char *interface, int port, enum network_transport transport, FILE *portnumber_file) { int sfd; struct linger ling = {0, 0}; struct addrinfo *ai; struct addrinfo *next; struct addrinfo hints = { .ai_flags = AI_PASSIVE, .ai_family = AF_UNSPEC }; char port_buf[NI_MAXSERV]; int error; int success = 0; int flags =1; hints.ai_socktype = IS_UDP(transport) ? SOCK_DGRAM : SOCK_STREAM; if (port == -1) { port = 0; } snprintf(port_buf, sizeof(port_buf), "%d", port); error= getaddrinfo(interface, port_buf, &hints, &ai); if (error != 0) { if (error != EAI_SYSTEM) fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(error)); else perror("getaddrinfo()"); return 1; } for (next= ai; next; next= next->ai_next) { conn *listen_conn_add; if ((sfd = new_socket(next)) == -1) { /* getaddrinfo can return "junk" addresses, * we make sure at least one works before erroring. */ if (errno == EMFILE) { /* ...unless we're out of fds */ perror("server_socket"); exit(EX_OSERR); } continue; } #ifdef IPV6_V6ONLY if (next->ai_family == AF_INET6) { error = setsockopt(sfd, IPPROTO_IPV6, IPV6_V6ONLY, (char *) &flags, sizeof(flags)); if (error != 0) { perror("setsockopt"); close(sfd); continue; } } #endif setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); if (IS_UDP(transport)) { maximize_sndbuf(sfd); } else { error = setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); if (error != 0) perror("setsockopt"); error = setsockopt(sfd, IPPROTO_TCP, TCP_NODELAY, (void *)&flags, sizeof(flags)); if (error != 0) perror("setsockopt"); } if (bind(sfd, next->ai_addr, next->ai_addrlen) == -1) { if (errno != EADDRINUSE) { perror("bind()"); close(sfd); freeaddrinfo(ai); return 1; } close(sfd); continue; } else { success++; if (!IS_UDP(transport) && listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); freeaddrinfo(ai); return 1; } if (portnumber_file != NULL && (next->ai_addr->sa_family == AF_INET || next->ai_addr->sa_family == AF_INET6)) { union { struct sockaddr_in in; struct sockaddr_in6 in6; } my_sockaddr; socklen_t len = sizeof(my_sockaddr); if (getsockname(sfd, (struct sockaddr*)&my_sockaddr, &len)==0) { if (next->ai_addr->sa_family == AF_INET) { fprintf(portnumber_file, "%s INET: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in.sin_port)); } else { fprintf(portnumber_file, "%s INET6: %u\n", IS_UDP(transport) ? "UDP" : "TCP", ntohs(my_sockaddr.in6.sin6_port)); } } } } if (IS_UDP(transport)) { int c; for (c = 0; c < settings.num_threads_per_udp; c++) { /* Allocate one UDP file descriptor per worker thread; * this allows "stats conns" to separately list multiple * parallel UDP requests in progress. * * The dispatch code round-robins new connection requests * among threads, so this is guaranteed to assign one * FD to each thread. */ int per_thread_fd = c ? dup(sfd) : sfd; dispatch_conn_new(per_thread_fd, conn_read, EV_READ | EV_PERSIST, UDP_READ_BUFFER_SIZE, transport); } } else { if (!(listen_conn_add = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, transport, main_base))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } listen_conn_add->next = listen_conn; listen_conn = listen_conn_add; } } freeaddrinfo(ai); /* Return zero iff we detected no errors in starting up connections */ return success == 0; } static int server_sockets(int port, enum network_transport transport, FILE *portnumber_file) { if (settings.inter == NULL) { return server_socket(settings.inter, port, transport, portnumber_file); } else { // tokenize them and bind to each one of them.. char *b; int ret = 0; char *list = strdup(settings.inter); if (list == NULL) { fprintf(stderr, "Failed to allocate memory for parsing server interface string\n"); return 1; } for (char *p = strtok_r(list, ";,", &b); p != NULL; p = strtok_r(NULL, ";,", &b)) { int the_port = port; char *h = NULL; if (*p == '[') { // expecting it to be an IPv6 address enclosed in [] // i.e. RFC3986 style recommended by RFC5952 char *e = strchr(p, ']'); if (e == NULL) { fprintf(stderr, "Invalid IPV6 address: \"%s\"", p); return 1; } h = ++p; // skip the opening '[' *e = '\0'; p = ++e; // skip the closing ']' } char *s = strchr(p, ':'); if (s != NULL) { // If no more semicolons - attempt to treat as port number. // Otherwise the only valid option is an unenclosed IPv6 without port, until // of course there was an RFC3986 IPv6 address previously specified - // in such a case there is no good option, will just send it to fail as port number. if (strchr(s + 1, ':') == NULL || h != NULL) { *s = '\0'; ++s; if (!safe_strtol(s, &the_port)) { fprintf(stderr, "Invalid port number: \"%s\"", s); return 1; } } } if (h != NULL) p = h; if (strcmp(p, "*") == 0) { p = NULL; } ret |= server_socket(p, the_port, transport, portnumber_file); } free(list); return ret; } } static int new_socket_unix(void) { int sfd; int flags; if ((sfd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket()"); return -1; } if ((flags = fcntl(sfd, F_GETFL, 0)) < 0 || fcntl(sfd, F_SETFL, flags | O_NONBLOCK) < 0) { perror("setting O_NONBLOCK"); close(sfd); return -1; } return sfd; } static int server_socket_unix(const char *path, int access_mask) { int sfd; struct linger ling = {0, 0}; struct sockaddr_un addr; struct stat tstat; int flags =1; int old_umask; if (!path) { return 1; } if ((sfd = new_socket_unix()) == -1) { return 1; } /* * Clean up a previous socket file if we left it around */ if (lstat(path, &tstat) == 0) { if (S_ISSOCK(tstat.st_mode)) unlink(path); } setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&flags, sizeof(flags)); setsockopt(sfd, SOL_SOCKET, SO_LINGER, (void *)&ling, sizeof(ling)); /* * the memset call clears nonstandard fields in some impementations * that otherwise mess things up. */ memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1); assert(strcmp(addr.sun_path, path) == 0); old_umask = umask( ~(access_mask&0777)); if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("bind()"); close(sfd); umask(old_umask); return 1; } umask(old_umask); if (listen(sfd, settings.backlog) == -1) { perror("listen()"); close(sfd); return 1; } if (!(listen_conn = conn_new(sfd, conn_listening, EV_READ | EV_PERSIST, 1, local_transport, main_base))) { fprintf(stderr, "failed to create listening connection\n"); exit(EXIT_FAILURE); } return 0; } /* * We keep the current time of day in a global variable that's updated by a * timer event. This saves us a bunch of time() system calls (we really only * need to get the time once a second, whereas there can be tens of thousands * of requests a second) and allows us to use server-start-relative timestamps * rather than absolute UNIX timestamps, a space savings on systems where * sizeof(time_t) > sizeof(unsigned int). */ volatile rel_time_t current_time; static struct event clockevent; /* libevent uses a monotonic clock when available for event scheduling. Aside * from jitter, simply ticking our internal timer here is accurate enough. * Note that users who are setting explicit dates for expiration times *must* * ensure their clocks are correct before starting memcached. */ static void clock_handler(const int fd, const short which, void *arg) { struct timeval t = {.tv_sec = 1, .tv_usec = 0}; static bool initialized = false; #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) static bool monotonic = false; static time_t monotonic_start; #endif if (initialized) { /* only delete the event if it's actually there. */ evtimer_del(&clockevent); } else { initialized = true; /* process_started is initialized to time() - 2. We initialize to 1 so * flush_all won't underflow during tests. */ #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) { monotonic = true; monotonic_start = ts.tv_sec - ITEM_UPDATE_INTERVAL - 2; } #endif } evtimer_set(&clockevent, clock_handler, 0); event_base_set(main_base, &clockevent); evtimer_add(&clockevent, &t); #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC) if (monotonic) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts) == -1) return; current_time = (rel_time_t) (ts.tv_sec - monotonic_start); return; } #endif { struct timeval tv; gettimeofday(&tv, NULL); current_time = (rel_time_t) (tv.tv_sec - process_started); } } static void usage(void) { printf(PACKAGE " " VERSION "\n"); printf("-p <num> TCP port number to listen on (default: 11211)\n" "-U <num> UDP port number to listen on (default: 11211, 0 is off)\n" "-s <file> UNIX socket path to listen on (disables network support)\n" "-A enable ascii \"shutdown\" command\n" "-a <mask> access mask for UNIX socket, in octal (default: 0700)\n" "-l <addr> interface to listen on (default: INADDR_ANY, all addresses)\n" " <addr> may be specified as host:port. If you don't specify\n" " a port number, the value you specified with -p or -U is\n" " used. You may specify multiple addresses separated by comma\n" " or by using -l multiple times\n" "-d run as a daemon\n" "-r maximize core file limit\n" "-u <username> assume identity of <username> (only when run as root)\n" "-m <num> max memory to use for items in megabytes (default: 64 MB)\n" "-M return error on memory exhausted (rather than removing items)\n" "-c <num> max simultaneous connections (default: 1024)\n" "-k lock down all paged memory. Note that there is a\n" " limit on how much memory you may lock. Trying to\n" " allocate more than that would fail, so be sure you\n" " set the limit correctly for the user you started\n" " the daemon with (not for -u <username> user;\n" " under sh this is done with 'ulimit -S -l NUM_KB').\n" "-v verbose (print errors/warnings while in event loop)\n" "-vv very verbose (also print client commands/reponses)\n" "-vvv extremely verbose (also print internal state transitions)\n" "-h print this help and exit\n" "-i print memcached and libevent license\n" "-V print version and exit\n" "-P <file> save PID in <file>, only used with -d option\n" "-f <factor> chunk size growth factor (default: 1.25)\n" "-n <bytes> minimum space allocated for key+value+flags (default: 48)\n"); printf("-L Try to use large memory pages (if available). Increasing\n" " the memory page size could reduce the number of TLB misses\n" " and improve the performance. In order to get large pages\n" " from the OS, memcached will allocate the total item-cache\n" " in one large chunk.\n"); printf("-D <char> Use <char> as the delimiter between key prefixes and IDs.\n" " This is used for per-prefix stats reporting. The default is\n" " \":\" (colon). If this option is specified, stats collection\n" " is turned on automatically; if not, then it may be turned on\n" " by sending the \"stats detail on\" command to the server.\n"); printf("-t <num> number of threads to use (default: 4)\n"); printf("-R Maximum number of requests per event, limits the number of\n" " requests process for a given connection to prevent \n" " starvation (default: 20)\n"); printf("-C Disable use of CAS\n"); printf("-b <num> Set the backlog queue limit (default: 1024)\n"); printf("-B Binding protocol - one of ascii, binary, or auto (default)\n"); printf("-I Override the size of each slab page. Adjusts max item size\n" " (default: 1mb, min: 1k, max: 128m)\n"); #ifdef ENABLE_SASL printf("-S Turn on Sasl authentication\n"); #endif printf("-F Disable flush_all command\n"); printf("-X Disable stats cachedump and lru_crawler metadump commands\n"); printf("-o Comma separated list of extended or experimental options\n" " - maxconns_fast: immediately close new\n" " connections if over maxconns limit\n" " - hashpower: An integer multiplier for how large the hash\n" " table should be. Can be grown at runtime if not big enough.\n" " Set this based on \"STAT hash_power_level\" before a \n" " restart.\n" " - tail_repair_time: Time in seconds that indicates how long to wait before\n" " forcefully taking over the LRU tail item whose refcount has leaked.\n" " Disabled by default; dangerous option.\n" " - hash_algorithm: The hash table algorithm\n" " default is jenkins hash. options: jenkins, murmur3\n" " - lru_crawler: Enable LRU Crawler background thread\n" " - lru_crawler_sleep: Microseconds to sleep between items\n" " default is 100.\n" " - lru_crawler_tocrawl: Max items to crawl per slab per run\n" " default is 0 (unlimited)\n" " - lru_maintainer: Enable new LRU system + background thread\n" " - hot_lru_pct: Pct of slab memory to reserve for hot lru.\n" " (requires lru_maintainer)\n" " - warm_lru_pct: Pct of slab memory to reserve for warm lru.\n" " (requires lru_maintainer)\n" " - hot_max_age: Items idle longer than this drop from hot lru.\n" " - cold_max_factor: Items idle longer than cold lru age * this drop from warm.\n" " - temporary_ttl: TTL's below this use separate LRU, cannot be evicted.\n" " (requires lru_maintainer)\n" " - idle_timeout: Timeout for idle connections\n" " - (EXPERIMENTAL) slab_chunk_max: Maximum slab size. Do not change without extreme care.\n" " - watcher_logbuf_size: Size in kilobytes of per-watcher write buffer.\n" " - worker_logbuf_Size: Size in kilobytes of per-worker-thread buffer\n" " read by background thread. Which is then written to watchers.\n" " - track_sizes: Enable dynamic reports for 'stats sizes' command.\n" " - no_inline_ascii_resp: Save up to 24 bytes per item. Small perf hit in ASCII,\n" " no perf difference in binary protocol. Speeds up sets.\n" " - modern: Enables 'modern' defaults. Options that will be default in future.\n" " enables: slab_chunk_max:512k,slab_reassign,slab_automove=1,maxconns_fast,\n" " hash_algorithm=murmur3,lru_crawler,lru_maintainer,no_inline_ascii_resp\n" ); return; } static void usage_license(void) { printf(PACKAGE " " VERSION "\n\n"); printf( "Copyright (c) 2003, Danga Interactive, Inc. <http://www.danga.com/>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions are\n" "met:\n" "\n" " * Redistributions of source code must retain the above copyright\n" "notice, this list of conditions and the following disclaimer.\n" "\n" " * Redistributions in binary form must reproduce the above\n" "copyright notice, this list of conditions and the following disclaimer\n" "in the documentation and/or other materials provided with the\n" "distribution.\n" "\n" " * Neither the name of the Danga Interactive nor the names of its\n" "contributors may be used to endorse or promote products derived from\n" "this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n" "\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n" "LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n" "A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n" "OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n" "SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n" "LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n" "OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" "\n" "\n" "This product includes software developed by Niels Provos.\n" "\n" "[ libevent ]\n" "\n" "Copyright 2000-2003 Niels Provos <provos@citi.umich.edu>\n" "All rights reserved.\n" "\n" "Redistribution and use in source and binary forms, with or without\n" "modification, are permitted provided that the following conditions\n" "are met:\n" "1. Redistributions of source code must retain the above copyright\n" " notice, this list of conditions and the following disclaimer.\n" "2. Redistributions in binary form must reproduce the above copyright\n" " notice, this list of conditions and the following disclaimer in the\n" " documentation and/or other materials provided with the distribution.\n" "3. All advertising materials mentioning features or use of this software\n" " must display the following acknowledgement:\n" " This product includes software developed by Niels Provos.\n" "4. The name of the author may not be used to endorse or promote products\n" " derived from this software without specific prior written permission.\n" "\n" "THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n" "IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n" "OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n" "IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n" "INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n" "NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n" "DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n" "THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n" "(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n" "THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n" ); return; } static void save_pid(const char *pid_file) { FILE *fp; if (access(pid_file, F_OK) == 0) { if ((fp = fopen(pid_file, "r")) != NULL) { char buffer[1024]; if (fgets(buffer, sizeof(buffer), fp) != NULL) { unsigned int pid; if (safe_strtoul(buffer, &pid) && kill((pid_t)pid, 0) == 0) { fprintf(stderr, "WARNING: The pid file contained the following (running) pid: %u\n", pid); } } fclose(fp); } } /* Create the pid file first with a temporary name, then * atomically move the file to the real name to avoid a race with * another process opening the file to read the pid, but finding * it empty. */ char tmp_pid_file[1024]; snprintf(tmp_pid_file, sizeof(tmp_pid_file), "%s.tmp", pid_file); if ((fp = fopen(tmp_pid_file, "w")) == NULL) { vperror("Could not open the pid file %s for writing", tmp_pid_file); return; } fprintf(fp,"%ld\n", (long)getpid()); if (fclose(fp) == -1) { vperror("Could not close the pid file %s", tmp_pid_file); } if (rename(tmp_pid_file, pid_file) != 0) { vperror("Could not rename the pid file from %s to %s", tmp_pid_file, pid_file); } } static void remove_pidfile(const char *pid_file) { if (pid_file == NULL) return; if (unlink(pid_file) != 0) { vperror("Could not remove the pid file %s", pid_file); } } static void sig_handler(const int sig) { printf("Signal handled: %s.\n", strsignal(sig)); exit(EXIT_SUCCESS); } #ifndef HAVE_SIGIGNORE static int sigignore(int sig) { struct sigaction sa = { .sa_handler = SIG_IGN, .sa_flags = 0 }; if (sigemptyset(&sa.sa_mask) == -1 || sigaction(sig, &sa, 0) == -1) { return -1; } return 0; } #endif /* * On systems that supports multiple page sizes we may reduce the * number of TLB-misses by using the biggest available page size */ static int enable_large_pages(void) { #if defined(HAVE_GETPAGESIZES) && defined(HAVE_MEMCNTL) int ret = -1; size_t sizes[32]; int avail = getpagesizes(sizes, 32); if (avail != -1) { size_t max = sizes[0]; struct memcntl_mha arg = {0}; int ii; for (ii = 1; ii < avail; ++ii) { if (max < sizes[ii]) { max = sizes[ii]; } } arg.mha_flags = 0; arg.mha_pagesize = max; arg.mha_cmd = MHA_MAPSIZE_BSSBRK; if (memcntl(0, 0, MC_HAT_ADVISE, (caddr_t)&arg, 0, 0) == -1) { fprintf(stderr, "Failed to set large pages: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } else { ret = 0; } } else { fprintf(stderr, "Failed to get supported pagesizes: %s\n", strerror(errno)); fprintf(stderr, "Will use default page size\n"); } return ret; #else return -1; #endif } /** * Do basic sanity check of the runtime environment * @return true if no errors found, false if we can't use this env */ static bool sanitycheck(void) { /* One of our biggest problems is old and bogus libevents */ const char *ever = event_get_version(); if (ever != NULL) { if (strncmp(ever, "1.", 2) == 0) { /* Require at least 1.3 (that's still a couple of years old) */ if (('0' <= ever[2] && ever[2] < '3') && !isdigit(ever[3])) { fprintf(stderr, "You are using libevent %s.\nPlease upgrade to" " a more recent version (1.3 or newer)\n", event_get_version()); return false; } } } return true; } static bool _parse_slab_sizes(char *s, uint32_t *slab_sizes) { char *b = NULL; uint32_t size = 0; int i = 0; uint32_t last_size = 0; if (strlen(s) < 1) return false; for (char *p = strtok_r(s, "-", &b); p != NULL; p = strtok_r(NULL, "-", &b)) { if (!safe_strtoul(p, &size) || size < settings.chunk_size || size > settings.slab_chunk_size_max) { fprintf(stderr, "slab size %u is out of valid range\n", size); return false; } if (last_size >= size) { fprintf(stderr, "slab size %u cannot be lower than or equal to a previous class size\n", size); return false; } if (size <= last_size + CHUNK_ALIGN_BYTES) { fprintf(stderr, "slab size %u must be at least %d bytes larger than previous class\n", size, CHUNK_ALIGN_BYTES); return false; } slab_sizes[i++] = size; last_size = size; if (i >= MAX_NUMBER_OF_SLAB_CLASSES-1) { fprintf(stderr, "too many slab classes specified\n"); return false; } } slab_sizes[i] = 0; return true; } int main (int argc, char **argv) { int c; bool lock_memory = false; bool do_daemonize = false; bool preallocate = false; int maxcore = 0; char *username = NULL; char *pid_file = NULL; struct passwd *pw; struct rlimit rlim; char *buf; char unit = '\0'; int size_max = 0; int retval = EXIT_SUCCESS; /* listening sockets */ static int *l_socket = NULL; /* udp socket */ static int *u_socket = NULL; bool protocol_specified = false; bool tcp_specified = false; bool udp_specified = false; bool start_lru_maintainer = false; bool start_lru_crawler = false; enum hashfunc_type hash_type = JENKINS_HASH; uint32_t tocrawl; uint32_t slab_sizes[MAX_NUMBER_OF_SLAB_CLASSES]; bool use_slab_sizes = false; char *slab_sizes_unparsed = NULL; bool slab_chunk_size_changed = false; char *subopts, *subopts_orig; char *subopts_value; enum { MAXCONNS_FAST = 0, HASHPOWER_INIT, SLAB_REASSIGN, SLAB_AUTOMOVE, TAIL_REPAIR_TIME, HASH_ALGORITHM, LRU_CRAWLER, LRU_CRAWLER_SLEEP, LRU_CRAWLER_TOCRAWL, LRU_MAINTAINER, HOT_LRU_PCT, WARM_LRU_PCT, HOT_MAX_AGE, WARM_MAX_FACTOR, TEMPORARY_TTL, IDLE_TIMEOUT, WATCHER_LOGBUF_SIZE, WORKER_LOGBUF_SIZE, SLAB_SIZES, SLAB_CHUNK_MAX, TRACK_SIZES, NO_INLINE_ASCII_RESP, MODERN }; char *const subopts_tokens[] = { [MAXCONNS_FAST] = "maxconns_fast", [HASHPOWER_INIT] = "hashpower", [SLAB_REASSIGN] = "slab_reassign", [SLAB_AUTOMOVE] = "slab_automove", [TAIL_REPAIR_TIME] = "tail_repair_time", [HASH_ALGORITHM] = "hash_algorithm", [LRU_CRAWLER] = "lru_crawler", [LRU_CRAWLER_SLEEP] = "lru_crawler_sleep", [LRU_CRAWLER_TOCRAWL] = "lru_crawler_tocrawl", [LRU_MAINTAINER] = "lru_maintainer", [HOT_LRU_PCT] = "hot_lru_pct", [WARM_LRU_PCT] = "warm_lru_pct", [HOT_MAX_AGE] = "hot_max_age", [WARM_MAX_FACTOR] = "warm_max_factor", [TEMPORARY_TTL] = "temporary_ttl", [IDLE_TIMEOUT] = "idle_timeout", [WATCHER_LOGBUF_SIZE] = "watcher_logbuf_size", [WORKER_LOGBUF_SIZE] = "worker_logbuf_size", [SLAB_SIZES] = "slab_sizes", [SLAB_CHUNK_MAX] = "slab_chunk_max", [TRACK_SIZES] = "track_sizes", [NO_INLINE_ASCII_RESP] = "no_inline_ascii_resp", [MODERN] = "modern", NULL }; if (!sanitycheck()) { return EX_OSERR; } /* handle SIGINT and SIGTERM */ signal(SIGINT, sig_handler); signal(SIGTERM, sig_handler); /* init settings */ settings_init(); /* Run regardless of initializing it later */ init_lru_crawler(); init_lru_maintainer(); /* set stderr non-buffering (for running under, say, daemontools) */ setbuf(stderr, NULL); /* process arguments */ while (-1 != (c = getopt(argc, argv, "a:" /* access mask for unix socket */ "A" /* enable admin shutdown commannd */ "p:" /* TCP port number to listen on */ "s:" /* unix socket path to listen on */ "U:" /* UDP port number to listen on */ "m:" /* max memory to use for items in megabytes */ "M" /* return error on memory exhausted */ "c:" /* max simultaneous connections */ "k" /* lock down all paged memory */ "hiV" /* help, licence info, version */ "r" /* maximize core file limit */ "v" /* verbose */ "d" /* daemon mode */ "l:" /* interface to listen on */ "u:" /* user identity to run as */ "P:" /* save PID in file */ "f:" /* factor? */ "n:" /* minimum space allocated for key+value+flags */ "t:" /* threads */ "D:" /* prefix delimiter? */ "L" /* Large memory pages */ "R:" /* max requests per event */ "C" /* Disable use of CAS */ "b:" /* backlog queue limit */ "B:" /* Binding protocol */ "I:" /* Max item size */ "S" /* Sasl ON */ "F" /* Disable flush_all */ "X" /* Disable dump commands */ "o:" /* Extended generic options */ ))) { switch (c) { case 'A': /* enables "shutdown" command */ settings.shutdown_command = true; break; case 'a': /* access for unix domain socket, as octal mask (like chmod)*/ settings.access= strtol(optarg,NULL,8); break; case 'U': settings.udpport = atoi(optarg); udp_specified = true; break; case 'p': settings.port = atoi(optarg); tcp_specified = true; break; case 's': settings.socketpath = optarg; break; case 'm': settings.maxbytes = ((size_t)atoi(optarg)) * 1024 * 1024; break; case 'M': settings.evict_to_free = 0; break; case 'c': settings.maxconns = atoi(optarg); if (settings.maxconns <= 0) { fprintf(stderr, "Maximum connections must be greater than 0\n"); return 1; } break; case 'h': usage(); exit(EXIT_SUCCESS); case 'i': usage_license(); exit(EXIT_SUCCESS); case 'V': printf(PACKAGE " " VERSION "\n"); exit(EXIT_SUCCESS); case 'k': lock_memory = true; break; case 'v': settings.verbose++; break; case 'l': if (settings.inter != NULL) { if (strstr(settings.inter, optarg) != NULL) { break; } size_t len = strlen(settings.inter) + strlen(optarg) + 2; char *p = malloc(len); if (p == NULL) { fprintf(stderr, "Failed to allocate memory\n"); return 1; } snprintf(p, len, "%s,%s", settings.inter, optarg); free(settings.inter); settings.inter = p; } else { settings.inter= strdup(optarg); } break; case 'd': do_daemonize = true; break; case 'r': maxcore = 1; break; case 'R': settings.reqs_per_event = atoi(optarg); if (settings.reqs_per_event == 0) { fprintf(stderr, "Number of requests per event must be greater than 0\n"); return 1; } break; case 'u': username = optarg; break; case 'P': pid_file = optarg; break; case 'f': settings.factor = atof(optarg); if (settings.factor <= 1.0) { fprintf(stderr, "Factor must be greater than 1\n"); return 1; } break; case 'n': settings.chunk_size = atoi(optarg); if (settings.chunk_size == 0) { fprintf(stderr, "Chunk size must be greater than 0\n"); return 1; } break; case 't': settings.num_threads = atoi(optarg); if (settings.num_threads <= 0) { fprintf(stderr, "Number of threads must be greater than 0\n"); return 1; } /* There're other problems when you get above 64 threads. * In the future we should portably detect # of cores for the * default. */ if (settings.num_threads > 64) { fprintf(stderr, "WARNING: Setting a high number of worker" "threads is not recommended.\n" " Set this value to the number of cores in" " your machine or less.\n"); } break; case 'D': if (! optarg || ! optarg[0]) { fprintf(stderr, "No delimiter specified\n"); return 1; } settings.prefix_delimiter = optarg[0]; settings.detail_enabled = 1; break; case 'L' : if (enable_large_pages() == 0) { preallocate = true; } else { fprintf(stderr, "Cannot enable large pages on this system\n" "(There is no Linux support as of this version)\n"); return 1; } break; case 'C' : settings.use_cas = false; break; case 'b' : settings.backlog = atoi(optarg); break; case 'B': protocol_specified = true; if (strcmp(optarg, "auto") == 0) { settings.binding_protocol = negotiating_prot; } else if (strcmp(optarg, "binary") == 0) { settings.binding_protocol = binary_prot; } else if (strcmp(optarg, "ascii") == 0) { settings.binding_protocol = ascii_prot; } else { fprintf(stderr, "Invalid value for binding protocol: %s\n" " -- should be one of auto, binary, or ascii\n", optarg); exit(EX_USAGE); } break; case 'I': buf = strdup(optarg); unit = buf[strlen(buf)-1]; if (unit == 'k' || unit == 'm' || unit == 'K' || unit == 'M') { buf[strlen(buf)-1] = '\0'; size_max = atoi(buf); if (unit == 'k' || unit == 'K') size_max *= 1024; if (unit == 'm' || unit == 'M') size_max *= 1024 * 1024; settings.item_size_max = size_max; } else { settings.item_size_max = atoi(buf); } free(buf); if (settings.item_size_max < 1024) { fprintf(stderr, "Item max size cannot be less than 1024 bytes.\n"); return 1; } if (settings.item_size_max > (settings.maxbytes / 4)) { fprintf(stderr, "Cannot set item size limit higher than 1/4 of memory max.\n"); return 1; } if (settings.item_size_max > (1024 * 1024 * 1024)) { fprintf(stderr, "Cannot set item size limit higher than a gigabyte.\n"); return 1; } if (settings.item_size_max > 1024 * 1024) { if (!slab_chunk_size_changed) { // Ideal new default is 16k, but needs stitching. settings.slab_chunk_size_max = 524288; } } break; case 'S': /* set Sasl authentication to true. Default is false */ #ifndef ENABLE_SASL fprintf(stderr, "This server is not built with SASL support.\n"); exit(EX_USAGE); #endif settings.sasl = true; break; case 'F' : settings.flush_enabled = false; break; case 'X' : settings.dump_enabled = false; break; case 'o': /* It's sub-opts time! */ subopts_orig = subopts = strdup(optarg); /* getsubopt() changes the original args */ while (*subopts != '\0') { switch (getsubopt(&subopts, subopts_tokens, &subopts_value)) { case MAXCONNS_FAST: settings.maxconns_fast = true; break; case HASHPOWER_INIT: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for hashpower\n"); return 1; } settings.hashpower_init = atoi(subopts_value); if (settings.hashpower_init < 12) { fprintf(stderr, "Initial hashtable multiplier of %d is too low\n", settings.hashpower_init); return 1; } else if (settings.hashpower_init > 64) { fprintf(stderr, "Initial hashtable multiplier of %d is too high\n" "Choose a value based on \"STAT hash_power_level\" from a running instance\n", settings.hashpower_init); return 1; } break; case SLAB_REASSIGN: settings.slab_reassign = true; break; case SLAB_AUTOMOVE: if (subopts_value == NULL) { settings.slab_automove = 1; break; } settings.slab_automove = atoi(subopts_value); if (settings.slab_automove < 0 || settings.slab_automove > 2) { fprintf(stderr, "slab_automove must be between 0 and 2\n"); return 1; } break; case TAIL_REPAIR_TIME: if (subopts_value == NULL) { fprintf(stderr, "Missing numeric argument for tail_repair_time\n"); return 1; } settings.tail_repair_time = atoi(subopts_value); if (settings.tail_repair_time < 10) { fprintf(stderr, "Cannot set tail_repair_time to less than 10 seconds\n"); return 1; } break; case HASH_ALGORITHM: if (subopts_value == NULL) { fprintf(stderr, "Missing hash_algorithm argument\n"); return 1; }; if (strcmp(subopts_value, "jenkins") == 0) { hash_type = JENKINS_HASH; } else if (strcmp(subopts_value, "murmur3") == 0) { hash_type = MURMUR3_HASH; } else { fprintf(stderr, "Unknown hash_algorithm option (jenkins, murmur3)\n"); return 1; } break; case LRU_CRAWLER: start_lru_crawler = true; break; case LRU_CRAWLER_SLEEP: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_sleep value\n"); return 1; } settings.lru_crawler_sleep = atoi(subopts_value); if (settings.lru_crawler_sleep > 1000000 || settings.lru_crawler_sleep < 0) { fprintf(stderr, "LRU crawler sleep must be between 0 and 1 second\n"); return 1; } break; case LRU_CRAWLER_TOCRAWL: if (subopts_value == NULL) { fprintf(stderr, "Missing lru_crawler_tocrawl value\n"); return 1; } if (!safe_strtoul(subopts_value, &tocrawl)) { fprintf(stderr, "lru_crawler_tocrawl takes a numeric 32bit value\n"); return 1; } settings.lru_crawler_tocrawl = tocrawl; break; case LRU_MAINTAINER: start_lru_maintainer = true; settings.lru_segmented = true; break; case HOT_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_lru_pct argument\n"); return 1; } settings.hot_lru_pct = atoi(subopts_value); if (settings.hot_lru_pct < 1 || settings.hot_lru_pct >= 80) { fprintf(stderr, "hot_lru_pct must be > 1 and < 80\n"); return 1; } break; case WARM_LRU_PCT: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_lru_pct argument\n"); return 1; } settings.warm_lru_pct = atoi(subopts_value); if (settings.warm_lru_pct < 1 || settings.warm_lru_pct >= 80) { fprintf(stderr, "warm_lru_pct must be > 1 and < 80\n"); return 1; } break; case HOT_MAX_AGE: if (subopts_value == NULL) { fprintf(stderr, "Missing hot_max_age argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.hot_max_age)) { fprintf(stderr, "invalid argument to hot_max_age\n"); return 1; } break; case WARM_MAX_FACTOR: if (subopts_value == NULL) { fprintf(stderr, "Missing warm_max_factor argument\n"); return 1; } settings.warm_max_factor = atof(subopts_value); if (settings.warm_max_factor <= 0) { fprintf(stderr, "warm_max_factor must be > 0\n"); return 1; } break; case TEMPORARY_TTL: if (subopts_value == NULL) { fprintf(stderr, "Missing temporary_ttl argument\n"); return 1; } settings.temp_lru = true; settings.temporary_ttl = atoi(subopts_value); break; case IDLE_TIMEOUT: settings.idle_timeout = atoi(subopts_value); break; case WATCHER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing watcher_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_watcher_buf_size)) { fprintf(stderr, "could not parse argument to watcher_logbuf_size\n"); return 1; } settings.logger_watcher_buf_size *= 1024; /* kilobytes */ break; case WORKER_LOGBUF_SIZE: if (subopts_value == NULL) { fprintf(stderr, "Missing worker_logbuf_size argument\n"); return 1; } if (!safe_strtoul(subopts_value, &settings.logger_buf_size)) { fprintf(stderr, "could not parse argument to worker_logbuf_size\n"); return 1; } settings.logger_buf_size *= 1024; /* kilobytes */ case SLAB_SIZES: slab_sizes_unparsed = subopts_value; break; case SLAB_CHUNK_MAX: if (subopts_value == NULL) { fprintf(stderr, "Missing slab_chunk_max argument\n"); } if (!safe_strtol(subopts_value, &settings.slab_chunk_size_max)) { fprintf(stderr, "could not parse argument to slab_chunk_max\n"); } slab_chunk_size_changed = true; break; case TRACK_SIZES: item_stats_sizes_init(); break; case NO_INLINE_ASCII_RESP: settings.inline_ascii_response = false; break; case MODERN: /* Modernized defaults. Need to add equivalent no_* flags * before making truly default. */ // chunk default should come after stitching is fixed. //settings.slab_chunk_size_max = 16384; // With slab_ressign, pages are always 1MB, so anything larger // than .5m ends up using 1m anyway. With this we at least // avoid having several slab classes that use 1m. if (!slab_chunk_size_changed) { settings.slab_chunk_size_max = 524288; } settings.slab_reassign = true; settings.slab_automove = 1; settings.maxconns_fast = true; settings.inline_ascii_response = false; settings.lru_segmented = true; hash_type = MURMUR3_HASH; start_lru_crawler = true; start_lru_maintainer = true; break; default: printf("Illegal suboption \"%s\"\n", subopts_value); return 1; } } free(subopts_orig); break; default: fprintf(stderr, "Illegal argument \"%c\"\n", c); return 1; } } if (settings.slab_chunk_size_max > settings.item_size_max) { fprintf(stderr, "slab_chunk_max (bytes: %d) cannot be larger than -I (item_size_max %d)\n", settings.slab_chunk_size_max, settings.item_size_max); exit(EX_USAGE); } if (settings.item_size_max % settings.slab_chunk_size_max != 0) { fprintf(stderr, "-I (item_size_max: %d) must be evenly divisible by slab_chunk_max (bytes: %d)\n", settings.item_size_max, settings.slab_chunk_size_max); exit(EX_USAGE); } if (settings.slab_page_size % settings.slab_chunk_size_max != 0) { fprintf(stderr, "slab_chunk_max (bytes: %d) must divide evenly into %d (slab_page_size)\n", settings.slab_chunk_size_max, settings.slab_page_size); exit(EX_USAGE); } // Reserve this for the new default. If factor size hasn't changed, use // new default. /*if (settings.slab_chunk_size_max == 16384 && settings.factor == 1.25) { settings.factor = 1.08; }*/ if (slab_sizes_unparsed != NULL) { if (_parse_slab_sizes(slab_sizes_unparsed, slab_sizes)) { use_slab_sizes = true; } else { exit(EX_USAGE); } } if (settings.hot_lru_pct + settings.warm_lru_pct > 80) { fprintf(stderr, "hot_lru_pct + warm_lru_pct cannot be more than 80%% combined\n"); exit(EX_USAGE); } if (settings.temp_lru && !start_lru_maintainer) { fprintf(stderr, "temporary_ttl requires lru_maintainer to be enabled\n"); exit(EX_USAGE); } if (hash_init(hash_type) != 0) { fprintf(stderr, "Failed to initialize hash_algorithm!\n"); exit(EX_USAGE); } /* * Use one workerthread to serve each UDP port if the user specified * multiple ports */ if (settings.inter != NULL && strchr(settings.inter, ',')) { settings.num_threads_per_udp = 1; } else { settings.num_threads_per_udp = settings.num_threads; } if (settings.sasl) { if (!protocol_specified) { settings.binding_protocol = binary_prot; } else { if (settings.binding_protocol != binary_prot) { fprintf(stderr, "ERROR: You cannot allow the ASCII protocol while using SASL.\n"); exit(EX_USAGE); } } } if (tcp_specified && !udp_specified) { settings.udpport = settings.port; } else if (udp_specified && !tcp_specified) { settings.port = settings.udpport; } if (maxcore != 0) { struct rlimit rlim_new; /* * First try raising to infinity; if that fails, try bringing * the soft limit to the hard. */ if (getrlimit(RLIMIT_CORE, &rlim) == 0) { rlim_new.rlim_cur = rlim_new.rlim_max = RLIM_INFINITY; if (setrlimit(RLIMIT_CORE, &rlim_new)!= 0) { /* failed. try raising just to the old max */ rlim_new.rlim_cur = rlim_new.rlim_max = rlim.rlim_max; (void)setrlimit(RLIMIT_CORE, &rlim_new); } } /* * getrlimit again to see what we ended up with. Only fail if * the soft limit ends up 0, because then no core files will be * created at all. */ if ((getrlimit(RLIMIT_CORE, &rlim) != 0) || rlim.rlim_cur == 0) { fprintf(stderr, "failed to ensure corefile creation\n"); exit(EX_OSERR); } } /* * If needed, increase rlimits to allow as many connections * as needed. */ if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to getrlimit number of files\n"); exit(EX_OSERR); } else { rlim.rlim_cur = settings.maxconns; rlim.rlim_max = settings.maxconns; if (setrlimit(RLIMIT_NOFILE, &rlim) != 0) { fprintf(stderr, "failed to set rlimit for open files. Try starting as root or requesting smaller maxconns value.\n"); exit(EX_OSERR); } } /* lose root privileges if we have them */ if (getuid() == 0 || geteuid() == 0) { if (username == 0 || *username == '\0') { fprintf(stderr, "can't run as root without the -u switch\n"); exit(EX_USAGE); } if ((pw = getpwnam(username)) == 0) { fprintf(stderr, "can't find the user %s to switch to\n", username); exit(EX_NOUSER); } if (setgid(pw->pw_gid) < 0 || setuid(pw->pw_uid) < 0) { fprintf(stderr, "failed to assume identity of user %s\n", username); exit(EX_OSERR); } } /* Initialize Sasl if -S was specified */ if (settings.sasl) { init_sasl(); } /* daemonize if requested */ /* if we want to ensure our ability to dump core, don't chdir to / */ if (do_daemonize) { if (sigignore(SIGHUP) == -1) { perror("Failed to ignore SIGHUP"); } if (daemonize(maxcore, settings.verbose) == -1) { fprintf(stderr, "failed to daemon() in order to daemonize\n"); exit(EXIT_FAILURE); } } /* lock paged memory if needed */ if (lock_memory) { #ifdef HAVE_MLOCKALL int res = mlockall(MCL_CURRENT | MCL_FUTURE); if (res != 0) { fprintf(stderr, "warning: -k invalid, mlockall() failed: %s\n", strerror(errno)); } #else fprintf(stderr, "warning: -k invalid, mlockall() not supported on this platform. proceeding without.\n"); #endif } /* initialize main thread libevent instance */ main_base = event_init(); /* initialize other stuff */ logger_init(); stats_init(); assoc_init(settings.hashpower_init); conn_init(); slabs_init(settings.maxbytes, settings.factor, preallocate, use_slab_sizes ? slab_sizes : NULL); /* * ignore SIGPIPE signals; we can use errno == EPIPE if we * need that information */ if (sigignore(SIGPIPE) == -1) { perror("failed to ignore SIGPIPE; sigaction"); exit(EX_OSERR); } /* start up worker threads if MT mode */ memcached_thread_init(settings.num_threads); if (start_assoc_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (start_lru_crawler && start_item_crawler_thread() != 0) { fprintf(stderr, "Failed to enable LRU crawler thread\n"); exit(EXIT_FAILURE); } if (start_lru_maintainer && start_lru_maintainer_thread() != 0) { fprintf(stderr, "Failed to enable LRU maintainer thread\n"); return 1; } if (settings.slab_reassign && start_slab_maintenance_thread() == -1) { exit(EXIT_FAILURE); } if (settings.idle_timeout && start_conn_timeout_thread() == -1) { exit(EXIT_FAILURE); } /* initialise clock event */ clock_handler(0, 0, 0); /* create unix mode sockets after dropping privileges */ if (settings.socketpath != NULL) { errno = 0; if (server_socket_unix(settings.socketpath,settings.access)) { vperror("failed to listen on UNIX socket: %s", settings.socketpath); exit(EX_OSERR); } } /* create the listening socket, bind it, and init */ if (settings.socketpath == NULL) { const char *portnumber_filename = getenv("MEMCACHED_PORT_FILENAME"); char *temp_portnumber_filename = NULL; size_t len; FILE *portnumber_file = NULL; if (portnumber_filename != NULL) { len = strlen(portnumber_filename)+4+1; temp_portnumber_filename = malloc(len); snprintf(temp_portnumber_filename, len, "%s.lck", portnumber_filename); portnumber_file = fopen(temp_portnumber_filename, "a"); if (portnumber_file == NULL) { fprintf(stderr, "Failed to open \"%s\": %s\n", temp_portnumber_filename, strerror(errno)); } } errno = 0; if (settings.port && server_sockets(settings.port, tcp_transport, portnumber_file)) { vperror("failed to listen on TCP port %d", settings.port); exit(EX_OSERR); } /* * initialization order: first create the listening sockets * (may need root on low ports), then drop root if needed, * then daemonise if needed, then init libevent (in some cases * descriptors created by libevent wouldn't survive forking). */ /* create the UDP listening socket and bind it */ errno = 0; if (settings.udpport && server_sockets(settings.udpport, udp_transport, portnumber_file)) { vperror("failed to listen on UDP port %d", settings.udpport); exit(EX_OSERR); } if (portnumber_file) { fclose(portnumber_file); rename(temp_portnumber_filename, portnumber_filename); free(temp_portnumber_filename); } } /* Give the sockets a moment to open. I know this is dumb, but the error * is only an advisory. */ usleep(1000); if (stats_state.curr_conns + stats_state.reserved_fds >= settings.maxconns - 1) { fprintf(stderr, "Maxconns setting is too low, use -c to increase.\n"); exit(EXIT_FAILURE); } if (pid_file != NULL) { save_pid(pid_file); } /* Drop privileges no longer needed */ drop_privileges(); /* Initialize the uriencode lookup table. */ uriencode_init(); /* enter the event loop */ if (event_base_loop(main_base, 0) != 0) { retval = EXIT_FAILURE; } stop_assoc_maintenance_thread(); /* remove the PID file if we're a daemon */ if (do_daemonize) remove_pidfile(pid_file); /* Clean up strdup() call for bind() address */ if (settings.inter) free(settings.inter); if (l_socket) free(l_socket); if (u_socket) free(u_socket); return retval; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_23_0
crossvul-cpp_data_bad_1834_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M M EEEEE M M OOO RRRR Y Y % % MM MM E MM MM O O R R Y Y % % M M M EEE M M M O O RRRR Y % % M M E M M O O R R Y % % M M EEEEE M M OOO R R Y % % % % % % MagickCore Memory Allocation Methods % % % % Software Design % % Cristy % % July 1998 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segregate our memory requirements from any program that calls our API. This % should help reduce the risk of others changing our program state or causing % memory corruption. % % Our custom memory allocation manager implements a best-fit allocation policy % using segregated free lists. It uses a linear distribution of size classes % for lower sizes and a power of two distribution of size classes at higher % sizes. It is based on the paper, "Fast Memory Allocation using Lazy Fits." % written by Yoo C. Chung. % % By default, ANSI memory methods are called (e.g. malloc). Use the % custom memory allocator by defining MAGICKCORE_ZERO_CONFIGURATION_SUPPORT % to allocate memory with private anonymous mapping rather than from the % heap. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/string_.h" #include "MagickCore/utility-private.h" /* Define declarations. */ #define BlockFooter(block,size) \ ((size_t *) ((char *) (block)+(size)-2*sizeof(size_t))) #define BlockHeader(block) ((size_t *) (block)-1) #define BlockSize 4096 #define BlockThreshold 1024 #define MaxBlockExponent 16 #define MaxBlocks ((BlockThreshold/(4*sizeof(size_t)))+MaxBlockExponent+1) #define MaxSegments 1024 #define MemoryGuard ((0xdeadbeef << 31)+0xdeafdeed) #define NextBlock(block) ((char *) (block)+SizeOfBlock(block)) #define NextBlockInList(block) (*(void **) (block)) #define PreviousBlock(block) ((char *) (block)-(*((size_t *) (block)-2))) #define PreviousBlockBit 0x01 #define PreviousBlockInList(block) (*((void **) (block)+1)) #define SegmentSize (2*1024*1024) #define SizeMask (~0x01) #define SizeOfBlock(block) (*BlockHeader(block) & SizeMask) /* Typedef declarations. */ typedef enum { UndefinedVirtualMemory, AlignedVirtualMemory, MapVirtualMemory, UnalignedVirtualMemory } VirtualMemoryType; typedef struct _DataSegmentInfo { void *allocation, *bound; MagickBooleanType mapped; size_t length; struct _DataSegmentInfo *previous, *next; } DataSegmentInfo; typedef struct _MagickMemoryMethods { AcquireMemoryHandler acquire_memory_handler; ResizeMemoryHandler resize_memory_handler; DestroyMemoryHandler destroy_memory_handler; } MagickMemoryMethods; struct _MemoryInfo { char filename[MagickPathExtent]; VirtualMemoryType type; size_t length; void *blob; size_t signature; }; typedef struct _MemoryPool { size_t allocation; void *blocks[MaxBlocks+1]; size_t number_segments; DataSegmentInfo *segments[MaxSegments], segment_pool[MaxSegments]; } MemoryPool; /* Global declarations. */ #if defined _MSC_VER static void* MSCMalloc(size_t size) { return malloc(size); } static void* MSCRealloc(void* ptr, size_t size) { return realloc(ptr, size); } static void MSCFree(void* ptr) { free(ptr); } #endif static MagickMemoryMethods memory_methods = { #if defined _MSC_VER (AcquireMemoryHandler) MSCMalloc, (ResizeMemoryHandler) MSCRealloc, (DestroyMemoryHandler) MSCFree #else (AcquireMemoryHandler) malloc, (ResizeMemoryHandler) realloc, (DestroyMemoryHandler) free #endif }; #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) static MemoryPool memory_pool; static SemaphoreInfo *memory_semaphore = (SemaphoreInfo *) NULL; static volatile DataSegmentInfo *free_segments = (DataSegmentInfo *) NULL; /* Forward declarations. */ static MagickBooleanType ExpandHeap(size_t); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e A l i g n e d M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireAlignedMemory() returns a pointer to a block of memory at least size % bytes whose address is a multiple of 16*sizeof(void *). % % The format of the AcquireAlignedMemory method is: % % void *AcquireAlignedMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *AcquireAlignedMemory(const size_t count,const size_t quantum) { #define AlignedExtent(size,alignment) \ (((size)+((alignment)-1)) & ~((alignment)-1)) size_t alignment, extent, size; void *memory; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { errno=ENOMEM; return((void *) NULL); } memory=NULL; alignment=CACHE_LINE_SIZE; extent=AlignedExtent(size,alignment); if ((size == 0) || (alignment < sizeof(void *)) || (extent < size)) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) if (posix_memalign(&memory,alignment,extent) != 0) memory=NULL; #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) memory=_aligned_malloc(extent,alignment); #else { void *p; extent=(size+alignment-1)+sizeof(void *); if (extent > size) { p=malloc(extent); if (p != NULL) { memory=(void *) AlignedExtent((size_t) p+sizeof(void *),alignment); *((void **) memory-1)=p; } } } #endif return(memory); } #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e B l o c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireBlock() returns a pointer to a block of memory at least size bytes % suitably aligned for any use. % % The format of the AcquireBlock method is: % % void *AcquireBlock(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ static inline size_t AllocationPolicy(size_t size) { register size_t blocksize; /* The linear distribution. */ assert(size != 0); assert(size % (4*sizeof(size_t)) == 0); if (size <= BlockThreshold) return(size/(4*sizeof(size_t))); /* Check for the largest block size. */ if (size > (size_t) (BlockThreshold*(1L << (MaxBlockExponent-1L)))) return(MaxBlocks-1L); /* Otherwise use a power of two distribution. */ blocksize=BlockThreshold/(4*sizeof(size_t)); for ( ; size > BlockThreshold; size/=2) blocksize++; assert(blocksize > (BlockThreshold/(4*sizeof(size_t)))); assert(blocksize < (MaxBlocks-1L)); return(blocksize); } static inline void InsertFreeBlock(void *block,const size_t i) { register void *next, *previous; size_t size; size=SizeOfBlock(block); previous=(void *) NULL; next=memory_pool.blocks[i]; while ((next != (void *) NULL) && (SizeOfBlock(next) < size)) { previous=next; next=NextBlockInList(next); } PreviousBlockInList(block)=previous; NextBlockInList(block)=next; if (previous != (void *) NULL) NextBlockInList(previous)=block; else memory_pool.blocks[i]=block; if (next != (void *) NULL) PreviousBlockInList(next)=block; } static inline void RemoveFreeBlock(void *block,const size_t i) { register void *next, *previous; next=NextBlockInList(block); previous=PreviousBlockInList(block); if (previous == (void *) NULL) memory_pool.blocks[i]=next; else NextBlockInList(previous)=next; if (next != (void *) NULL) PreviousBlockInList(next)=previous; } static void *AcquireBlock(size_t size) { register size_t i; register void *block; /* Find free block. */ size=(size_t) (size+sizeof(size_t)+6*sizeof(size_t)-1) & -(4U*sizeof(size_t)); i=AllocationPolicy(size); block=memory_pool.blocks[i]; while ((block != (void *) NULL) && (SizeOfBlock(block) < size)) block=NextBlockInList(block); if (block == (void *) NULL) { i++; while (memory_pool.blocks[i] == (void *) NULL) i++; block=memory_pool.blocks[i]; if (i >= MaxBlocks) return((void *) NULL); } assert((*BlockHeader(NextBlock(block)) & PreviousBlockBit) == 0); assert(SizeOfBlock(block) >= size); RemoveFreeBlock(block,AllocationPolicy(SizeOfBlock(block))); if (SizeOfBlock(block) > size) { size_t blocksize; void *next; /* Split block. */ next=(char *) block+size; blocksize=SizeOfBlock(block)-size; *BlockHeader(next)=blocksize; *BlockFooter(next,blocksize)=blocksize; InsertFreeBlock(next,AllocationPolicy(blocksize)); *BlockHeader(block)=size | (*BlockHeader(block) & ~SizeMask); } assert(size == SizeOfBlock(block)); *BlockHeader(NextBlock(block))|=PreviousBlockBit; memory_pool.allocation+=size; return(block); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireMagickMemory() returns a pointer to a block of memory at least size % bytes suitably aligned for any use. % % The format of the AcquireMagickMemory method is: % % void *AcquireMagickMemory(const size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *AcquireMagickMemory(const size_t size) { register void *memory; #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) memory=memory_methods.acquire_memory_handler(size == 0 ? 1UL : size); #else if (memory_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&memory_semaphore); if (free_segments == (DataSegmentInfo *) NULL) { LockSemaphoreInfo(memory_semaphore); if (free_segments == (DataSegmentInfo *) NULL) { register ssize_t i; assert(2*sizeof(size_t) > (size_t) (~SizeMask)); (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool)); memory_pool.allocation=SegmentSize; memory_pool.blocks[MaxBlocks]=(void *) (-1); for (i=0; i < MaxSegments; i++) { if (i != 0) memory_pool.segment_pool[i].previous= (&memory_pool.segment_pool[i-1]); if (i != (MaxSegments-1)) memory_pool.segment_pool[i].next=(&memory_pool.segment_pool[i+1]); } free_segments=(&memory_pool.segment_pool[0]); } UnlockSemaphoreInfo(memory_semaphore); } LockSemaphoreInfo(memory_semaphore); memory=AcquireBlock(size == 0 ? 1UL : size); if (memory == (void *) NULL) { if (ExpandHeap(size == 0 ? 1UL : size) != MagickFalse) memory=AcquireBlock(size == 0 ? 1UL : size); } UnlockSemaphoreInfo(memory_semaphore); #endif return(memory); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t u m M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantumMemory() returns a pointer to a block of memory at least % count * quantum bytes suitably aligned for any use. % % The format of the AcquireQuantumMemory method is: % % void *AcquireQuantumMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *AcquireQuantumMemory(const size_t count,const size_t quantum) { size_t size; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { errno=ENOMEM; return((void *) NULL); } return(AcquireMagickMemory(size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e V i r t u a l M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireVirtualMemory() allocates a pointer to a block of memory at least size % bytes suitably aligned for any use. % % The format of the AcquireVirtualMemory method is: % % MemoryInfo *AcquireVirtualMemory(const size_t count,const size_t quantum) % % A description of each parameter follows: % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport MemoryInfo *AcquireVirtualMemory(const size_t count, const size_t quantum) { MemoryInfo *memory_info; size_t length; length=count*quantum; if ((count == 0) || (quantum != (length/count))) { errno=ENOMEM; return((MemoryInfo *) NULL); } memory_info=(MemoryInfo *) MagickAssumeAligned(AcquireAlignedMemory(1, sizeof(*memory_info))); if (memory_info == (MemoryInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) ResetMagickMemory(memory_info,0,sizeof(*memory_info)); memory_info->length=length; memory_info->signature=MagickSignature; if (AcquireMagickResource(MemoryResource,length) != MagickFalse) { memory_info->blob=AcquireAlignedMemory(1,length); if (memory_info->blob != NULL) memory_info->type=AlignedVirtualMemory; else RelinquishMagickResource(MemoryResource,length); } if ((memory_info->blob == NULL) && (AcquireMagickResource(MapResource,length) != MagickFalse)) { /* Heap memory failed, try anonymous memory mapping. */ memory_info->blob=MapBlob(-1,IOMode,0,length); if (memory_info->blob != NULL) memory_info->type=MapVirtualMemory; else RelinquishMagickResource(MapResource,length); } if (memory_info->blob == NULL) { int file; /* Anonymous memory mapping failed, try file-backed memory mapping. */ file=AcquireUniqueFileResource(memory_info->filename); if (file != -1) { if ((lseek(file,length-1,SEEK_SET) >= 0) && (write(file,"",1) == 1)) { memory_info->blob=MapBlob(file,IOMode,0,length); if (memory_info->blob != NULL) { memory_info->type=MapVirtualMemory; (void) AcquireMagickResource(MapResource,length); } } (void) close(file); } } if (memory_info->blob == NULL) { memory_info->blob=AcquireMagickMemory(length); if (memory_info->blob != NULL) memory_info->type=UnalignedVirtualMemory; } if (memory_info->blob == NULL) memory_info=RelinquishVirtualMemory(memory_info); return(memory_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o p y M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CopyMagickMemory() copies size bytes from memory area source to the % destination. Copying between objects that overlap will take place % correctly. It returns destination. % % The format of the CopyMagickMemory method is: % % void *CopyMagickMemory(void *destination,const void *source, % const size_t size) % % A description of each parameter follows: % % o destination: the destination. % % o source: the source. % % o size: the size of the memory in bytes to allocate. % */ MagickExport void *CopyMagickMemory(void *destination,const void *source, const size_t size) { register const unsigned char *p; register unsigned char *q; assert(destination != (void *) NULL); assert(source != (const void *) NULL); p=(const unsigned char *) source; q=(unsigned char *) destination; if (((q+size) < p) || (q > (p+size))) switch (size) { default: return(memcpy(destination,source,size)); case 8: *q++=(*p++); case 7: *q++=(*p++); case 6: *q++=(*p++); case 5: *q++=(*p++); case 4: *q++=(*p++); case 3: *q++=(*p++); case 2: *q++=(*p++); case 1: *q++=(*p++); case 0: return(destination); } return(memmove(destination,source,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyMagickMemory() deallocates memory associated with the memory manager. % % The format of the DestroyMagickMemory method is: % % DestroyMagickMemory(void) % */ MagickExport void DestroyMagickMemory(void) { #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) register ssize_t i; if (memory_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&memory_semaphore); LockSemaphoreInfo(memory_semaphore); for (i=0; i < (ssize_t) memory_pool.number_segments; i++) if (memory_pool.segments[i]->mapped == MagickFalse) memory_methods.destroy_memory_handler( memory_pool.segments[i]->allocation); else (void) UnmapBlob(memory_pool.segments[i]->allocation, memory_pool.segments[i]->length); free_segments=(DataSegmentInfo *) NULL; (void) ResetMagickMemory(&memory_pool,0,sizeof(memory_pool)); UnlockSemaphoreInfo(memory_semaphore); RelinquishSemaphoreInfo(&memory_semaphore); #endif } #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E x p a n d H e a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExpandHeap() get more memory from the system. It returns MagickTrue on % success otherwise MagickFalse. % % The format of the ExpandHeap method is: % % MagickBooleanType ExpandHeap(size_t size) % % A description of each parameter follows: % % o size: the size of the memory in bytes we require. % */ static MagickBooleanType ExpandHeap(size_t size) { DataSegmentInfo *segment_info; MagickBooleanType mapped; register ssize_t i; register void *block; size_t blocksize; void *segment; blocksize=((size+12*sizeof(size_t))+SegmentSize-1) & -SegmentSize; assert(memory_pool.number_segments < MaxSegments); segment=MapBlob(-1,IOMode,0,blocksize); mapped=segment != (void *) NULL ? MagickTrue : MagickFalse; if (segment == (void *) NULL) segment=(void *) memory_methods.acquire_memory_handler(blocksize); if (segment == (void *) NULL) return(MagickFalse); segment_info=(DataSegmentInfo *) free_segments; free_segments=segment_info->next; segment_info->mapped=mapped; segment_info->length=blocksize; segment_info->allocation=segment; segment_info->bound=(char *) segment+blocksize; i=(ssize_t) memory_pool.number_segments-1; for ( ; (i >= 0) && (memory_pool.segments[i]->allocation > segment); i--) memory_pool.segments[i+1]=memory_pool.segments[i]; memory_pool.segments[i+1]=segment_info; memory_pool.number_segments++; size=blocksize-12*sizeof(size_t); block=(char *) segment_info->allocation+4*sizeof(size_t); *BlockHeader(block)=size | PreviousBlockBit; *BlockFooter(block,size)=size; InsertFreeBlock(block,AllocationPolicy(size)); block=NextBlock(block); assert(block < segment_info->bound); *BlockHeader(block)=2*sizeof(size_t); *BlockHeader(NextBlock(block))=PreviousBlockBit; return(MagickTrue); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k M e m o r y M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickMemoryMethods() gets the methods to acquire, resize, and destroy % memory. % % The format of the GetMagickMemoryMethods() method is: % % void GetMagickMemoryMethods(AcquireMemoryHandler *acquire_memory_handler, % ResizeMemoryHandler *resize_memory_handler, % DestroyMemoryHandler *destroy_memory_handler) % % A description of each parameter follows: % % o acquire_memory_handler: method to acquire memory (e.g. malloc). % % o resize_memory_handler: method to resize memory (e.g. realloc). % % o destroy_memory_handler: method to destroy memory (e.g. free). % */ MagickExport void GetMagickMemoryMethods( AcquireMemoryHandler *acquire_memory_handler, ResizeMemoryHandler *resize_memory_handler, DestroyMemoryHandler *destroy_memory_handler) { assert(acquire_memory_handler != (AcquireMemoryHandler *) NULL); assert(resize_memory_handler != (ResizeMemoryHandler *) NULL); assert(destroy_memory_handler != (DestroyMemoryHandler *) NULL); *acquire_memory_handler=memory_methods.acquire_memory_handler; *resize_memory_handler=memory_methods.resize_memory_handler; *destroy_memory_handler=memory_methods.destroy_memory_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e m o r y B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMemoryBlob() returns the virtual memory blob associated with the % specified MemoryInfo structure. % % The format of the GetVirtualMemoryBlob method is: % % void *GetVirtualMemoryBlob(const MemoryInfo *memory_info) % % A description of each parameter follows: % % o memory_info: The MemoryInfo structure. */ MagickExport void *GetVirtualMemoryBlob(const MemoryInfo *memory_info) { assert(memory_info != (const MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); return(memory_info->blob); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h A l i g n e d M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishAlignedMemory() frees memory acquired with AcquireAlignedMemory() % or reuse. % % The format of the RelinquishAlignedMemory method is: % % void *RelinquishAlignedMemory(void *memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void *RelinquishAlignedMemory(void *memory) { if (memory == (void *) NULL) return((void *) NULL); #if defined(MAGICKCORE_HAVE_POSIX_MEMALIGN) free(memory); #elif defined(MAGICKCORE_HAVE__ALIGNED_MALLOC) _aligned_free(memory); #else free(*((void **) memory-1)); #endif return(NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishMagickMemory() frees memory acquired with AcquireMagickMemory() % or AcquireQuantumMemory() for reuse. % % The format of the RelinquishMagickMemory method is: % % void *RelinquishMagickMemory(void *memory) % % A description of each parameter follows: % % o memory: A pointer to a block of memory to free for reuse. % */ MagickExport void *RelinquishMagickMemory(void *memory) { if (memory == (void *) NULL) return((void *) NULL); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) memory_methods.destroy_memory_handler(memory); #else LockSemaphoreInfo(memory_semaphore); assert((SizeOfBlock(memory) % (4*sizeof(size_t))) == 0); assert((*BlockHeader(NextBlock(memory)) & PreviousBlockBit) != 0); if ((*BlockHeader(memory) & PreviousBlockBit) == 0) { void *previous; /* Coalesce with previous adjacent block. */ previous=PreviousBlock(memory); RemoveFreeBlock(previous,AllocationPolicy(SizeOfBlock(previous))); *BlockHeader(previous)=(SizeOfBlock(previous)+SizeOfBlock(memory)) | (*BlockHeader(previous) & ~SizeMask); memory=previous; } if ((*BlockHeader(NextBlock(NextBlock(memory))) & PreviousBlockBit) == 0) { void *next; /* Coalesce with next adjacent block. */ next=NextBlock(memory); RemoveFreeBlock(next,AllocationPolicy(SizeOfBlock(next))); *BlockHeader(memory)=(SizeOfBlock(memory)+SizeOfBlock(next)) | (*BlockHeader(memory) & ~SizeMask); } *BlockFooter(memory,SizeOfBlock(memory))=SizeOfBlock(memory); *BlockHeader(NextBlock(memory))&=(~PreviousBlockBit); InsertFreeBlock(memory,AllocationPolicy(SizeOfBlock(memory))); UnlockSemaphoreInfo(memory_semaphore); #endif return((void *) NULL); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e l i n q u i s h V i r t u a l M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RelinquishVirtualMemory() frees memory acquired with AcquireVirtualMemory(). % % The format of the RelinquishVirtualMemory method is: % % MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) % % A description of each parameter follows: % % o memory_info: A pointer to a block of memory to free for reuse. % */ MagickExport MemoryInfo *RelinquishVirtualMemory(MemoryInfo *memory_info) { assert(memory_info != (MemoryInfo *) NULL); assert(memory_info->signature == MagickSignature); if (memory_info->blob != (void *) NULL) switch (memory_info->type) { case AlignedVirtualMemory: { memory_info->blob=RelinquishAlignedMemory(memory_info->blob); RelinquishMagickResource(MemoryResource,memory_info->length); break; } case MapVirtualMemory: { (void) UnmapBlob(memory_info->blob,memory_info->length); memory_info->blob=NULL; RelinquishMagickResource(MapResource,memory_info->length); if (*memory_info->filename != '\0') (void) RelinquishUniqueFileResource(memory_info->filename); break; } case UnalignedVirtualMemory: default: { memory_info->blob=RelinquishMagickMemory(memory_info->blob); break; } } memory_info->signature=(~MagickSignature); memory_info=(MemoryInfo *) RelinquishAlignedMemory(memory_info); return(memory_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetMagickMemory() fills the first size bytes of the memory area pointed to % by memory with the constant byte c. % % The format of the ResetMagickMemory method is: % % void *ResetMagickMemory(void *memory,int byte,const size_t size) % % A description of each parameter follows: % % o memory: a pointer to a memory allocation. % % o byte: set the memory to this value. % % o size: size of the memory to reset. % */ MagickExport void *ResetMagickMemory(void *memory,int byte,const size_t size) { assert(memory != (void *) NULL); return(memset(memory,byte,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e M a g i c k M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeMagickMemory() changes the size of the memory and returns a pointer to % the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ResizeMagickMemory method is: % % void *ResizeMagickMemory(void *memory,const size_t size) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. % % o size: the new size of the allocated memory. % */ #if defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) static inline void *ResizeBlock(void *block,size_t size) { register void *memory; if (block == (void *) NULL) return(AcquireBlock(size)); memory=AcquireBlock(size); if (memory == (void *) NULL) return((void *) NULL); if (size <= (SizeOfBlock(block)-sizeof(size_t))) (void) memcpy(memory,block,size); else (void) memcpy(memory,block,SizeOfBlock(block)-sizeof(size_t)); memory_pool.allocation+=size; return(memory); } #endif MagickExport void *ResizeMagickMemory(void *memory,const size_t size) { register void *block; if (memory == (void *) NULL) return(AcquireMagickMemory(size)); #if !defined(MAGICKCORE_ZERO_CONFIGURATION_SUPPORT) block=memory_methods.resize_memory_handler(memory,size == 0 ? 1UL : size); if (block == (void *) NULL) memory=RelinquishMagickMemory(memory); #else LockSemaphoreInfo(memory_semaphore); block=ResizeBlock(memory,size == 0 ? 1UL : size); if (block == (void *) NULL) { if (ExpandHeap(size == 0 ? 1UL : size) == MagickFalse) { UnlockSemaphoreInfo(memory_semaphore); memory=RelinquishMagickMemory(memory); ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); } block=ResizeBlock(memory,size == 0 ? 1UL : size); assert(block != (void *) NULL); } UnlockSemaphoreInfo(memory_semaphore); memory=RelinquishMagickMemory(memory); #endif return(block); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s i z e Q u a n t u m M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResizeQuantumMemory() changes the size of the memory and returns a pointer % to the (possibly moved) block. The contents will be unchanged up to the % lesser of the new and old sizes. % % The format of the ResizeQuantumMemory method is: % % void *ResizeQuantumMemory(void *memory,const size_t count, % const size_t quantum) % % A description of each parameter follows: % % o memory: A pointer to a memory allocation. % % o count: the number of quantum elements to allocate. % % o quantum: the number of bytes in each quantum. % */ MagickExport void *ResizeQuantumMemory(void *memory,const size_t count, const size_t quantum) { size_t size; size=count*quantum; if ((count == 0) || (quantum != (size/count))) { memory=RelinquishMagickMemory(memory); errno=ENOMEM; return((void *) NULL); } return(ResizeMagickMemory(memory,size)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t M a g i c k M e m o r y M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetMagickMemoryMethods() sets the methods to acquire, resize, and destroy % memory. Your custom memory methods must be set prior to the % MagickCoreGenesis() method. % % The format of the SetMagickMemoryMethods() method is: % % SetMagickMemoryMethods(AcquireMemoryHandler acquire_memory_handler, % ResizeMemoryHandler resize_memory_handler, % DestroyMemoryHandler destroy_memory_handler) % % A description of each parameter follows: % % o acquire_memory_handler: method to acquire memory (e.g. malloc). % % o resize_memory_handler: method to resize memory (e.g. realloc). % % o destroy_memory_handler: method to destroy memory (e.g. free). % */ MagickExport void SetMagickMemoryMethods( AcquireMemoryHandler acquire_memory_handler, ResizeMemoryHandler resize_memory_handler, DestroyMemoryHandler destroy_memory_handler) { /* Set memory methods. */ if (acquire_memory_handler != (AcquireMemoryHandler) NULL) memory_methods.acquire_memory_handler=acquire_memory_handler; if (resize_memory_handler != (ResizeMemoryHandler) NULL) memory_methods.resize_memory_handler=resize_memory_handler; if (destroy_memory_handler != (DestroyMemoryHandler) NULL) memory_methods.destroy_memory_handler=destroy_memory_handler; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1834_0
crossvul-cpp_data_bad_112_0
/* * 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. */ #include "delta.h" /* maximum hash entry list for the same hash bucket */ #define HASH_LIMIT 64 #define RABIN_SHIFT 23 #define RABIN_WINDOW 16 static const unsigned int T[256] = { 0x00000000, 0xab59b4d1, 0x56b369a2, 0xfdeadd73, 0x063f6795, 0xad66d344, 0x508c0e37, 0xfbd5bae6, 0x0c7ecf2a, 0xa7277bfb, 0x5acda688, 0xf1941259, 0x0a41a8bf, 0xa1181c6e, 0x5cf2c11d, 0xf7ab75cc, 0x18fd9e54, 0xb3a42a85, 0x4e4ef7f6, 0xe5174327, 0x1ec2f9c1, 0xb59b4d10, 0x48719063, 0xe32824b2, 0x1483517e, 0xbfdae5af, 0x423038dc, 0xe9698c0d, 0x12bc36eb, 0xb9e5823a, 0x440f5f49, 0xef56eb98, 0x31fb3ca8, 0x9aa28879, 0x6748550a, 0xcc11e1db, 0x37c45b3d, 0x9c9defec, 0x6177329f, 0xca2e864e, 0x3d85f382, 0x96dc4753, 0x6b369a20, 0xc06f2ef1, 0x3bba9417, 0x90e320c6, 0x6d09fdb5, 0xc6504964, 0x2906a2fc, 0x825f162d, 0x7fb5cb5e, 0xd4ec7f8f, 0x2f39c569, 0x846071b8, 0x798aaccb, 0xd2d3181a, 0x25786dd6, 0x8e21d907, 0x73cb0474, 0xd892b0a5, 0x23470a43, 0x881ebe92, 0x75f463e1, 0xdeadd730, 0x63f67950, 0xc8afcd81, 0x354510f2, 0x9e1ca423, 0x65c91ec5, 0xce90aa14, 0x337a7767, 0x9823c3b6, 0x6f88b67a, 0xc4d102ab, 0x393bdfd8, 0x92626b09, 0x69b7d1ef, 0xc2ee653e, 0x3f04b84d, 0x945d0c9c, 0x7b0be704, 0xd05253d5, 0x2db88ea6, 0x86e13a77, 0x7d348091, 0xd66d3440, 0x2b87e933, 0x80de5de2, 0x7775282e, 0xdc2c9cff, 0x21c6418c, 0x8a9ff55d, 0x714a4fbb, 0xda13fb6a, 0x27f92619, 0x8ca092c8, 0x520d45f8, 0xf954f129, 0x04be2c5a, 0xafe7988b, 0x5432226d, 0xff6b96bc, 0x02814bcf, 0xa9d8ff1e, 0x5e738ad2, 0xf52a3e03, 0x08c0e370, 0xa39957a1, 0x584ced47, 0xf3155996, 0x0eff84e5, 0xa5a63034, 0x4af0dbac, 0xe1a96f7d, 0x1c43b20e, 0xb71a06df, 0x4ccfbc39, 0xe79608e8, 0x1a7cd59b, 0xb125614a, 0x468e1486, 0xedd7a057, 0x103d7d24, 0xbb64c9f5, 0x40b17313, 0xebe8c7c2, 0x16021ab1, 0xbd5bae60, 0x6cb54671, 0xc7ecf2a0, 0x3a062fd3, 0x915f9b02, 0x6a8a21e4, 0xc1d39535, 0x3c394846, 0x9760fc97, 0x60cb895b, 0xcb923d8a, 0x3678e0f9, 0x9d215428, 0x66f4eece, 0xcdad5a1f, 0x3047876c, 0x9b1e33bd, 0x7448d825, 0xdf116cf4, 0x22fbb187, 0x89a20556, 0x7277bfb0, 0xd92e0b61, 0x24c4d612, 0x8f9d62c3, 0x7836170f, 0xd36fa3de, 0x2e857ead, 0x85dcca7c, 0x7e09709a, 0xd550c44b, 0x28ba1938, 0x83e3ade9, 0x5d4e7ad9, 0xf617ce08, 0x0bfd137b, 0xa0a4a7aa, 0x5b711d4c, 0xf028a99d, 0x0dc274ee, 0xa69bc03f, 0x5130b5f3, 0xfa690122, 0x0783dc51, 0xacda6880, 0x570fd266, 0xfc5666b7, 0x01bcbbc4, 0xaae50f15, 0x45b3e48d, 0xeeea505c, 0x13008d2f, 0xb85939fe, 0x438c8318, 0xe8d537c9, 0x153feaba, 0xbe665e6b, 0x49cd2ba7, 0xe2949f76, 0x1f7e4205, 0xb427f6d4, 0x4ff24c32, 0xe4abf8e3, 0x19412590, 0xb2189141, 0x0f433f21, 0xa41a8bf0, 0x59f05683, 0xf2a9e252, 0x097c58b4, 0xa225ec65, 0x5fcf3116, 0xf49685c7, 0x033df00b, 0xa86444da, 0x558e99a9, 0xfed72d78, 0x0502979e, 0xae5b234f, 0x53b1fe3c, 0xf8e84aed, 0x17bea175, 0xbce715a4, 0x410dc8d7, 0xea547c06, 0x1181c6e0, 0xbad87231, 0x4732af42, 0xec6b1b93, 0x1bc06e5f, 0xb099da8e, 0x4d7307fd, 0xe62ab32c, 0x1dff09ca, 0xb6a6bd1b, 0x4b4c6068, 0xe015d4b9, 0x3eb80389, 0x95e1b758, 0x680b6a2b, 0xc352defa, 0x3887641c, 0x93ded0cd, 0x6e340dbe, 0xc56db96f, 0x32c6cca3, 0x999f7872, 0x6475a501, 0xcf2c11d0, 0x34f9ab36, 0x9fa01fe7, 0x624ac294, 0xc9137645, 0x26459ddd, 0x8d1c290c, 0x70f6f47f, 0xdbaf40ae, 0x207afa48, 0x8b234e99, 0x76c993ea, 0xdd90273b, 0x2a3b52f7, 0x8162e626, 0x7c883b55, 0xd7d18f84, 0x2c043562, 0x875d81b3, 0x7ab75cc0, 0xd1eee811 }; static const unsigned int U[256] = { 0x00000000, 0x7eb5200d, 0x5633f4cb, 0x2886d4c6, 0x073e5d47, 0x798b7d4a, 0x510da98c, 0x2fb88981, 0x0e7cba8e, 0x70c99a83, 0x584f4e45, 0x26fa6e48, 0x0942e7c9, 0x77f7c7c4, 0x5f711302, 0x21c4330f, 0x1cf9751c, 0x624c5511, 0x4aca81d7, 0x347fa1da, 0x1bc7285b, 0x65720856, 0x4df4dc90, 0x3341fc9d, 0x1285cf92, 0x6c30ef9f, 0x44b63b59, 0x3a031b54, 0x15bb92d5, 0x6b0eb2d8, 0x4388661e, 0x3d3d4613, 0x39f2ea38, 0x4747ca35, 0x6fc11ef3, 0x11743efe, 0x3eccb77f, 0x40799772, 0x68ff43b4, 0x164a63b9, 0x378e50b6, 0x493b70bb, 0x61bda47d, 0x1f088470, 0x30b00df1, 0x4e052dfc, 0x6683f93a, 0x1836d937, 0x250b9f24, 0x5bbebf29, 0x73386bef, 0x0d8d4be2, 0x2235c263, 0x5c80e26e, 0x740636a8, 0x0ab316a5, 0x2b7725aa, 0x55c205a7, 0x7d44d161, 0x03f1f16c, 0x2c4978ed, 0x52fc58e0, 0x7a7a8c26, 0x04cfac2b, 0x73e5d470, 0x0d50f47d, 0x25d620bb, 0x5b6300b6, 0x74db8937, 0x0a6ea93a, 0x22e87dfc, 0x5c5d5df1, 0x7d996efe, 0x032c4ef3, 0x2baa9a35, 0x551fba38, 0x7aa733b9, 0x041213b4, 0x2c94c772, 0x5221e77f, 0x6f1ca16c, 0x11a98161, 0x392f55a7, 0x479a75aa, 0x6822fc2b, 0x1697dc26, 0x3e1108e0, 0x40a428ed, 0x61601be2, 0x1fd53bef, 0x3753ef29, 0x49e6cf24, 0x665e46a5, 0x18eb66a8, 0x306db26e, 0x4ed89263, 0x4a173e48, 0x34a21e45, 0x1c24ca83, 0x6291ea8e, 0x4d29630f, 0x339c4302, 0x1b1a97c4, 0x65afb7c9, 0x446b84c6, 0x3adea4cb, 0x1258700d, 0x6ced5000, 0x4355d981, 0x3de0f98c, 0x15662d4a, 0x6bd30d47, 0x56ee4b54, 0x285b6b59, 0x00ddbf9f, 0x7e689f92, 0x51d01613, 0x2f65361e, 0x07e3e2d8, 0x7956c2d5, 0x5892f1da, 0x2627d1d7, 0x0ea10511, 0x7014251c, 0x5facac9d, 0x21198c90, 0x099f5856, 0x772a785b, 0x4c921c31, 0x32273c3c, 0x1aa1e8fa, 0x6414c8f7, 0x4bac4176, 0x3519617b, 0x1d9fb5bd, 0x632a95b0, 0x42eea6bf, 0x3c5b86b2, 0x14dd5274, 0x6a687279, 0x45d0fbf8, 0x3b65dbf5, 0x13e30f33, 0x6d562f3e, 0x506b692d, 0x2ede4920, 0x06589de6, 0x78edbdeb, 0x5755346a, 0x29e01467, 0x0166c0a1, 0x7fd3e0ac, 0x5e17d3a3, 0x20a2f3ae, 0x08242768, 0x76910765, 0x59298ee4, 0x279caee9, 0x0f1a7a2f, 0x71af5a22, 0x7560f609, 0x0bd5d604, 0x235302c2, 0x5de622cf, 0x725eab4e, 0x0ceb8b43, 0x246d5f85, 0x5ad87f88, 0x7b1c4c87, 0x05a96c8a, 0x2d2fb84c, 0x539a9841, 0x7c2211c0, 0x029731cd, 0x2a11e50b, 0x54a4c506, 0x69998315, 0x172ca318, 0x3faa77de, 0x411f57d3, 0x6ea7de52, 0x1012fe5f, 0x38942a99, 0x46210a94, 0x67e5399b, 0x19501996, 0x31d6cd50, 0x4f63ed5d, 0x60db64dc, 0x1e6e44d1, 0x36e89017, 0x485db01a, 0x3f77c841, 0x41c2e84c, 0x69443c8a, 0x17f11c87, 0x38499506, 0x46fcb50b, 0x6e7a61cd, 0x10cf41c0, 0x310b72cf, 0x4fbe52c2, 0x67388604, 0x198da609, 0x36352f88, 0x48800f85, 0x6006db43, 0x1eb3fb4e, 0x238ebd5d, 0x5d3b9d50, 0x75bd4996, 0x0b08699b, 0x24b0e01a, 0x5a05c017, 0x728314d1, 0x0c3634dc, 0x2df207d3, 0x534727de, 0x7bc1f318, 0x0574d315, 0x2acc5a94, 0x54797a99, 0x7cffae5f, 0x024a8e52, 0x06852279, 0x78300274, 0x50b6d6b2, 0x2e03f6bf, 0x01bb7f3e, 0x7f0e5f33, 0x57888bf5, 0x293dabf8, 0x08f998f7, 0x764cb8fa, 0x5eca6c3c, 0x207f4c31, 0x0fc7c5b0, 0x7172e5bd, 0x59f4317b, 0x27411176, 0x1a7c5765, 0x64c97768, 0x4c4fa3ae, 0x32fa83a3, 0x1d420a22, 0x63f72a2f, 0x4b71fee9, 0x35c4dee4, 0x1400edeb, 0x6ab5cde6, 0x42331920, 0x3c86392d, 0x133eb0ac, 0x6d8b90a1, 0x450d4467, 0x3bb8646a }; struct index_entry { const unsigned char *ptr; unsigned int val; struct index_entry *next; }; struct git_delta_index { unsigned long memsize; const void *src_buf; size_t src_size; unsigned int hash_mask; struct index_entry *hash[GIT_FLEX_ARRAY]; }; static int lookup_index_alloc( void **out, unsigned long *out_len, size_t entries, size_t hash_count) { size_t entries_len, hash_len, index_len; GITERR_CHECK_ALLOC_MULTIPLY(&entries_len, entries, sizeof(struct index_entry)); GITERR_CHECK_ALLOC_MULTIPLY(&hash_len, hash_count, sizeof(struct index_entry *)); GITERR_CHECK_ALLOC_ADD(&index_len, sizeof(struct git_delta_index), entries_len); GITERR_CHECK_ALLOC_ADD(&index_len, index_len, hash_len); if (!git__is_ulong(index_len)) { giterr_set(GITERR_NOMEMORY, "overly large delta"); return -1; } *out = git__malloc(index_len); GITERR_CHECK_ALLOC(*out); *out_len = index_len; return 0; } int git_delta_index_init( git_delta_index **out, const void *buf, size_t bufsize) { unsigned int i, hsize, hmask, entries, prev_val, *hash_count; const unsigned char *data, *buffer = buf; struct git_delta_index *index; struct index_entry *entry, **hash; void *mem; unsigned long memsize; *out = NULL; if (!buf || !bufsize) return 0; /* Determine index hash size. Note that indexing skips the first byte to allow for optimizing the rabin polynomial initialization in create_delta(). */ entries = (unsigned int)(bufsize - 1) / RABIN_WINDOW; if (bufsize >= 0xffffffffUL) { /* * Current delta format can't encode offsets into * reference buffer with more than 32 bits. */ entries = 0xfffffffeU / RABIN_WINDOW; } hsize = entries / 4; for (i = 4; i < 31 && (1u << i) < hsize; i++); hsize = 1 << i; hmask = hsize - 1; if (lookup_index_alloc(&mem, &memsize, entries, hsize) < 0) return -1; index = mem; mem = index->hash; hash = mem; mem = hash + hsize; entry = mem; index->memsize = memsize; index->src_buf = buf; index->src_size = bufsize; index->hash_mask = hmask; memset(hash, 0, hsize * sizeof(*hash)); /* allocate an array to count hash entries */ hash_count = git__calloc(hsize, sizeof(*hash_count)); if (!hash_count) { git__free(index); return -1; } /* then populate the index */ prev_val = ~0; for (data = buffer + entries * RABIN_WINDOW - RABIN_WINDOW; data >= buffer; data -= RABIN_WINDOW) { unsigned int val = 0; for (i = 1; i <= RABIN_WINDOW; i++) val = ((val << 8) | data[i]) ^ T[val >> RABIN_SHIFT]; if (val == prev_val) { /* keep the lowest of consecutive identical blocks */ entry[-1].ptr = data + RABIN_WINDOW; } else { prev_val = val; i = val & hmask; entry->ptr = data + RABIN_WINDOW; entry->val = val; entry->next = hash[i]; hash[i] = entry++; hash_count[i]++; } } /* * Determine a limit on the number of entries in the same hash * bucket. This guard us against patological data sets causing * really bad hash distribution with most entries in the same hash * bucket that would bring us to O(m*n) computing costs (m and n * corresponding to reference and target buffer sizes). * * Make sure none of the hash buckets has more entries than * we're willing to test. Otherwise we cull the entry list * uniformly to still preserve a good repartition across * the reference buffer. */ for (i = 0; i < hsize; i++) { if (hash_count[i] < HASH_LIMIT) continue; entry = hash[i]; do { struct index_entry *keep = entry; int skip = hash_count[i] / HASH_LIMIT / 2; do { entry = entry->next; } while(--skip && entry); keep->next = entry; } while (entry); } git__free(hash_count); *out = index; return 0; } void git_delta_index_free(git_delta_index *index) { git__free(index); } size_t git_delta_index_size(git_delta_index *index) { assert(index); return index->memsize; } /* * The maximum size for any opcode sequence, including the initial header * plus rabin window plus biggest copy. */ #define MAX_OP_SIZE (5 + 5 + 1 + RABIN_WINDOW + 7) int git_delta_create_from_index( void **out, size_t *out_len, const struct git_delta_index *index, const void *trg_buf, size_t trg_size, size_t max_size) { unsigned int i, bufpos, bufsize, moff, msize, val; int inscnt; const unsigned char *ref_data, *ref_top, *data, *top; unsigned char *buf; *out = NULL; *out_len = 0; if (!trg_buf || !trg_size) return 0; bufpos = 0; bufsize = 8192; if (max_size && bufsize >= max_size) bufsize = (unsigned int)(max_size + MAX_OP_SIZE + 1); buf = git__malloc(bufsize); GITERR_CHECK_ALLOC(buf); /* store reference buffer size */ i = index->src_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; /* store target buffer size */ i = trg_size; while (i >= 0x80) { buf[bufpos++] = i | 0x80; i >>= 7; } buf[bufpos++] = i; ref_data = index->src_buf; ref_top = ref_data + index->src_size; data = trg_buf; top = (const unsigned char *) trg_buf + trg_size; bufpos++; val = 0; for (i = 0; i < RABIN_WINDOW && data < top; i++, data++) { buf[bufpos++] = *data; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; } inscnt = i; moff = 0; msize = 0; while (data < top) { if (msize < 4096) { struct index_entry *entry; val ^= U[data[-RABIN_WINDOW]]; val = ((val << 8) | *data) ^ T[val >> RABIN_SHIFT]; i = val & index->hash_mask; for (entry = index->hash[i]; entry; entry = entry->next) { const unsigned char *ref = entry->ptr; const unsigned char *src = data; unsigned int ref_size = (unsigned int)(ref_top - ref); if (entry->val != val) continue; if (ref_size > (unsigned int)(top - src)) ref_size = (unsigned int)(top - src); if (ref_size <= msize) break; while (ref_size-- && *src++ == *ref) ref++; if (msize < (unsigned int)(ref - entry->ptr)) { /* this is our best match so far */ msize = (unsigned int)(ref - entry->ptr); moff = (unsigned int)(entry->ptr - ref_data); if (msize >= 4096) /* good enough */ break; } } } if (msize < 4) { if (!inscnt) bufpos++; buf[bufpos++] = *data++; inscnt++; if (inscnt == 0x7f) { buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } msize = 0; } else { unsigned int left; unsigned char *op; if (inscnt) { while (moff && ref_data[moff-1] == data[-1]) { /* we can match one byte back */ msize++; moff--; data--; bufpos--; if (--inscnt) continue; bufpos--; /* remove count slot */ inscnt--; /* make it -1 */ break; } buf[bufpos - inscnt - 1] = inscnt; inscnt = 0; } /* A copy op is currently limited to 64KB (pack v2) */ left = (msize < 0x10000) ? 0 : (msize - 0x10000); msize -= left; op = buf + bufpos++; i = 0x80; if (moff & 0x000000ff) buf[bufpos++] = moff >> 0, i |= 0x01; if (moff & 0x0000ff00) buf[bufpos++] = moff >> 8, i |= 0x02; if (moff & 0x00ff0000) buf[bufpos++] = moff >> 16, i |= 0x04; if (moff & 0xff000000) buf[bufpos++] = moff >> 24, i |= 0x08; if (msize & 0x00ff) buf[bufpos++] = msize >> 0, i |= 0x10; if (msize & 0xff00) buf[bufpos++] = msize >> 8, i |= 0x20; *op = i; data += msize; moff += msize; msize = left; if (msize < 4096) { int j; val = 0; for (j = -RABIN_WINDOW; j < 0; j++) val = ((val << 8) | data[j]) ^ T[val >> RABIN_SHIFT]; } } if (bufpos >= bufsize - MAX_OP_SIZE) { void *tmp = buf; bufsize = bufsize * 3 / 2; if (max_size && bufsize >= max_size) bufsize = max_size + MAX_OP_SIZE + 1; if (max_size && bufpos > max_size) break; buf = git__realloc(buf, bufsize); if (!buf) { git__free(tmp); return -1; } } } if (inscnt) buf[bufpos - inscnt - 1] = inscnt; if (max_size && bufpos > max_size) { giterr_set(GITERR_NOMEMORY, "delta would be larger than maximum size"); git__free(buf); return GIT_EBUFS; } *out_len = bufpos; *out = buf; return 0; } /* * Delta application was heavily cribbed from BinaryDelta.java in JGit, which * itself was heavily cribbed from <code>patch-delta.c</code> in the * GIT project. The original delta patching code was written by * Nicolas Pitre <nico@cam.org>. */ static int hdr_sz( size_t *size, const unsigned char **delta, const unsigned char *end) { const unsigned char *d = *delta; size_t r = 0; unsigned int c, shift = 0; do { if (d == end) { giterr_set(GITERR_INVALID, "truncated delta"); return -1; } c = *d++; r |= (c & 0x7f) << shift; shift += 7; } while (c & 0x80); *delta = d; *size = r; return 0; } int git_delta_read_header( size_t *base_out, size_t *result_out, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; if ((hdr_sz(base_out, &delta, delta_end) < 0) || (hdr_sz(result_out, &delta, delta_end) < 0)) return -1; return 0; } #define DELTA_HEADER_BUFFER_LEN 16 int git_delta_read_header_fromstream( size_t *base_sz, size_t *res_sz, git_packfile_stream *stream) { static const size_t buffer_len = DELTA_HEADER_BUFFER_LEN; unsigned char buffer[DELTA_HEADER_BUFFER_LEN]; const unsigned char *delta, *delta_end; size_t len; ssize_t read; len = read = 0; while (len < buffer_len) { read = git_packfile_stream_read(stream, &buffer[len], buffer_len - len); if (read == 0) break; if (read == GIT_EBUFS) continue; len += read; } delta = buffer; delta_end = delta + len; if ((hdr_sz(base_sz, &delta, delta_end) < 0) || (hdr_sz(res_sz, &delta, delta_end) < 0)) return -1; return 0; } int git_delta_apply( void **out, size_t *out_len, const unsigned char *base, size_t base_len, const unsigned char *delta, size_t delta_len) { const unsigned char *delta_end = delta + delta_len; size_t base_sz, res_sz, alloc_sz; unsigned char *res_dp; *out = NULL; *out_len = 0; /* * Check that the base size matches the data we were given; * if not we would underflow while accessing data from the * base object, resulting in data corruption or segfault. */ if ((hdr_sz(&base_sz, &delta, delta_end) < 0) || (base_sz != base_len)) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } if (hdr_sz(&res_sz, &delta, delta_end) < 0) { giterr_set(GITERR_INVALID, "failed to apply delta: base size does not match given data"); return -1; } GITERR_CHECK_ALLOC_ADD(&alloc_sz, res_sz, 1); res_dp = git__malloc(alloc_sz); GITERR_CHECK_ALLOC(res_dp); res_dp[res_sz] = '\0'; *out = res_dp; *out_len = res_sz; while (delta < delta_end) { unsigned char cmd = *delta++; if (cmd & 0x80) { /* cmd is a copy instruction; copy from the base. */ size_t off = 0, len = 0; #define ADD_DELTA(o, shift) { if (delta < delta_end) (o) |= ((unsigned) *delta++ << shift); else goto fail; } if (cmd & 0x01) ADD_DELTA(off, 0UL); if (cmd & 0x02) ADD_DELTA(off, 8UL); if (cmd & 0x04) ADD_DELTA(off, 16UL); if (cmd & 0x08) ADD_DELTA(off, 24UL); if (cmd & 0x10) ADD_DELTA(len, 0UL); if (cmd & 0x20) ADD_DELTA(len, 8UL); if (cmd & 0x40) ADD_DELTA(len, 16UL); if (!len) len = 0x10000; #undef ADD_DELTA if (base_len < off + len || res_sz < len) goto fail; memcpy(res_dp, base + off, len); res_dp += len; res_sz -= len; } else if (cmd) { /* * cmd is a literal insert instruction; copy from * the delta stream itself. */ if (delta_end - delta < cmd || res_sz < cmd) goto fail; memcpy(res_dp, delta, cmd); delta += cmd; res_dp += cmd; res_sz -= cmd; } else { /* cmd == 0 is reserved for future encodings. */ goto fail; } } if (delta != delta_end || res_sz) goto fail; return 0; fail: git__free(*out); *out = NULL; *out_len = 0; giterr_set(GITERR_INVALID, "failed to apply delta"); return -1; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_112_0
crossvul-cpp_data_bad_4850_0
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2002 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * Memory Allocator * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <stddef.h> #include <assert.h> /* We need the prototype for memset. */ #include <string.h> #include "jasper/jas_malloc.h" #include "jasper/jas_debug.h" #include "jasper/jas_math.h" /******************************************************************************\ * Code. \******************************************************************************/ #if defined(JAS_DEFAULT_MAX_MEM_USAGE) static size_t jas_mem = 0; static size_t jas_max_mem = JAS_DEFAULT_MAX_MEM_USAGE; typedef struct { size_t size; } jas_mb_t; #define JAS_MB_ADJUST \ ((sizeof(jas_mb_t) + sizeof(max_align_t) - 1) / sizeof(max_align_t)) #define JAS_MB_SIZE (JAS_MB_ADJUST * sizeof(max_align_t)) jas_mb_t *jas_get_mb(void *ptr) { return JAS_CAST(jas_mb_t *, JAS_CAST(max_align_t *, ptr) - JAS_MB_ADJUST); } void *jas_mb_get_data(jas_mb_t *mb) { return JAS_CAST(void *, JAS_CAST(max_align_t *, mb) + JAS_MB_ADJUST); } void jas_set_max_mem_usage(size_t max_mem) { jas_max_mem = max_mem; } size_t jas_get_mem_usage() { return jas_mem; } void *jas_malloc(size_t size) { void *result; jas_mb_t *mb; size_t ext_size; size_t mem; JAS_DBGLOG(100, ("jas_malloc(%zu)\n", size)); #if defined(JAS_MALLOC_RETURN_NULL_PTR_FOR_ZERO_SIZE) if (!size) { return 0; } #endif if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) { jas_eprintf("requested memory size is too large\n"); result = 0; mb = 0; } else if (!jas_safe_size_add(jas_mem, size, &mem) || mem > jas_max_mem) { jas_eprintf("maximum memory limit would be exceeded\n"); result = 0; mb = 0; } else { JAS_DBGLOG(100, ("jas_malloc: ext_size=%zu\n", ext_size)); if ((mb = malloc(ext_size))) { result = jas_mb_get_data(mb); mb->size = size; jas_mem = mem; } else { result = 0; } } JAS_DBGLOG(99, ("jas_malloc(%zu) -> %p (mb=%p)\n", size, result, mb)); JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem)); return result; } void *jas_realloc(void *ptr, size_t size) { void *result; jas_mb_t *mb; jas_mb_t *old_mb; size_t old_size; size_t ext_size; size_t mem; JAS_DBGLOG(100, ("jas_realloc(%x, %zu)\n", ptr, size)); if (!ptr) { return jas_malloc(size); } if (ptr && !size) { jas_free(ptr); } if (!jas_safe_size_add(size, JAS_MB_SIZE, &ext_size)) { jas_eprintf("requested memory size is too large\n"); return 0; } old_mb = jas_get_mb(ptr); old_size = old_mb->size; JAS_DBGLOG(101, ("jas_realloc: old_mb=%x; old_size=%zu\n", old_mb, old_size)); if (size > old_size) { if (!jas_safe_size_add(jas_mem, ext_size, &mem) || mem > jas_max_mem) { jas_eprintf("maximum memory limit would be exceeded\n"); return 0; } } else { if (!jas_safe_size_sub(jas_mem, old_size - size, &jas_mem)) { jas_eprintf("heap corruption detected\n"); abort(); } } JAS_DBGLOG(100, ("jas_realloc: realloc(%p, %zu)\n", old_mb, ext_size)); if (!(mb = realloc(old_mb, ext_size))) { result = 0; } else { result = jas_mb_get_data(mb); mb->size = size; jas_mem = mem; } JAS_DBGLOG(100, ("jas_realloc(%p, %zu) -> %p (%p)\n", ptr, size, result, mb)); JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem)); return result; } void jas_free(void *ptr) { jas_mb_t *mb; size_t mem; size_t size; JAS_DBGLOG(100, ("jas_free(%p)\n", ptr)); if (ptr) { mb = jas_get_mb(ptr); size = mb->size; JAS_DBGLOG(101, ("jas_free(%p) (mb=%p; size=%zu)\n", ptr, mb, size)); if (!jas_safe_size_sub(jas_mem, size, &jas_mem)) { jas_eprintf("heap corruption detected\n"); abort(); } JAS_DBGLOG(100, ("jas_free: free(%p)\n", mb)); free(mb); } JAS_DBGLOG(102, ("max_mem=%zu; mem=%zu\n", jas_max_mem, jas_mem)); } #endif /******************************************************************************\ * Basic memory allocation and deallocation primitives. \******************************************************************************/ #if !defined(JAS_DEFAULT_MAX_MEM_USAGE) void *jas_malloc(size_t size) { void *result; JAS_DBGLOG(101, ("jas_malloc called with %zu\n", size)); result = malloc(size); JAS_DBGLOG(100, ("jas_malloc(%zu) -> %p\n", size, result)); return result; } void *jas_realloc(void *ptr, size_t size) { void *result; JAS_DBGLOG(101, ("jas_realloc called with %x,%zu\n", ptr, size)); result = realloc(ptr, size); JAS_DBGLOG(100, ("jas_realloc(%p, %zu) -> %p\n", ptr, size, result)); return result; } void jas_free(void *ptr) { JAS_DBGLOG(100, ("jas_free(%p)\n", ptr)); free(ptr); } #endif /******************************************************************************\ * Additional memory allocation and deallocation primitives * (mainly for overflow checking). \******************************************************************************/ void *jas_alloc2(size_t num_elements, size_t element_size) { size_t size; if (!jas_safe_size_mul(num_elements, element_size, &size)) { return 0; } return jas_malloc(size); } void *jas_alloc3(size_t num_arrays, size_t array_size, size_t element_size) { size_t size; if (!jas_safe_size_mul(array_size, element_size, &size) || !jas_safe_size_mul(size, num_arrays, &size)) { return 0; } return jas_malloc(size); } void *jas_realloc2(void *ptr, size_t num_elements, size_t element_size) { size_t size; if (!jas_safe_size_mul(num_elements, element_size, &size)) { return 0; } return jas_realloc(ptr, size); } void *jas_calloc(size_t num_elements, size_t element_size) { void *ptr; size_t size; if (!jas_safe_size_mul(num_elements, element_size, &size)) { return 0; } if (!(ptr = jas_malloc(size))) { return 0; } memset(ptr, 0, size); return ptr; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_4850_0
crossvul-cpp_data_bad_1834_2
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V EEEEE RRRR SSSSS IIIII OOO N N % % V V E R R SS I O O NN N % % V V EEE RRRR SSS I O O N N N % % V V E R R SS I O O N NN % % V EEEEE R R SSSSS IIIII OOO N N % % % % % % MagickCore Version and Copyright Methods % % % % Software Design % % Cristy % % September 2002 % % % % % % Copyright 1999-2015 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % http://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ #include "MagickCore/studio.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/hashmap.h" #include "MagickCore/locale_.h" #include "MagickCore/option.h" #include "MagickCore/string_.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" #include "MagickCore/version-private.h" /* Define declarations. */ #define MagickURLFilename "index.html" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k C o p y r i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickCopyright() returns the ImageMagick API copyright as a string. % % The format of the GetMagickCopyright method is: % % const char *GetMagickCopyright(void) % */ MagickExport const char *GetMagickCopyright(void) { return(MagickCopyright); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k D e l e g a t e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickDelegates() returns the ImageMagick delegate libraries. % % The format of the GetMagickDelegates method is: % % const char *GetMagickDelegates(void) % % No parameters are required. % */ MagickExport const char *GetMagickDelegates(void) { return "" #if defined(MAGICKCORE_AUTOTRACE_DELEGATE) "autotrace " #endif #if defined(MAGICKCORE_BZLIB_DELEGATE) "bzlib " #endif #if defined(MAGICKCORE_CAIRO_DELEGATE) "cairo " #endif #if defined(MAGICKCORE_DJVU_DELEGATE) "djvu " #endif #if defined(MAGICKCORE_DPS_DELEGATE) "dps " #endif #if defined(MAGICKCORE_EMF_DELEGATE) "emf " #endif #if defined(MAGICKCORE_FFTW_DELEGATE) "fftw " #endif #if defined(MAGICKCORE_FONTCONFIG_DELEGATE) "fontconfig " #endif #if defined(MAGICKCORE_FREETYPE_DELEGATE) "freetype " #endif #if defined(MAGICKCORE_FPX_DELEGATE) "fpx " #endif #if defined(MAGICKCORE_GS_DELEGATE) "gslib " #endif #if defined(MAGICKCORE_GVC_DELEGATE) "gvc " #endif #if defined(MAGICKCORE_JBIG_DELEGATE) "jbig " #endif #if defined(MAGICKCORE_JPEG_DELEGATE) && defined(MAGICKCORE_PNG_DELEGATE) "jng " #endif #if defined(MAGICKCORE_LIBOPENJP2_DELEGATE) "jp2 " #endif #if defined(MAGICKCORE_JPEG_DELEGATE) "jpeg " #endif #if defined(MAGICKCORE_LCMS_DELEGATE) "lcms " #endif #if defined(MAGICKCORE_LQR_DELEGATE) "lqr " #endif #if defined(MAGICKCORE_LTDL_DELEGATE) "ltdl " #endif #if defined(MAGICKCORE_LZMA_DELEGATE) "lzma " #endif #if defined(MAGICKCORE_OPENEXR_DELEGATE) "openexr " #endif #if defined(MAGICKCORE_PANGOCAIRO_DELEGATE) "pangocairo " #endif #if defined(MAGICKCORE_PNG_DELEGATE) "png " #endif #if defined(MAGICKCORE_DPS_DELEGATE) || defined(MAGICKCORE_GS_DELEGATE) || defined(WIN32) "ps " #endif #if defined(MAGICKCORE_RSVG_DELEGATE) "rsvg " #endif #if defined(MAGICKCORE_TIFF_DELEGATE) "tiff " #endif #if defined(MAGICKCORE_WEBP_DELEGATE) "webp " #endif #if defined(MAGICKCORE_WMF_DELEGATE) || defined (MAGICKCORE_WMFLITE_DELEGATE) "wmf " #endif #if defined(MAGICKCORE_X11_DELEGATE) "x " #endif #if defined(MAGICKCORE_XML_DELEGATE) "xml " #endif #if defined(MAGICKCORE_ZLIB_DELEGATE) "zlib" #endif ; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k F e a t u r e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickFeatures() returns the ImageMagick features. % % The format of the GetMagickFeatures method is: % % const char *GetMagickFeatures(void) % % No parameters are required. % */ MagickExport const char *GetMagickFeatures(void) { return "DPC" #if defined(MAGICKCORE_BUILD_MODULES) || defined(_DLL) " Modules" #endif #if defined(MAGICKCORE_HDRI_SUPPORT) " HDRI" #endif #if defined(MAGICKCORE_OPENCL_SUPPORT) " OpenCL" #endif #if defined(MAGICKCORE_OPENMP_SUPPORT) " OpenMP" #endif ; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k H o m e U R L % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickHomeURL() returns the ImageMagick home URL. % % The format of the GetMagickHomeURL method is: % % char *GetMagickHomeURL(void) % */ MagickExport char *GetMagickHomeURL(void) { char path[MagickPathExtent]; const char *element; ExceptionInfo *exception; LinkedListInfo *paths; exception=AcquireExceptionInfo(); paths=GetConfigurePaths(MagickURLFilename,exception); exception=DestroyExceptionInfo(exception); if (paths == (LinkedListInfo *) NULL) return(ConstantString(MagickHomeURL)); element=(const char *) GetNextValueInLinkedList(paths); while (element != (const char *) NULL) { (void) FormatLocaleString(path,MagickPathExtent,"%s%s%s",element, DirectorySeparator,MagickURLFilename); if (IsPathAccessible(path) != MagickFalse) return(ConstantString(path)); element=(const char *) GetNextValueInLinkedList(paths); } return(ConstantString(MagickHomeURL)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k L i c e n s e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickLicense() returns the ImageMagick API license as a string. % % The format of the GetMagickLicense method is: % % const char *GetMagickLicense(void) % */ MagickExport const char *GetMagickLicense(void) { return(MagickAuthoritativeLicense); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k P a c k a g e N a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickPackageName() returns the ImageMagick package name. % % The format of the GetMagickName method is: % % const char *GetMagickName(void) % % No parameters are required. % */ MagickExport const char *GetMagickPackageName(void) { return(MagickPackageName); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k Q u a n t u m D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickQuantumDepth() returns the ImageMagick quantum depth. % % The format of the GetMagickQuantumDepth method is: % % const char *GetMagickQuantumDepth(size_t *depth) % % A description of each parameter follows: % % o depth: the quantum depth is returned as a number. % */ MagickExport const char *GetMagickQuantumDepth(size_t *depth) { if (depth != (size_t *) NULL) *depth=(size_t) MAGICKCORE_QUANTUM_DEPTH; return(MagickQuantumDepth); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k Q u a n t u m R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickQuantumRange() returns the ImageMagick quantum range. % % The format of the GetMagickQuantumRange method is: % % const char *GetMagickQuantumRange(size_t *range) % % A description of each parameter follows: % % o range: the quantum range is returned as a number. % */ MagickExport const char *GetMagickQuantumRange(size_t *range) { if (range != (size_t *) NULL) *range=(size_t) QuantumRange; return(MagickQuantumRange); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k R e l e a s e D a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickReleaseDate() returns the ImageMagick release date. % % The format of the GetMagickReleaseDate method is: % % const char *GetMagickReleaseDate(void) % % No parameters are required. % */ MagickExport const char *GetMagickReleaseDate(void) { return(MagickReleaseDate); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k S i g n a t u r e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickSignature() returns a signature that uniquely encodes the % MagickCore libary version, quantum depth, HDRI status, OS word size, and % endianness. % % The format of the GetMagickSignature method is: % % unsigned int GetMagickSignature(const StringInfo *nonce) % % A description of each parameter follows: % % o nonce: arbitrary data. % */ static unsigned int CRC32(const unsigned char *message,const size_t length) { register ssize_t i; static MagickBooleanType crc_initial = MagickFalse; static unsigned int crc_xor[256]; unsigned int crc; /* Generate a 32-bit cyclic redundancy check for the message. */ if (crc_initial == MagickFalse) { register unsigned int i; unsigned int alpha; for (i=0; i < 256; i++) { register ssize_t j; alpha=i; for (j=0; j < 8; j++) alpha=(alpha & 0x01) ? (0xEDB88320 ^ (alpha >> 1)) : (alpha >> 1); crc_xor[i]=alpha; } crc_initial=MagickTrue; } crc=0xFFFFFFFF; for (i=0; i < (ssize_t) length; i++) crc=crc_xor[(crc ^ message[i]) & 0xff] ^ (crc >> 8); return(crc ^ 0xFFFFFFFF); } MagickExport unsigned int GetMagickSignature(const StringInfo *nonce) { register unsigned char *p; StringInfo *version; unsigned int signature; version=AcquireStringInfo(MagickPathExtent); p=GetStringInfoDatum(version); signature=MAGICKCORE_QUANTUM_DEPTH; (void) memcpy(p,&signature,sizeof(signature)); p+=sizeof(signature); signature=MAGICKCORE_HDRI_ENABLE; (void) memcpy(p,&signature,sizeof(signature)); p+=sizeof(signature); signature=MagickLibInterface; (void) memcpy(p,&signature,sizeof(signature)); p+=sizeof(signature); signature=1; /* endianess */ (void) memcpy(p,&signature,sizeof(signature)); p+=sizeof(signature); SetStringInfoLength(version,p-GetStringInfoDatum(version)); if (nonce != (const StringInfo *) NULL) ConcatenateStringInfo(version,nonce); signature=CRC32(GetStringInfoDatum(version),GetStringInfoLength(version)); version=DestroyStringInfo(version); return(signature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t M a g i c k V e r s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetMagickVersion() returns the ImageMagick API version as a string and % as a number. % % The format of the GetMagickVersion method is: % % const char *GetMagickVersion(size_t *version) % % A description of each parameter follows: % % o version: the ImageMagick version is returned as a number. % */ MagickExport const char *GetMagickVersion(size_t *version) { if (version != (size_t *) NULL) *version=MagickLibVersion; return(MagickVersion); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t M a g i c k V e r s i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListMagickVersion() identifies the ImageMagick version by printing its % attributes to the file. Attributes include the copyright, features, and % delegates. % % The format of the ListMagickVersion method is: % % void ListMagickVersion(FILE *file) % % A description of each parameter follows: % % o file: the file, typically stdout. % */ MagickExport void ListMagickVersion(FILE *file) { (void) FormatLocaleFile(file,"Version: %s\n", GetMagickVersion((size_t *) NULL)); (void) FormatLocaleFile(file,"Copyright: %s\n",GetMagickCopyright()); (void) FormatLocaleFile(file,"License: %s\n",GetMagickLicense()); (void) FormatLocaleFile(file,"Features: %s\n",GetMagickFeatures()); (void) FormatLocaleFile(file,"Delegates (built-in): %s\n\n", GetMagickDelegates()); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_1834_2
crossvul-cpp_data_good_5170_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Marcus Boerger <helly@php.net> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "ext/standard/file.h" #include "ext/standard/php_string.h" #include "zend_compile.h" #include "zend_exceptions.h" #include "zend_interfaces.h" #include "php_spl.h" #include "spl_functions.h" #include "spl_engine.h" #include "spl_iterators.h" #include "spl_directory.h" #include "spl_exceptions.h" #include "php.h" #include "fopen_wrappers.h" #include "ext/standard/basic_functions.h" #include "ext/standard/php_filestat.h" #define SPL_HAS_FLAG(flags, test_flag) ((flags & test_flag) ? 1 : 0) /* declare the class handlers */ static zend_object_handlers spl_filesystem_object_handlers; /* includes handler to validate object state when retrieving methods */ static zend_object_handlers spl_filesystem_object_check_handlers; /* decalre the class entry */ PHPAPI zend_class_entry *spl_ce_SplFileInfo; PHPAPI zend_class_entry *spl_ce_DirectoryIterator; PHPAPI zend_class_entry *spl_ce_FilesystemIterator; PHPAPI zend_class_entry *spl_ce_RecursiveDirectoryIterator; PHPAPI zend_class_entry *spl_ce_GlobIterator; PHPAPI zend_class_entry *spl_ce_SplFileObject; PHPAPI zend_class_entry *spl_ce_SplTempFileObject; static void spl_filesystem_file_free_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { efree(intern->u.file.current_line); intern->u.file.current_line = NULL; } if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); intern->u.file.current_zval = NULL; } } /* }}} */ static void spl_filesystem_object_free_storage(void *object TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)object; if (intern->oth_handler && intern->oth_handler->dtor) { intern->oth_handler->dtor(intern TSRMLS_CC); } zend_object_std_dtor(&intern->std TSRMLS_CC); if (intern->_path) { efree(intern->_path); } if (intern->file_name) { efree(intern->file_name); } switch(intern->type) { case SPL_FS_INFO: break; case SPL_FS_DIR: if (intern->u.dir.dirp) { php_stream_close(intern->u.dir.dirp); intern->u.dir.dirp = NULL; } if (intern->u.dir.sub_path) { efree(intern->u.dir.sub_path); } break; case SPL_FS_FILE: if (intern->u.file.stream) { if (intern->u.file.zcontext) { /* zend_list_delref(Z_RESVAL_P(intern->zcontext));*/ } if (!intern->u.file.stream->is_persistent) { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE); } else { php_stream_free(intern->u.file.stream, PHP_STREAM_FREE_CLOSE_PERSISTENT); } if (intern->u.file.open_mode) { efree(intern->u.file.open_mode); } if (intern->orig_path) { efree(intern->orig_path); } } spl_filesystem_file_free_line(intern TSRMLS_CC); break; } { zend_object_iterator *iterator; iterator = (zend_object_iterator*) spl_filesystem_object_to_iterator(intern); if (iterator->data != NULL) { iterator->data = NULL; iterator->funcs->dtor(iterator TSRMLS_CC); } } efree(object); } /* }}} */ /* {{{ spl_ce_dir_object_new */ /* creates the object by - allocating memory - initializing the object members - storing the object - setting it's handlers called from - clone - new */ static zend_object_value spl_filesystem_object_new_ex(zend_class_entry *class_type, spl_filesystem_object **obj TSRMLS_DC) { zend_object_value retval; spl_filesystem_object *intern; intern = emalloc(sizeof(spl_filesystem_object)); memset(intern, 0, sizeof(spl_filesystem_object)); /* intern->type = SPL_FS_INFO; done by set 0 */ intern->file_class = spl_ce_SplFileObject; intern->info_class = spl_ce_SplFileInfo; if (obj) *obj = intern; zend_object_std_init(&intern->std, class_type TSRMLS_CC); object_properties_init(&intern->std, class_type); retval.handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t) zend_objects_destroy_object, (zend_objects_free_object_storage_t) spl_filesystem_object_free_storage, NULL TSRMLS_CC); retval.handlers = &spl_filesystem_object_handlers; return retval; } /* }}} */ /* {{{ spl_filesystem_object_new */ /* See spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new(zend_class_entry *class_type TSRMLS_DC) { return spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_object_new_ex */ static zend_object_value spl_filesystem_object_new_check(zend_class_entry *class_type TSRMLS_DC) { zend_object_value ret = spl_filesystem_object_new_ex(class_type, NULL TSRMLS_CC); ret.handlers = &spl_filesystem_object_check_handlers; return ret; } /* }}} */ PHPAPI char* spl_filesystem_object_get_path(spl_filesystem_object *intern, int *len TSRMLS_DC) /* {{{ */ { #ifdef HAVE_GLOB if (intern->type == SPL_FS_DIR) { if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { return php_glob_stream_get_path(intern->u.dir.dirp, 0, len); } } #endif if (len) { *len = intern->_path_len; } return intern->_path; } /* }}} */ static inline void spl_filesystem_object_get_file_name(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (!intern->file_name) { php_error_docref(NULL TSRMLS_CC, E_ERROR, "Object not initialized"); } break; case SPL_FS_DIR: if (intern->file_name) { efree(intern->file_name); } intern->file_name_len = spprintf(&intern->file_name, 0, "%s%c%s", spl_filesystem_object_get_path(intern, NULL TSRMLS_CC), slash, intern->u.dir.entry.d_name); break; } } /* }}} */ static int spl_filesystem_dir_read(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (!intern->u.dir.dirp || !php_stream_readdir(intern->u.dir.dirp, &intern->u.dir.entry)) { intern->u.dir.entry.d_name[0] = '\0'; return 0; } else { return 1; } } /* }}} */ #define IS_SLASH_AT(zs, pos) (IS_SLASH(zs[pos])) static inline int spl_filesystem_is_dot(const char * d_name) /* {{{ */ { return !strcmp(d_name, ".") || !strcmp(d_name, ".."); } /* }}} */ /* {{{ spl_filesystem_dir_open */ /* open a directory resource */ static void spl_filesystem_dir_open(spl_filesystem_object* intern, char *path TSRMLS_DC) { int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); intern->type = SPL_FS_DIR; intern->_path_len = strlen(path); intern->u.dir.dirp = php_stream_opendir(path, REPORT_ERRORS, FG(default_context)); if (intern->_path_len > 1 && IS_SLASH_AT(path, intern->_path_len-1)) { intern->_path = estrndup(path, --intern->_path_len); } else { intern->_path = estrndup(path, intern->_path_len); } intern->u.dir.index = 0; if (EG(exception) || intern->u.dir.dirp == NULL) { intern->u.dir.entry.d_name[0] = '\0'; if (!EG(exception)) { /* open failed w/out notice (turned to exception due to EH_THROW) */ zend_throw_exception_ex(spl_ce_UnexpectedValueException, 0 TSRMLS_CC, "Failed to open directory \"%s\"", path); } } else { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } } /* }}} */ static int spl_filesystem_file_open(spl_filesystem_object *intern, int use_include_path, int silent TSRMLS_DC) /* {{{ */ { zval tmp; intern->type = SPL_FS_FILE; php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, &tmp TSRMLS_CC); if (Z_LVAL(tmp)) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Cannot use SplFileObject with directories"); return FAILURE; } intern->u.file.context = php_stream_context_from_zval(intern->u.file.zcontext, 0); intern->u.file.stream = php_stream_open_wrapper_ex(intern->file_name, intern->u.file.open_mode, (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, intern->u.file.context); if (!intern->file_name_len || !intern->u.file.stream) { if (!EG(exception)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot open file '%s'", intern->file_name_len ? intern->file_name : ""); } intern->file_name = NULL; /* until here it is not a copy */ intern->u.file.open_mode = NULL; return FAILURE; } if (intern->u.file.zcontext) { zend_list_addref(Z_RESVAL_P(intern->u.file.zcontext)); } if (intern->file_name_len > 1 && IS_SLASH_AT(intern->file_name, intern->file_name_len-1)) { intern->file_name_len--; } intern->orig_path = estrndup(intern->u.file.stream->orig_path, strlen(intern->u.file.stream->orig_path)); intern->file_name = estrndup(intern->file_name, intern->file_name_len); intern->u.file.open_mode = estrndup(intern->u.file.open_mode, intern->u.file.open_mode_len); /* avoid reference counting in debug mode, thus do it manually */ ZVAL_RESOURCE(&intern->u.file.zresource, php_stream_get_resource_id(intern->u.file.stream)); Z_SET_REFCOUNT(intern->u.file.zresource, 1); intern->u.file.delimiter = ','; intern->u.file.enclosure = '"'; intern->u.file.escape = '\\'; zend_hash_find(&intern->std.ce->function_table, "getcurrentline", sizeof("getcurrentline"), (void **) &intern->u.file.func_getCurr); return SUCCESS; } /* }}} */ /* {{{ spl_filesystem_object_clone */ /* Local zend_object_value creation (on stack) Load the 'other' object Create a new empty object (See spl_filesystem_object_new_ex) Open the directory Clone other members (properties) */ static zend_object_value spl_filesystem_object_clone(zval *zobject TSRMLS_DC) { zend_object_value new_obj_val; zend_object *old_object; zend_object *new_object; zend_object_handle handle = Z_OBJ_HANDLE_P(zobject); spl_filesystem_object *intern; spl_filesystem_object *source; int index, skip_dots; old_object = zend_objects_get_address(zobject TSRMLS_CC); source = (spl_filesystem_object*)old_object; new_obj_val = spl_filesystem_object_new_ex(old_object->ce, &intern TSRMLS_CC); new_object = &intern->std; intern->flags = source->flags; switch (source->type) { case SPL_FS_INFO: intern->_path_len = source->_path_len; intern->_path = estrndup(source->_path, source->_path_len); intern->file_name_len = source->file_name_len; intern->file_name = estrndup(source->file_name, intern->file_name_len); break; case SPL_FS_DIR: spl_filesystem_dir_open(intern, source->_path TSRMLS_CC); /* read until we hit the position in which we were before */ skip_dots = SPL_HAS_FLAG(source->flags, SPL_FILE_DIR_SKIPDOTS); for(index = 0; index < source->u.dir.index; ++index) { do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } intern->u.dir.index = index; break; case SPL_FS_FILE: php_error_docref(NULL TSRMLS_CC, E_ERROR, "An object of class %s cannot be cloned", old_object->ce->name); break; } intern->file_class = source->file_class; intern->info_class = source->info_class; intern->oth = source->oth; intern->oth_handler = source->oth_handler; zend_objects_clone_members(new_object, new_obj_val, old_object, handle TSRMLS_CC); if (intern->oth_handler && intern->oth_handler->clone) { intern->oth_handler->clone(source, intern TSRMLS_CC); } return new_obj_val; } /* }}} */ void spl_filesystem_info_set_filename(spl_filesystem_object *intern, char *path, int len, int use_copy TSRMLS_DC) /* {{{ */ { char *p1, *p2; if (intern->file_name) { efree(intern->file_name); } intern->file_name = use_copy ? estrndup(path, len) : path; intern->file_name_len = len; while(IS_SLASH_AT(intern->file_name, intern->file_name_len-1) && intern->file_name_len > 1) { intern->file_name[intern->file_name_len-1] = 0; intern->file_name_len--; } p1 = strrchr(intern->file_name, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(intern->file_name, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - intern->file_name; } else { intern->_path_len = 0; } if (intern->_path) { efree(intern->_path); } intern->_path = estrndup(path, intern->_path_len); } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_info(spl_filesystem_object *source, char *file_path, int file_path_len, int use_copy, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zval *arg1; zend_error_handling error_handling; if (!file_path || !file_path_len) { #if defined(PHP_WIN32) zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot create SplFileInfo for empty path"); if (file_path && !use_copy) { efree(file_path); } #else if (file_path && !use_copy) { efree(file_path); } file_path_len = 1; file_path = "/"; #endif return NULL; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, file_path, file_path_len, use_copy); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { spl_filesystem_info_set_filename(intern, file_path, file_path_len, use_copy TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); return intern; } /* }}} */ static spl_filesystem_object * spl_filesystem_object_create_type(int ht, spl_filesystem_object *source, int type, zend_class_entry *ce, zval *return_value TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern; zend_bool use_include_path = 0; zval *arg1, *arg2; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); switch (source->type) { case SPL_FS_INFO: case SPL_FS_FILE: break; case SPL_FS_DIR: if (!source->u.dir.entry.d_name[0]) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Could not open file"); zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } } switch (type) { case SPL_FS_INFO: ce = ce ? ce : source->info_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileInfo) { MAKE_STD_ZVAL(arg1); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1); zval_ptr_dtor(&arg1); } else { intern->file_name = estrndup(source->file_name, source->file_name_len); intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); } break; case SPL_FS_FILE: ce = ce ? ce : source->file_class; zend_update_class_constants(ce TSRMLS_CC); return_value->value.obj = spl_filesystem_object_new_ex(ce, &intern TSRMLS_CC); Z_TYPE_P(return_value) = IS_OBJECT; spl_filesystem_object_get_file_name(source TSRMLS_CC); if (ce->constructor->common.scope != spl_ce_SplFileObject) { MAKE_STD_ZVAL(arg1); MAKE_STD_ZVAL(arg2); ZVAL_STRINGL(arg1, source->file_name, source->file_name_len, 1); ZVAL_STRINGL(arg2, "r", 1, 1); zend_call_method_with_2_params(&return_value, ce, &ce->constructor, "__construct", NULL, arg1, arg2); zval_ptr_dtor(&arg1); zval_ptr_dtor(&arg2); } else { intern->file_name = source->file_name; intern->file_name_len = source->file_name_len; intern->_path = spl_filesystem_object_get_path(source, &intern->_path_len TSRMLS_CC); intern->_path = estrndup(intern->_path, intern->_path_len); intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; if (ht && zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sbr", &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->file_name = NULL; zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); zval_dtor(return_value); Z_TYPE_P(return_value) = IS_NULL; return NULL; } } break; case SPL_FS_DIR: zend_restore_error_handling(&error_handling TSRMLS_CC); zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Operation not supported"); return NULL; } zend_restore_error_handling(&error_handling TSRMLS_CC); return NULL; } /* }}} */ static int spl_filesystem_is_invalid_or_dot(const char * d_name) /* {{{ */ { return d_name[0] == '\0' || spl_filesystem_is_dot(d_name); } /* }}} */ static char *spl_filesystem_object_get_pathname(spl_filesystem_object *intern, int *len TSRMLS_DC) { /* {{{ */ switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: *len = intern->file_name_len; return intern->file_name; case SPL_FS_DIR: if (intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); *len = intern->file_name_len; return intern->file_name; } } *len = 0; return NULL; } /* }}} */ static HashTable* spl_filesystem_object_get_debug_info(zval *obj, int *is_temp TSRMLS_DC) /* {{{ */ { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(obj TSRMLS_CC); HashTable *rv; zval *tmp, zrv; char *pnstr, *path; int pnlen, path_len; char stmp[2]; *is_temp = 1; if (!intern->std.properties) { rebuild_object_properties(&intern->std); } ALLOC_HASHTABLE(rv); ZEND_INIT_SYMTABLE_EX(rv, zend_hash_num_elements(intern->std.properties) + 3, 0); INIT_PZVAL(&zrv); Z_ARRVAL(zrv) = rv; zend_hash_copy(rv, intern->std.properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *)); pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "pathName", sizeof("pathName")-1, &pnlen TSRMLS_CC); path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, path, path_len, 1); efree(pnstr); if (intern->file_name) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileInfo, "fileName", sizeof("fileName")-1, &pnlen TSRMLS_CC); spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->file_name, intern->file_name_len, 1); } efree(pnstr); } if (intern->type == SPL_FS_DIR) { #ifdef HAVE_GLOB pnstr = spl_gen_private_prop_name(spl_ce_DirectoryIterator, "glob", sizeof("glob")-1, &pnlen TSRMLS_CC); if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->_path, intern->_path_len, 1); } else { add_assoc_bool_ex(&zrv, pnstr, pnlen+1, 0); } efree(pnstr); #endif pnstr = spl_gen_private_prop_name(spl_ce_RecursiveDirectoryIterator, "subPathName", sizeof("subPathName")-1, &pnlen TSRMLS_CC); if (intern->u.dir.sub_path) { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, "", 0, 1); } efree(pnstr); } if (intern->type == SPL_FS_FILE) { pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "openMode", sizeof("openMode")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, intern->u.file.open_mode, intern->u.file.open_mode_len, 1); efree(pnstr); stmp[1] = '\0'; stmp[0] = intern->u.file.delimiter; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "delimiter", sizeof("delimiter")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); stmp[0] = intern->u.file.enclosure; pnstr = spl_gen_private_prop_name(spl_ce_SplFileObject, "enclosure", sizeof("enclosure")-1, &pnlen TSRMLS_CC); add_assoc_stringl_ex(&zrv, pnstr, pnlen+1, stmp, 1, 1); efree(pnstr); } return rv; } /* }}} */ zend_function *spl_filesystem_object_get_method_check(zval **object_ptr, char *method, int method_len, const struct _zend_literal *key TSRMLS_DC) /* {{{ */ { spl_filesystem_object *fsobj = zend_object_store_get_object(*object_ptr TSRMLS_CC); if (fsobj->u.dir.entry.d_name[0] == '\0' && fsobj->orig_path == NULL) { method = "_bad_state_ex"; method_len = sizeof("_bad_state_ex") - 1; key = NULL; } return zend_get_std_object_handlers()->get_method(object_ptr, method, method_len, key TSRMLS_CC); } /* }}} */ #define DIT_CTOR_FLAGS 0x00000001 #define DIT_CTOR_GLOB 0x00000002 void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed, len; long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Directory name must not be empty."); zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (intern->_path) { /* object is alreay initialized */ zend_restore_error_handling(&error_handling TSRMLS_CC); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Directory object is already initialized"); return; } intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path TSRMLS_CC); efree(path); } else #endif { spl_filesystem_dir_open(intern, path TSRMLS_CC); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator TSRMLS_CC) ? 1 : 0; zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void DirectoryIterator::__construct(string path) Cronstructs a new dir iterator from a path. */ SPL_METHOD(DirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::rewind() Rewind dir back to the start */ SPL_METHOD(DirectoryIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } spl_filesystem_dir_read(intern TSRMLS_CC); } /* }}} */ /* {{{ proto string DirectoryIterator::key() Return current dir entry */ SPL_METHOD(DirectoryIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.dirp) { RETURN_LONG(intern->u.dir.index); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto DirectoryIterator DirectoryIterator::current() Return this (needed for Iterator interface) */ SPL_METHOD(DirectoryIterator, current) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_ZVAL(getThis(), 1, 0); } /* }}} */ /* {{{ proto void DirectoryIterator::next() Move to next entry */ SPL_METHOD(DirectoryIterator, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index++; do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); if (intern->file_name) { efree(intern->file_name); intern->file_name = NULL; } } /* }}} */ /* {{{ proto void DirectoryIterator::seek(int position) Seek to the given position */ SPL_METHOD(DirectoryIterator, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *retval = NULL; long pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &pos) == FAILURE) { return; } if (intern->u.dir.index > pos) { /* we first rewind */ zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_rewind, "rewind", &retval); if (retval) { zval_ptr_dtor(&retval); retval = NULL; } } while (intern->u.dir.index < pos) { int valid = 0; zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_valid, "valid", &retval); if (retval) { valid = zend_is_true(retval); zval_ptr_dtor(&retval); retval = NULL; } if (!valid) { break; } zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.dir.func_next, "next", &retval); if (retval) { zval_ptr_dtor(&retval); } } } /* }}} */ /* {{{ proto string DirectoryIterator::valid() Check whether dir contains more entries */ SPL_METHOD(DirectoryIterator, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(intern->u.dir.entry.d_name[0] != '\0'); } /* }}} */ /* {{{ proto string SplFileInfo::getPath() Return the path */ SPL_METHOD(SplFileInfo, getPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); RETURN_STRINGL(path, path_len, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getFilename() Return filename only */ SPL_METHOD(SplFileInfo, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { RETURN_STRINGL(intern->file_name + path_len + 1, intern->file_name_len - (path_len + 1), 1); } else { RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string DirectoryIterator::getFilename() Return filename of current dir entry */ SPL_METHOD(DirectoryIterator, getFilename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_STRING(intern->u.dir.entry.d_name, 1); } /* }}} */ /* {{{ proto string SplFileInfo::getExtension() Returns file extension component of path */ SPL_METHOD(SplFileInfo, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int path_len, idx; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}}*/ /* {{{ proto string DirectoryIterator::getExtension() Returns the file extension component of path */ SPL_METHOD(DirectoryIterator, getExtension) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname = NULL; const char *p; size_t flen; int idx; if (zend_parse_parameters_none() == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), NULL, 0, &fname, &flen TSRMLS_CC); p = zend_memrchr(fname, '.', flen); if (p) { idx = p - fname; RETVAL_STRINGL(fname + idx + 1, flen - idx - 1, 1); efree(fname); return; } else { if (fname) { efree(fname); } RETURN_EMPTY_STRING(); } } /* }}} */ /* {{{ proto string SplFileInfo::getBasename([string $suffix]) U Returns filename component of path */ SPL_METHOD(SplFileInfo, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *fname, *suffix = 0; size_t flen; int slen = 0, path_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } spl_filesystem_object_get_path(intern, &path_len TSRMLS_CC); if (path_len && path_len < intern->file_name_len) { fname = intern->file_name + path_len + 1; flen = intern->file_name_len - (path_len + 1); } else { fname = intern->file_name; flen = intern->file_name_len; } php_basename(fname, flen, suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}}*/ /* {{{ proto string DirectoryIterator::getBasename([string $suffix]) U Returns filename component of current dir entry */ SPL_METHOD(DirectoryIterator, getBasename) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *suffix = 0, *fname; int slen = 0; size_t flen; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &suffix, &slen) == FAILURE) { return; } php_basename(intern->u.dir.entry.d_name, strlen(intern->u.dir.entry.d_name), suffix, slen, &fname, &flen TSRMLS_CC); RETURN_STRINGL(fname, flen, 0); } /* }}} */ /* {{{ proto string SplFileInfo::getPathname() Return path and filename */ SPL_METHOD(SplFileInfo, getPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *path; int path_len; if (zend_parse_parameters_none() == FAILURE) { return; } path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path != NULL) { RETURN_STRINGL(path, path_len, 1); } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto string FilesystemIterator::key() Return getPathname() or getFilename() depending on flags */ SPL_METHOD(FilesystemIterator, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_KEY(intern, SPL_FILE_DIR_KEY_AS_FILENAME)) { RETURN_STRING(intern->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } } /* }}} */ /* {{{ proto string FilesystemIterator::current() Return getFilename(), getFileInfo() or $this depending on flags */ SPL_METHOD(FilesystemIterator, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); RETURN_STRINGL(intern->file_name, intern->file_name_len, 1); } else if (SPL_FILE_DIR_CURRENT(intern, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); spl_filesystem_object_create_type(0, intern, SPL_FS_INFO, NULL, return_value TSRMLS_CC); } else { RETURN_ZVAL(getThis(), 1, 0); /*RETURN_STRING(intern->u.dir.entry.d_name, 1);*/ } } /* }}} */ /* {{{ proto bool DirectoryIterator::isDot() Returns true if current entry is '.' or '..' */ SPL_METHOD(DirectoryIterator, isDot) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto void SplFileInfo::__construct(string file_name) Cronstructs a new SplFileInfo from a path. */ /* zend_replace_error_handling() is used to throw exceptions in case the constructor fails. Here we use this to ensure the object has a valid directory resource. When the constructor gets called the object is already created by the engine, so we must only call 'additional' initializations. */ SPL_METHOD(SplFileInfo, __construct) { spl_filesystem_object *intern; char *path; int len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &path, &len) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_info_set_filename(intern, path, len, 1 TSRMLS_CC); zend_restore_error_handling(&error_handling TSRMLS_CC); /* intern->type = SPL_FS_INFO; already set */ } /* }}} */ /* {{{ FileInfoFunction */ #define FileInfoFunction(func_name, func_num) \ SPL_METHOD(SplFileInfo, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ zend_error_handling error_handling; \ if (zend_parse_parameters_none() == FAILURE) { \ return; \ } \ \ zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC);\ spl_filesystem_object_get_file_name(intern TSRMLS_CC); \ php_stat(intern->file_name, intern->file_name_len, func_num, return_value TSRMLS_CC); \ zend_restore_error_handling(&error_handling TSRMLS_CC); \ } /* }}} */ /* {{{ proto int SplFileInfo::getPerms() Get file permissions */ FileInfoFunction(getPerms, FS_PERMS) /* }}} */ /* {{{ proto int SplFileInfo::getInode() Get file inode */ FileInfoFunction(getInode, FS_INODE) /* }}} */ /* {{{ proto int SplFileInfo::getSize() Get file size */ FileInfoFunction(getSize, FS_SIZE) /* }}} */ /* {{{ proto int SplFileInfo::getOwner() Get file owner */ FileInfoFunction(getOwner, FS_OWNER) /* }}} */ /* {{{ proto int SplFileInfo::getGroup() Get file group */ FileInfoFunction(getGroup, FS_GROUP) /* }}} */ /* {{{ proto int SplFileInfo::getATime() Get last access time of file */ FileInfoFunction(getATime, FS_ATIME) /* }}} */ /* {{{ proto int SplFileInfo::getMTime() Get last modification time of file */ FileInfoFunction(getMTime, FS_MTIME) /* }}} */ /* {{{ proto int SplFileInfo::getCTime() Get inode modification time of file */ FileInfoFunction(getCTime, FS_CTIME) /* }}} */ /* {{{ proto string SplFileInfo::getType() Get file type */ FileInfoFunction(getType, FS_TYPE) /* }}} */ /* {{{ proto bool SplFileInfo::isWritable() Returns true if file can be written */ FileInfoFunction(isWritable, FS_IS_W) /* }}} */ /* {{{ proto bool SplFileInfo::isReadable() Returns true if file can be read */ FileInfoFunction(isReadable, FS_IS_R) /* }}} */ /* {{{ proto bool SplFileInfo::isExecutable() Returns true if file is executable */ FileInfoFunction(isExecutable, FS_IS_X) /* }}} */ /* {{{ proto bool SplFileInfo::isFile() Returns true if file is a regular file */ FileInfoFunction(isFile, FS_IS_FILE) /* }}} */ /* {{{ proto bool SplFileInfo::isDir() Returns true if file is directory */ FileInfoFunction(isDir, FS_IS_DIR) /* }}} */ /* {{{ proto bool SplFileInfo::isLink() Returns true if file is symbolic link */ FileInfoFunction(isLink, FS_IS_LINK) /* }}} */ /* {{{ proto string SplFileInfo::getLinkTarget() U Return the target of a symbolic link */ SPL_METHOD(SplFileInfo, getLinkTarget) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int ret; char buff[MAXPATHLEN]; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); #if defined(PHP_WIN32) || HAVE_SYMLINK if (intern->file_name == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Empty filename"); RETURN_FALSE; } else if (!IS_ABSOLUTE_PATH(intern->file_name, intern->file_name_len)) { char expanded_path[MAXPATHLEN]; if (!expand_filepath_with_mode(intern->file_name, expanded_path, NULL, 0, CWD_EXPAND TSRMLS_CC)) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such file or directory"); RETURN_FALSE; } ret = php_sys_readlink(expanded_path, buff, MAXPATHLEN - 1); } else { ret = php_sys_readlink(intern->file_name, buff, MAXPATHLEN-1); } #else ret = -1; /* always fail if not implemented */ #endif if (ret == -1) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Unable to read link %s, error: %s", intern->file_name, strerror(errno)); RETVAL_FALSE; } else { /* Append NULL to the end of the string */ buff[ret] = '\0'; RETVAL_STRINGL(buff, ret, 1); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) /* {{{ proto string SplFileInfo::getRealPath() Return the resolved path */ SPL_METHOD(SplFileInfo, getRealPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buff[MAXPATHLEN]; char *filename; zend_error_handling error_handling; if (zend_parse_parameters_none() == FAILURE) { return; } zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (intern->type == SPL_FS_DIR && !intern->file_name && intern->u.dir.entry.d_name[0]) { spl_filesystem_object_get_file_name(intern TSRMLS_CC); } if (intern->orig_path) { filename = intern->orig_path; } else { filename = intern->file_name; } if (filename && VCWD_REALPATH(filename, buff)) { #ifdef ZTS if (VCWD_ACCESS(buff, F_OK)) { RETVAL_FALSE; } else #endif RETVAL_STRING(buff, 1); } else { RETVAL_FALSE; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ #endif /* {{{ proto SplFileObject SplFileInfo::openFile([string mode = 'r' [, bool use_include_path [, resource context]]]) Open the current file */ SPL_METHOD(SplFileInfo, openFile) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object_create_type(ht, intern, SPL_FS_FILE, NULL, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setFileClass([string class_name]) Class to use in openFile() */ SPL_METHOD(SplFileInfo, setFileClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileObject; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->file_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileInfo::setInfoClass([string class_name]) Class to use in getFileInfo(), getPathInfo() */ SPL_METHOD(SplFileInfo, setInfoClass) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = spl_ce_SplFileInfo; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { intern->info_class = ce; } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getFileInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getFileInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { spl_filesystem_object_create_type(ht, intern, SPL_FS_INFO, ce, return_value TSRMLS_CC); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto SplFileInfo SplFileInfo::getPathInfo([string $class_name]) Get/copy file info */ SPL_METHOD(SplFileInfo, getPathInfo) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_class_entry *ce = intern->info_class; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|C", &ce) == SUCCESS) { int path_len; char *path = spl_filesystem_object_get_pathname(intern, &path_len TSRMLS_CC); if (path) { char *dpath = estrndup(path, path_len); path_len = php_dirname(dpath, path_len); spl_filesystem_object_create_info(intern, dpath, path_len, 1, ce, return_value TSRMLS_CC); efree(dpath); } } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ */ SPL_METHOD(SplFileInfo, _bad_state_ex) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "The parent constructor was not called: the object is in an " "invalid state "); } /* }}} */ /* {{{ proto void FilesystemIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(FilesystemIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS | SPL_FILE_DIR_SKIPDOTS); } /* }}} */ /* {{{ proto void FilesystemIterator::rewind() Rewind dir back to the start */ SPL_METHOD(FilesystemIterator, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); int skip_dots = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_SKIPDOTS); if (zend_parse_parameters_none() == FAILURE) { return; } intern->u.dir.index = 0; if (intern->u.dir.dirp) { php_stream_rewinddir(intern->u.dir.dirp); } do { spl_filesystem_dir_read(intern TSRMLS_CC); } while (skip_dots && spl_filesystem_is_dot(intern->u.dir.entry.d_name)); } /* }}} */ /* {{{ proto int FilesystemIterator::getFlags() Get handling flags */ SPL_METHOD(FilesystemIterator, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & (SPL_FILE_DIR_KEY_MODE_MASK | SPL_FILE_DIR_CURRENT_MODE_MASK | SPL_FILE_DIR_OTHERS_MASK)); } /* }}} */ /* {{{ proto void FilesystemIterator::setFlags(long $flags) Set handling flags */ SPL_METHOD(FilesystemIterator, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long flags; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &flags) == FAILURE) { return; } intern->flags &= ~(SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK); intern->flags |= ((SPL_FILE_DIR_KEY_MODE_MASK|SPL_FILE_DIR_CURRENT_MODE_MASK|SPL_FILE_DIR_OTHERS_MASK) & flags); } /* }}} */ /* {{{ proto bool RecursiveDirectoryIterator::hasChildren([bool $allow_links = false]) Returns whether current entry is a directory and not '.' or '..' */ SPL_METHOD(RecursiveDirectoryIterator, hasChildren) { zend_bool allow_links = 0; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &allow_links) == FAILURE) { return; } if (spl_filesystem_is_invalid_or_dot(intern->u.dir.entry.d_name)) { RETURN_FALSE; } else { spl_filesystem_object_get_file_name(intern TSRMLS_CC); if (!allow_links && !(intern->flags & SPL_FILE_DIR_FOLLOW_SYMLINKS)) { php_stat(intern->file_name, intern->file_name_len, FS_IS_LINK, return_value TSRMLS_CC); if (zend_is_true(return_value)) { RETURN_FALSE; } } php_stat(intern->file_name, intern->file_name_len, FS_IS_DIR, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto RecursiveDirectoryIterator DirectoryIterator::getChildren() Returns an iterator for the current entry if it is a directory */ SPL_METHOD(RecursiveDirectoryIterator, getChildren) { zval *zpath, *zflags; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_object *subdir; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_object_get_file_name(intern TSRMLS_CC); MAKE_STD_ZVAL(zflags); MAKE_STD_ZVAL(zpath); ZVAL_LONG(zflags, intern->flags); ZVAL_STRINGL(zpath, intern->file_name, intern->file_name_len, 1); spl_instantiate_arg_ex2(Z_OBJCE_P(getThis()), &return_value, 0, zpath, zflags TSRMLS_CC); zval_ptr_dtor(&zpath); zval_ptr_dtor(&zflags); subdir = (spl_filesystem_object*)zend_object_store_get_object(return_value TSRMLS_CC); if (subdir) { if (intern->u.dir.sub_path && intern->u.dir.sub_path[0]) { subdir->u.dir.sub_path_len = spprintf(&subdir->u.dir.sub_path, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); } else { subdir->u.dir.sub_path_len = strlen(intern->u.dir.entry.d_name); subdir->u.dir.sub_path = estrndup(intern->u.dir.entry.d_name, subdir->u.dir.sub_path_len); } subdir->info_class = intern->info_class; subdir->file_class = intern->file_class; subdir->oth = intern->oth; } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPath() Get sub path */ SPL_METHOD(RecursiveDirectoryIterator, getSubPath) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { RETURN_STRINGL(intern->u.dir.sub_path, intern->u.dir.sub_path_len, 1); } else { RETURN_STRINGL("", 0, 1); } } /* }}} */ /* {{{ proto void RecursiveDirectoryIterator::getSubPathname() Get sub path and file name */ SPL_METHOD(RecursiveDirectoryIterator, getSubPathname) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *sub_name; int len; char slash = SPL_HAS_FLAG(intern->flags, SPL_FILE_DIR_UNIXPATHS) ? '/' : DEFAULT_SLASH; if (zend_parse_parameters_none() == FAILURE) { return; } if (intern->u.dir.sub_path) { len = spprintf(&sub_name, 0, "%s%c%s", intern->u.dir.sub_path, slash, intern->u.dir.entry.d_name); RETURN_STRINGL(sub_name, len, 0); } else { RETURN_STRING(intern->u.dir.entry.d_name, 1); } } /* }}} */ /* {{{ proto int RecursiveDirectoryIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a path. */ SPL_METHOD(RecursiveDirectoryIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS); } /* }}} */ #ifdef HAVE_GLOB /* {{{ proto int GlobIterator::__construct(string path [, int flags]) Cronstructs a new dir iterator from a glob expression (no glob:// needed). */ SPL_METHOD(GlobIterator, __construct) { spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAM_PASSTHRU, DIT_CTOR_FLAGS|DIT_CTOR_GLOB); } /* }}} */ /* {{{ proto int GlobIterator::cont() Return the number of directories and files found by globbing */ SPL_METHOD(GlobIterator, count) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (php_stream_is(intern->u.dir.dirp ,&php_glob_stream_ops)) { RETURN_LONG(php_glob_stream_get_count(intern->u.dir.dirp, NULL)); } else { /* should not happen */ php_error_docref(NULL TSRMLS_CC, E_ERROR, "GlobIterator lost glob state"); } } /* }}} */ #endif /* HAVE_GLOB */ /* {{{ forward declarations to the iterator handlers */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC); static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC); static void spl_filesystem_dir_it_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC); static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC); static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC); /* iterator handler table */ zend_object_iterator_funcs spl_filesystem_dir_it_funcs = { spl_filesystem_dir_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_dir_it_current_data, spl_filesystem_dir_it_current_key, spl_filesystem_dir_it_move_forward, spl_filesystem_dir_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_dir_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if it wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_dir_it_funcs; /* ->current must be initialized; rewind doesn't set it and valid * doesn't check whether it's set */ iterator->current = object; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_dir_it_dtor */ static void spl_filesystem_dir_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; if (iterator->intern.data) { zval *object = iterator->intern.data; zval_ptr_dtor(&object); } /* Otherwise we were called from the owning object free storage handler as * it sets * iterator->intern.data to NULL. * We don't even need to destroy iterator->current as we didn't add a * reference to it in move_forward or get_iterator */ } /* }}} */ /* {{{ spl_filesystem_dir_it_valid */ static int spl_filesystem_dir_it_valid(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); return object->u.dir.entry.d_name[0] != '\0' ? SUCCESS : FAILURE; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_data */ static void spl_filesystem_dir_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; *data = &iterator->current; } /* }}} */ /* {{{ spl_filesystem_dir_it_current_key */ static void spl_filesystem_dir_it_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); ZVAL_LONG(key, object->u.dir.index); } /* }}} */ /* {{{ spl_filesystem_dir_it_move_forward */ static void spl_filesystem_dir_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index++; spl_filesystem_dir_read(object TSRMLS_CC); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } } /* }}} */ /* {{{ spl_filesystem_dir_it_rewind */ static void spl_filesystem_dir_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } spl_filesystem_dir_read(object TSRMLS_CC); } /* }}} */ /* {{{ spl_filesystem_tree_it_dtor */ static void spl_filesystem_tree_it_dtor(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; if (iterator->intern.data) { zval *object = iterator->intern.data; zval_ptr_dtor(&object); } else { if (iterator->current) { zval_ptr_dtor(&iterator->current); } } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_data */ static void spl_filesystem_tree_it_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_PATHNAME)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(iterator->current, object->file_name, object->file_name_len, 1); } *data = &iterator->current; } else if (SPL_FILE_DIR_CURRENT(object, SPL_FILE_DIR_CURRENT_AS_FILEINFO)) { if (!iterator->current) { ALLOC_INIT_ZVAL(iterator->current); spl_filesystem_object_get_file_name(object TSRMLS_CC); spl_filesystem_object_create_type(0, object, SPL_FS_INFO, NULL, iterator->current TSRMLS_CC); } *data = &iterator->current; } else { *data = (zval**)&iterator->intern.data; } } /* }}} */ /* {{{ spl_filesystem_tree_it_current_key */ static void spl_filesystem_tree_it_current_key(zend_object_iterator *iter, zval *key TSRMLS_DC) { spl_filesystem_object *object = spl_filesystem_iterator_to_object((spl_filesystem_iterator *)iter); if (SPL_FILE_DIR_KEY(object, SPL_FILE_DIR_KEY_AS_FILENAME)) { ZVAL_STRING(key, object->u.dir.entry.d_name, 1); } else { spl_filesystem_object_get_file_name(object TSRMLS_CC); ZVAL_STRINGL(key, object->file_name, object->file_name_len, 1); } } /* }}} */ /* {{{ spl_filesystem_tree_it_move_forward */ static void spl_filesystem_tree_it_move_forward(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index++; do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (object->file_name) { efree(object->file_name); object->file_name = NULL; } if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ spl_filesystem_tree_it_rewind */ static void spl_filesystem_tree_it_rewind(zend_object_iterator *iter TSRMLS_DC) { spl_filesystem_iterator *iterator = (spl_filesystem_iterator *)iter; spl_filesystem_object *object = spl_filesystem_iterator_to_object(iterator); object->u.dir.index = 0; if (object->u.dir.dirp) { php_stream_rewinddir(object->u.dir.dirp); } do { spl_filesystem_dir_read(object TSRMLS_CC); } while (spl_filesystem_is_dot(object->u.dir.entry.d_name)); if (iterator->current) { zval_ptr_dtor(&iterator->current); iterator->current = NULL; } } /* }}} */ /* {{{ iterator handler table */ zend_object_iterator_funcs spl_filesystem_tree_it_funcs = { spl_filesystem_tree_it_dtor, spl_filesystem_dir_it_valid, spl_filesystem_tree_it_current_data, spl_filesystem_tree_it_current_key, spl_filesystem_tree_it_move_forward, spl_filesystem_tree_it_rewind }; /* }}} */ /* {{{ spl_ce_dir_get_iterator */ zend_object_iterator *spl_filesystem_tree_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC) { spl_filesystem_iterator *iterator; spl_filesystem_object *dir_object; if (by_ref) { zend_error(E_ERROR, "An iterator cannot be used with foreach by reference"); } dir_object = (spl_filesystem_object*)zend_object_store_get_object(object TSRMLS_CC); iterator = spl_filesystem_object_to_iterator(dir_object); /* initialize iterator if wasn't gotten before */ if (iterator->intern.data == NULL) { iterator->intern.data = object; iterator->intern.funcs = &spl_filesystem_tree_it_funcs; } zval_add_ref(&object); return (zend_object_iterator*)iterator; } /* }}} */ /* {{{ spl_filesystem_object_cast */ static int spl_filesystem_object_cast(zval *readobj, zval *writeobj, int type TSRMLS_DC) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(readobj TSRMLS_CC); if (type == IS_STRING) { if (Z_OBJCE_P(readobj)->__tostring) { return std_object_handlers.cast_object(readobj, writeobj, type TSRMLS_CC); } switch (intern->type) { case SPL_FS_INFO: case SPL_FS_FILE: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRINGL(retval_ptr, intern->file_name, intern->file_name_len, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRINGL(writeobj, intern->file_name, intern->file_name_len, 1); } return SUCCESS; case SPL_FS_DIR: if (readobj == writeobj) { zval retval; zval *retval_ptr = &retval; ZVAL_STRING(retval_ptr, intern->u.dir.entry.d_name, 1); zval_dtor(readobj); ZVAL_ZVAL(writeobj, retval_ptr, 0, 0); } else { ZVAL_STRING(writeobj, intern->u.dir.entry.d_name, 1); } return SUCCESS; } } else if (type == IS_BOOL) { ZVAL_BOOL(writeobj, 1); return SUCCESS; } if (readobj == writeobj) { zval_dtor(readobj); } ZVAL_NULL(writeobj); return FAILURE; } /* }}} */ /* {{{ declare method parameters */ /* supply a name and default to call by parameter */ ZEND_BEGIN_ARG_INFO(arginfo_info___construct, 0) ZEND_ARG_INFO(0, file_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_openFile, 0, 0, 0) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_info_optinalFileClass, 0, 0, 0) ZEND_ARG_INFO(0, class_name) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_optinalSuffix, 0, 0, 0) ZEND_ARG_INFO(0, suffix) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_splfileinfo_void, 0) ZEND_END_ARG_INFO() /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_SplFileInfo_functions[] = { SPL_ME(SplFileInfo, __construct, arginfo_info___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPerms, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getInode, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getSize, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getOwner, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getGroup, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getATime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getMTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getCTime, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getType, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isWritable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isReadable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isExecutable, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isFile, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isDir, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, isLink, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getLinkTarget, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #if (!defined(__BEOS__) && !defined(NETWARE) && HAVE_REALPATH) || defined(ZTS) SPL_ME(SplFileInfo, getRealPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) #endif SPL_ME(SplFileInfo, getFileInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, getPathInfo, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, openFile, arginfo_info_openFile, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setFileClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, setInfoClass, arginfo_info_optinalFileClass, ZEND_ACC_PUBLIC) SPL_ME(SplFileInfo, _bad_state_ex, NULL, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL) SPL_MA(SplFileInfo, __toString, SplFileInfo, getPathname, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO(arginfo_dir___construct, 0) ZEND_ARG_INFO(0, path) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_dir_it_seek, 0) ZEND_ARG_INFO(0, position) ZEND_END_ARG_INFO(); /* the method table */ /* each method can have its own parameters and visibility */ static const zend_function_entry spl_DirectoryIterator_functions[] = { SPL_ME(DirectoryIterator, __construct, arginfo_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getExtension, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, getBasename, arginfo_optinalSuffix, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, isDot, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, seek, arginfo_dir_it_seek, ZEND_ACC_PUBLIC) SPL_MA(DirectoryIterator, __toString, DirectoryIterator, getFilename, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir___construct, 0, 0, 1) ZEND_ARG_INFO(0, path) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_hasChildren, 0, 0, 0) ZEND_ARG_INFO(0, allow_links) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_r_dir_setFlags, 0, 0, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() static const zend_function_entry spl_FilesystemIterator_functions[] = { SPL_ME(FilesystemIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(DirectoryIterator, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(FilesystemIterator, setFlags, arginfo_r_dir_setFlags, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry spl_RecursiveDirectoryIterator_functions[] = { SPL_ME(RecursiveDirectoryIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, hasChildren, arginfo_r_dir_hasChildren, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPath, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(RecursiveDirectoryIterator, getSubPathname,arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #ifdef HAVE_GLOB static const zend_function_entry spl_GlobIterator_functions[] = { SPL_ME(GlobIterator, __construct, arginfo_r_dir___construct, ZEND_ACC_PUBLIC) SPL_ME(GlobIterator, count, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; #endif /* }}} */ static int spl_filesystem_file_read(spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { char *buf; size_t line_len = 0; long line_add = (intern->u.file.current_line || intern->u.file.current_zval) ? 1 : 0; spl_filesystem_file_free_line(intern TSRMLS_CC); if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (intern->u.file.max_line_len > 0) { buf = safe_emalloc((intern->u.file.max_line_len + 1), sizeof(char), 0); if (php_stream_get_line(intern->u.file.stream, buf, intern->u.file.max_line_len + 1, &line_len) == NULL) { efree(buf); buf = NULL; } else { buf[line_len] = '\0'; } } else { buf = php_stream_get_line(intern->u.file.stream, NULL, 0, &line_len); } if (!buf) { intern->u.file.current_line = estrdup(""); intern->u.file.current_line_len = 0; } else { if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_DROP_NEW_LINE)) { line_len = strcspn(buf, "\r\n"); buf[line_len] = '\0'; } intern->u.file.current_line = buf; intern->u.file.current_line_len = line_len; } intern->u.file.current_line_num += line_add; return SUCCESS; } /* }}} */ static int spl_filesystem_file_call(spl_filesystem_object *intern, zend_function *func_ptr, int pass_num_args, zval *return_value, zval *arg2 TSRMLS_DC) /* {{{ */ { zend_fcall_info fci; zend_fcall_info_cache fcic; zval z_fname; zval * zresource_ptr = &intern->u.file.zresource, *retval; int result; int num_args = pass_num_args + (arg2 ? 2 : 1); zval ***params = (zval***)safe_emalloc(num_args, sizeof(zval**), 0); params[0] = &zresource_ptr; if (arg2) { params[1] = &arg2; } zend_get_parameters_array_ex(pass_num_args, params+(arg2 ? 2 : 1)); ZVAL_STRING(&z_fname, func_ptr->common.function_name, 0); fci.size = sizeof(fci); fci.function_table = EG(function_table); fci.object_ptr = NULL; fci.function_name = &z_fname; fci.retval_ptr_ptr = &retval; fci.param_count = num_args; fci.params = params; fci.no_separation = 1; fci.symbol_table = NULL; fcic.initialized = 1; fcic.function_handler = func_ptr; fcic.calling_scope = NULL; fcic.called_scope = NULL; fcic.object_ptr = NULL; result = zend_call_function(&fci, &fcic TSRMLS_CC); if (result == FAILURE) { RETVAL_FALSE; } else { ZVAL_ZVAL(return_value, retval, 1, 1); } efree(params); return result; } /* }}} */ #define FileFunctionCall(func_name, pass_num_args, arg2) /* {{{ */ \ { \ zend_function *func_ptr; \ int ret; \ ret = zend_hash_find(EG(function_table), #func_name, sizeof(#func_name), (void **) &func_ptr); \ if (ret != SUCCESS) { \ zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Internal error, function '%s' not found. Please report", #func_name); \ return; \ } \ spl_filesystem_file_call(intern, func_ptr, pass_num_args, return_value, arg2 TSRMLS_CC); \ } /* }}} */ static int spl_filesystem_file_read_csv(spl_filesystem_object *intern, char delimiter, char enclosure, char escape, zval *return_value TSRMLS_DC) /* {{{ */ { int ret = SUCCESS; do { ret = spl_filesystem_file_read(intern, 1 TSRMLS_CC); } while (ret == SUCCESS && !intern->u.file.current_line_len && SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY)); if (ret == SUCCESS) { size_t buf_len = intern->u.file.current_line_len; char *buf = estrndup(intern->u.file.current_line, buf_len); if (intern->u.file.current_zval) { zval_ptr_dtor(&intern->u.file.current_zval); } ALLOC_INIT_ZVAL(intern->u.file.current_zval); php_fgetcsv(intern->u.file.stream, delimiter, enclosure, escape, buf_len, buf, intern->u.file.current_zval TSRMLS_CC); if (return_value) { if (Z_TYPE_P(return_value) != IS_NULL) { zval_dtor(return_value); ZVAL_NULL(return_value); } ZVAL_ZVAL(return_value, intern->u.file.current_zval, 1, 0); } } return ret; } /* }}} */ static int spl_filesystem_file_read_line_ex(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { zval *retval = NULL; /* 1) use fgetcsv? 2) overloaded call the function, 3) do it directly */ if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || intern->u.file.func_getCurr->common.scope != spl_ce_SplFileObject) { if (php_stream_eof(intern->u.file.stream)) { if (!silent) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot read from file %s", intern->file_name); } return FAILURE; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV)) { return spl_filesystem_file_read_csv(intern, intern->u.file.delimiter, intern->u.file.enclosure, intern->u.file.escape, NULL TSRMLS_CC); } else { zend_call_method_with_0_params(&this_ptr, Z_OBJCE_P(getThis()), &intern->u.file.func_getCurr, "getCurrentLine", &retval); } if (retval) { if (intern->u.file.current_line || intern->u.file.current_zval) { intern->u.file.current_line_num++; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (Z_TYPE_P(retval) == IS_STRING) { intern->u.file.current_line = estrndup(Z_STRVAL_P(retval), Z_STRLEN_P(retval)); intern->u.file.current_line_len = Z_STRLEN_P(retval); } else { MAKE_STD_ZVAL(intern->u.file.current_zval); ZVAL_ZVAL(intern->u.file.current_zval, retval, 1, 0); } zval_ptr_dtor(&retval); return SUCCESS; } else { return FAILURE; } } else { return spl_filesystem_file_read(intern, silent TSRMLS_CC); } } /* }}} */ static int spl_filesystem_file_is_empty_line(spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (intern->u.file.current_line) { return intern->u.file.current_line_len == 0; } else if (intern->u.file.current_zval) { switch(Z_TYPE_P(intern->u.file.current_zval)) { case IS_STRING: return Z_STRLEN_P(intern->u.file.current_zval) == 0; case IS_ARRAY: if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) && zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 1) { zval ** first = Z_ARRVAL_P(intern->u.file.current_zval)->pListHead->pData; return Z_TYPE_PP(first) == IS_STRING && Z_STRLEN_PP(first) == 0; } return zend_hash_num_elements(Z_ARRVAL_P(intern->u.file.current_zval)) == 0; case IS_NULL: return 1; default: return 0; } } else { return 1; } } /* }}} */ static int spl_filesystem_file_read_line(zval * this_ptr, spl_filesystem_object *intern, int silent TSRMLS_DC) /* {{{ */ { int ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); while (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_SKIP_EMPTY) && ret == SUCCESS && spl_filesystem_file_is_empty_line(intern TSRMLS_CC)) { spl_filesystem_file_free_line(intern TSRMLS_CC); ret = spl_filesystem_file_read_line_ex(this_ptr, intern, silent TSRMLS_CC); } return ret; } /* }}} */ static void spl_filesystem_file_rewind(zval * this_ptr, spl_filesystem_object *intern TSRMLS_DC) /* {{{ */ { if (-1 == php_stream_rewind(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_RuntimeException, 0 TSRMLS_CC, "Cannot rewind file %s", intern->file_name); } else { spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num = 0; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(this_ptr, intern, 1 TSRMLS_CC); } } /* }}} */ /* {{{ proto void SplFileObject::__construct(string filename [, string mode = 'r' [, bool use_include_path [, resource context]]]]) Construct a new file object */ SPL_METHOD(SplFileObject, __construct) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_bool use_include_path = 0; char *p1, *p2; char *tmp_path; int tmp_path_len; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); intern->u.file.open_mode = NULL; intern->u.file.open_mode_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "p|sbr!", &intern->file_name, &intern->file_name_len, &intern->u.file.open_mode, &intern->u.file.open_mode_len, &use_include_path, &intern->u.file.zcontext) == FAILURE) { intern->u.file.open_mode = NULL; intern->file_name = NULL; zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (intern->u.file.open_mode == NULL) { intern->u.file.open_mode = "r"; intern->u.file.open_mode_len = 1; } if (spl_filesystem_file_open(intern, use_include_path, 0 TSRMLS_CC) == SUCCESS) { tmp_path_len = strlen(intern->u.file.stream->orig_path); if (tmp_path_len > 1 && IS_SLASH_AT(intern->u.file.stream->orig_path, tmp_path_len-1)) { tmp_path_len--; } tmp_path = estrndup(intern->u.file.stream->orig_path, tmp_path_len); p1 = strrchr(tmp_path, '/'); #if defined(PHP_WIN32) || defined(NETWARE) p2 = strrchr(tmp_path, '\\'); #else p2 = 0; #endif if (p1 || p2) { intern->_path_len = (p1 > p2 ? p1 : p2) - tmp_path; } else { intern->_path_len = 0; } efree(tmp_path); intern->_path = estrndup(intern->u.file.stream->orig_path, intern->_path_len); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplTempFileObject::__construct([int max_memory]) Construct a new temp file object */ SPL_METHOD(SplTempFileObject, __construct) { long max_memory = PHP_STREAM_MAX_MEM; char tmp_fname[48]; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_RuntimeException, &error_handling TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|l", &max_memory) == FAILURE) { zend_restore_error_handling(&error_handling TSRMLS_CC); return; } if (max_memory < 0) { intern->file_name = "php://memory"; intern->file_name_len = 12; } else if (ZEND_NUM_ARGS()) { intern->file_name_len = slprintf(tmp_fname, sizeof(tmp_fname), "php://temp/maxmemory:%ld", max_memory); intern->file_name = tmp_fname; } else { intern->file_name = "php://temp"; intern->file_name_len = 10; } intern->u.file.open_mode = "wb"; intern->u.file.open_mode_len = 1; intern->u.file.zcontext = NULL; if (spl_filesystem_file_open(intern, 0, 0 TSRMLS_CC) == SUCCESS) { intern->_path_len = 0; intern->_path = estrndup("", 0); } zend_restore_error_handling(&error_handling TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::rewind() Rewind the file and read the first line */ SPL_METHOD(SplFileObject, rewind) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); } /* }}} */ /* {{{ proto void SplFileObject::eof() Return whether end of file is reached */ SPL_METHOD(SplFileObject, eof) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_BOOL(php_stream_eof(intern->u.file.stream)); } /* }}} */ /* {{{ proto void SplFileObject::valid() Return !eof() */ SPL_METHOD(SplFileObject, valid) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { RETURN_BOOL(intern->u.file.current_line || intern->u.file.current_zval); } else { RETVAL_BOOL(!php_stream_eof(intern->u.file.stream)); } } /* }}} */ /* {{{ proto string SplFileObject::fgets() Rturn next line from file */ SPL_METHOD(SplFileObject, fgets) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (spl_filesystem_file_read(intern, 0 TSRMLS_CC) == FAILURE) { RETURN_FALSE; } RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } /* }}} */ /* {{{ proto string SplFileObject::current() Return current line from file */ SPL_METHOD(SplFileObject, current) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } if (!intern->u.file.current_line && !intern->u.file.current_zval) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } if (intern->u.file.current_line && (!SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_CSV) || !intern->u.file.current_zval)) { RETURN_STRINGL(intern->u.file.current_line, intern->u.file.current_line_len, 1); } else if (intern->u.file.current_zval) { RETURN_ZVAL(intern->u.file.current_zval, 1, 0); } RETURN_FALSE; } /* }}} */ /* {{{ proto int SplFileObject::key() Return line number */ SPL_METHOD(SplFileObject, key) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } /* Do not read the next line to support correct counting with fgetc() if (!intern->current_line) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } */ RETURN_LONG(intern->u.file.current_line_num); } /* }}} */ /* {{{ proto void SplFileObject::next() Read next line */ SPL_METHOD(SplFileObject, next) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) { spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC); } intern->u.file.current_line_num++; } /* }}} */ /* {{{ proto void SplFileObject::setFlags(int flags) Set file handling flags */ SPL_METHOD(SplFileObject, setFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &intern->flags) == FAILURE) { return; } } /* }}} */ /* {{{ proto int SplFileObject::getFlags() Get file handling flags */ SPL_METHOD(SplFileObject, getFlags) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG(intern->flags & SPL_FILE_OBJECT_MASK); } /* }}} */ /* {{{ proto void SplFileObject::setMaxLineLen(int max_len) Set maximum line length */ SPL_METHOD(SplFileObject, setMaxLineLen) { long max_len; spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &max_len) == FAILURE) { return; } if (max_len < 0) { zend_throw_exception_ex(spl_ce_DomainException, 0 TSRMLS_CC, "Maximum line length must be greater than or equal zero"); return; } intern->u.file.max_line_len = max_len; } /* }}} */ /* {{{ proto int SplFileObject::getMaxLineLen() Get maximum line length */ SPL_METHOD(SplFileObject, getMaxLineLen) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_LONG((long)intern->u.file.max_line_len); } /* }}} */ /* {{{ proto bool SplFileObject::hasChildren() Return false */ SPL_METHOD(SplFileObject, hasChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } RETURN_FALSE; } /* }}} */ /* {{{ proto bool SplFileObject::getChildren() Read NULL */ SPL_METHOD(SplFileObject, getChildren) { if (zend_parse_parameters_none() == FAILURE) { return; } /* return NULL */ } /* }}} */ /* {{{ FileFunction */ #define FileFunction(func_name) \ SPL_METHOD(SplFileObject, func_name) \ { \ spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); \ FileFunctionCall(func_name, ZEND_NUM_ARGS(), NULL); \ } /* }}} */ /* {{{ proto array SplFileObject::fgetcsv([string delimiter [, string enclosure [, escape = '\\']]]) Return current line as csv */ SPL_METHOD(SplFileObject, fgetcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } spl_filesystem_file_read_csv(intern, delimiter, enclosure, escape, return_value TSRMLS_CC); } } /* }}} */ /* {{{ proto int SplFileObject::fputcsv(array fields, [string delimiter [, string enclosure [, string escape]]]) Output a field array as a CSV line */ SPL_METHOD(SplFileObject, fputcsv) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = intern->u.file.delimiter, enclosure = intern->u.file.enclosure, escape = intern->u.file.escape; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0, ret; zval *fields = NULL; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a|sss", &fields, &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 4: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 3: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 2: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 1: case 0: break; } ret = php_fputcsv(intern->u.file.stream, fields, delimiter, enclosure, escape TSRMLS_CC); RETURN_LONG(ret); } } /* }}} */ /* {{{ proto void SplFileObject::setCsvControl([string delimiter = ',' [, string enclosure = '"' [, string escape = '\\']]]) Set the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, setCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter = ',', enclosure = '"', escape='\\'; char *delim = NULL, *enclo = NULL, *esc = NULL; int d_len = 0, e_len = 0, esc_len = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) { switch(ZEND_NUM_ARGS()) { case 3: if (esc_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character"); RETURN_FALSE; } escape = esc[0]; /* no break */ case 2: if (e_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character"); RETURN_FALSE; } enclosure = enclo[0]; /* no break */ case 1: if (d_len != 1) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character"); RETURN_FALSE; } delimiter = delim[0]; /* no break */ case 0: break; } intern->u.file.delimiter = delimiter; intern->u.file.enclosure = enclosure; intern->u.file.escape = escape; } } /* }}} */ /* {{{ proto array SplFileObject::getCsvControl() Get the delimiter and enclosure character used in fgetcsv */ SPL_METHOD(SplFileObject, getCsvControl) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char delimiter[2], enclosure[2]; array_init(return_value); delimiter[0] = intern->u.file.delimiter; delimiter[1] = '\0'; enclosure[0] = intern->u.file.enclosure; enclosure[1] = '\0'; add_next_index_string(return_value, delimiter, 1); add_next_index_string(return_value, enclosure, 1); } /* }}} */ /* {{{ proto bool SplFileObject::flock(int operation [, int &wouldblock]) Portable file locking */ FileFunction(flock) /* }}} */ /* {{{ proto bool SplFileObject::fflush() Flush the file */ SPL_METHOD(SplFileObject, fflush) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_BOOL(!php_stream_flush(intern->u.file.stream)); } /* }}} */ /* {{{ proto int SplFileObject::ftell() Return current file position */ SPL_METHOD(SplFileObject, ftell) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long ret = php_stream_tell(intern->u.file.stream); if (ret == -1) { RETURN_FALSE; } else { RETURN_LONG(ret); } } /* }}} */ /* {{{ proto int SplFileObject::fseek(int pos [, int whence = SEEK_SET]) Return current file position */ SPL_METHOD(SplFileObject, fseek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long pos, whence = SEEK_SET; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &pos, &whence) == FAILURE) { return; } spl_filesystem_file_free_line(intern TSRMLS_CC); RETURN_LONG(php_stream_seek(intern->u.file.stream, pos, whence)); } /* }}} */ /* {{{ proto int SplFileObject::fgetc() Get a character form the file */ SPL_METHOD(SplFileObject, fgetc) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char buf[2]; int result; spl_filesystem_file_free_line(intern TSRMLS_CC); result = php_stream_getc(intern->u.file.stream); if (result == EOF) { RETVAL_FALSE; } else { if (result == '\n') { intern->u.file.current_line_num++; } buf[0] = result; buf[1] = '\0'; RETURN_STRINGL(buf, 1, 1); } } /* }}} */ /* {{{ proto string SplFileObject::fgetss([string allowable_tags]) Get a line from file pointer and strip HTML tags */ SPL_METHOD(SplFileObject, fgetss) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); zval *arg2 = NULL; MAKE_STD_ZVAL(arg2); if (intern->u.file.max_line_len > 0) { ZVAL_LONG(arg2, intern->u.file.max_line_len); } else { ZVAL_LONG(arg2, 1024); } spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fgetss, ZEND_NUM_ARGS(), arg2); zval_ptr_dtor(&arg2); } /* }}} */ /* {{{ proto int SplFileObject::fpassthru() Output all remaining data from a file pointer */ SPL_METHOD(SplFileObject, fpassthru) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); RETURN_LONG(php_stream_passthru(intern->u.file.stream)); } /* }}} */ /* {{{ proto bool SplFileObject::fscanf(string format [, string ...]) Implements a mostly ANSI compatible fscanf() */ SPL_METHOD(SplFileObject, fscanf) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); spl_filesystem_file_free_line(intern TSRMLS_CC); intern->u.file.current_line_num++; FileFunctionCall(fscanf, ZEND_NUM_ARGS(), NULL); } /* }}} */ /* {{{ proto mixed SplFileObject::fwrite(string str [, int length]) Binary-safe file write */ SPL_METHOD(SplFileObject, fwrite) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); char *str; int str_len; long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &str, &str_len, &length) == FAILURE) { return; } if (ZEND_NUM_ARGS() > 1) { str_len = MAX(0, MIN(length, str_len)); } if (!str_len) { RETURN_LONG(0); } RETURN_LONG(php_stream_write(intern->u.file.stream, str, str_len)); } /* }}} */ SPL_METHOD(SplFileObject, fread) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long length = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &length) == FAILURE) { return; } if (length <= 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be greater than 0"); RETURN_FALSE; } if (length > INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Length parameter must be no more than %d", INT_MAX); RETURN_FALSE; } Z_STRVAL_P(return_value) = emalloc(length + 1); Z_STRLEN_P(return_value) = php_stream_read(intern->u.file.stream, Z_STRVAL_P(return_value), length); /* needed because recv/read/gzread doesnt put a null at the end*/ Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0; Z_TYPE_P(return_value) = IS_STRING; } /* {{{ proto bool SplFileObject::fstat() Stat() on a filehandle */ FileFunction(fstat) /* }}} */ /* {{{ proto bool SplFileObject::ftruncate(int size) Truncate file to 'size' length */ SPL_METHOD(SplFileObject, ftruncate) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { return; } if (!php_stream_truncate_supported(intern->u.file.stream)) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't truncate file %s", intern->file_name); RETURN_FALSE; } RETURN_BOOL(0 == php_stream_truncate_set_size(intern->u.file.stream, size)); } /* }}} */ /* {{{ proto void SplFileObject::seek(int line_pos) Seek to specified line */ SPL_METHOD(SplFileObject, seek) { spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC); long line_pos; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &line_pos) == FAILURE) { return; } if (line_pos < 0) { zend_throw_exception_ex(spl_ce_LogicException, 0 TSRMLS_CC, "Can't seek file %s to negative line %ld", intern->file_name, line_pos); RETURN_FALSE; } spl_filesystem_file_rewind(getThis(), intern TSRMLS_CC); while(intern->u.file.current_line_num < line_pos) { if (spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC) == FAILURE) { break; } } } /* }}} */ /* {{{ Function/Class/Method definitions */ ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object___construct, 0, 0, 1) ZEND_ARG_INFO(0, file_name) ZEND_ARG_INFO(0, open_mode) ZEND_ARG_INFO(0, use_include_path) ZEND_ARG_INFO(0, context) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setFlags, 0) ZEND_ARG_INFO(0, flags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO(arginfo_file_object_setMaxLineLen, 0) ZEND_ARG_INFO(0, max_len) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetcsv, 0, 0, 0) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fputcsv, 0, 0, 1) ZEND_ARG_INFO(0, fields) ZEND_ARG_INFO(0, delimiter) ZEND_ARG_INFO(0, enclosure) ZEND_ARG_INFO(0, escape) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_flock, 0, 0, 1) ZEND_ARG_INFO(0, operation) ZEND_ARG_INFO(1, wouldblock) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fseek, 0, 0, 1) ZEND_ARG_INFO(0, pos) ZEND_ARG_INFO(0, whence) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fgetss, 0, 0, 0) ZEND_ARG_INFO(0, allowable_tags) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fscanf, 1, 0, 1) ZEND_ARG_INFO(0, format) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fwrite, 0, 0, 1) ZEND_ARG_INFO(0, str) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_fread, 0, 0, 1) ZEND_ARG_INFO(0, length) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_ftruncate, 0, 0, 1) ZEND_ARG_INFO(0, size) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_file_object_seek, 0, 0, 1) ZEND_ARG_INFO(0, line_pos) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplFileObject_functions[] = { SPL_ME(SplFileObject, __construct, arginfo_file_object___construct, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, rewind, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, eof, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, valid, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetcsv, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fputcsv, arginfo_file_object_fputcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setCsvControl, arginfo_file_object_fgetcsv, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getCsvControl, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, flock, arginfo_file_object_flock, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fflush, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftell, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fseek, arginfo_file_object_fseek, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetc, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fpassthru, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fgetss, arginfo_file_object_fgetss, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fscanf, arginfo_file_object_fscanf, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fwrite, arginfo_file_object_fwrite, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fread, arginfo_file_object_fread, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, fstat, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, ftruncate, arginfo_file_object_ftruncate, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, key, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, next, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setFlags, arginfo_file_object_setFlags, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getFlags, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, setMaxLineLen, arginfo_file_object_setMaxLineLen, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getMaxLineLen, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, hasChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, getChildren, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_ME(SplFileObject, seek, arginfo_file_object_seek, ZEND_ACC_PUBLIC) /* mappings */ SPL_MA(SplFileObject, getCurrentLine, SplFileObject, fgets, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) SPL_MA(SplFileObject, __toString, SplFileObject, current, arginfo_splfileinfo_void, ZEND_ACC_PUBLIC) PHP_FE_END }; ZEND_BEGIN_ARG_INFO_EX(arginfo_temp_file_object___construct, 0, 0, 0) ZEND_ARG_INFO(0, max_memory) ZEND_END_ARG_INFO() static const zend_function_entry spl_SplTempFileObject_functions[] = { SPL_ME(SplTempFileObject, __construct, arginfo_temp_file_object___construct, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ /* {{{ PHP_MINIT_FUNCTION(spl_directory) */ PHP_MINIT_FUNCTION(spl_directory) { REGISTER_SPL_STD_CLASS_EX(SplFileInfo, spl_filesystem_object_new, spl_SplFileInfo_functions); memcpy(&spl_filesystem_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); spl_filesystem_object_handlers.clone_obj = spl_filesystem_object_clone; spl_filesystem_object_handlers.cast_object = spl_filesystem_object_cast; spl_filesystem_object_handlers.get_debug_info = spl_filesystem_object_get_debug_info; spl_ce_SplFileInfo->serialize = zend_class_serialize_deny; spl_ce_SplFileInfo->unserialize = zend_class_unserialize_deny; REGISTER_SPL_SUB_CLASS_EX(DirectoryIterator, SplFileInfo, spl_filesystem_object_new, spl_DirectoryIterator_functions); zend_class_implements(spl_ce_DirectoryIterator TSRMLS_CC, 1, zend_ce_iterator); REGISTER_SPL_IMPLEMENTS(DirectoryIterator, SeekableIterator); spl_ce_DirectoryIterator->get_iterator = spl_filesystem_dir_get_iterator; REGISTER_SPL_SUB_CLASS_EX(FilesystemIterator, DirectoryIterator, spl_filesystem_object_new, spl_FilesystemIterator_functions); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_MODE_MASK", SPL_FILE_DIR_CURRENT_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_PATHNAME", SPL_FILE_DIR_CURRENT_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_FILEINFO", SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "CURRENT_AS_SELF", SPL_FILE_DIR_CURRENT_AS_SELF); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_MODE_MASK", SPL_FILE_DIR_KEY_MODE_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_PATHNAME", SPL_FILE_DIR_KEY_AS_PATHNAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "FOLLOW_SYMLINKS", SPL_FILE_DIR_FOLLOW_SYMLINKS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "KEY_AS_FILENAME", SPL_FILE_DIR_KEY_AS_FILENAME); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "NEW_CURRENT_AND_KEY", SPL_FILE_DIR_KEY_AS_FILENAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "OTHER_MODE_MASK", SPL_FILE_DIR_OTHERS_MASK); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "SKIP_DOTS", SPL_FILE_DIR_SKIPDOTS); REGISTER_SPL_CLASS_CONST_LONG(FilesystemIterator, "UNIX_PATHS", SPL_FILE_DIR_UNIXPATHS); spl_ce_FilesystemIterator->get_iterator = spl_filesystem_tree_get_iterator; REGISTER_SPL_SUB_CLASS_EX(RecursiveDirectoryIterator, FilesystemIterator, spl_filesystem_object_new, spl_RecursiveDirectoryIterator_functions); REGISTER_SPL_IMPLEMENTS(RecursiveDirectoryIterator, RecursiveIterator); memcpy(&spl_filesystem_object_check_handlers, &spl_filesystem_object_handlers, sizeof(zend_object_handlers)); spl_filesystem_object_check_handlers.get_method = spl_filesystem_object_get_method_check; #ifdef HAVE_GLOB REGISTER_SPL_SUB_CLASS_EX(GlobIterator, FilesystemIterator, spl_filesystem_object_new_check, spl_GlobIterator_functions); REGISTER_SPL_IMPLEMENTS(GlobIterator, Countable); #endif REGISTER_SPL_SUB_CLASS_EX(SplFileObject, SplFileInfo, spl_filesystem_object_new_check, spl_SplFileObject_functions); REGISTER_SPL_IMPLEMENTS(SplFileObject, RecursiveIterator); REGISTER_SPL_IMPLEMENTS(SplFileObject, SeekableIterator); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "DROP_NEW_LINE", SPL_FILE_OBJECT_DROP_NEW_LINE); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_AHEAD", SPL_FILE_OBJECT_READ_AHEAD); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "SKIP_EMPTY", SPL_FILE_OBJECT_SKIP_EMPTY); REGISTER_SPL_CLASS_CONST_LONG(SplFileObject, "READ_CSV", SPL_FILE_OBJECT_READ_CSV); REGISTER_SPL_SUB_CLASS_EX(SplTempFileObject, SplFileObject, spl_filesystem_object_new_check, spl_SplTempFileObject_functions); return SUCCESS; } /* }}} */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5170_0
crossvul-cpp_data_bad_130_0
/* ** {====================================================== ** Library for packing/unpacking structures. ** $Id: struct.c,v 1.4 2012/07/04 18:54:29 roberto Exp $ ** See Copyright Notice at the end of this file ** ======================================================= */ /* ** Valid formats: ** > - big endian ** < - little endian ** ![num] - alignment ** x - pading ** b/B - signed/unsigned byte ** h/H - signed/unsigned short ** l/L - signed/unsigned long ** T - size_t ** i/In - signed/unsigned integer with size `n' (default is size of int) ** cn - sequence of `n' chars (from/to a string); when packing, n==0 means the whole string; when unpacking, n==0 means use the previous read number as the string length ** s - zero-terminated string ** f - float ** d - double ** ' ' - ignored */ #include <assert.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <string.h> #include "lua.h" #include "lauxlib.h" #if (LUA_VERSION_NUM >= 502) #define luaL_register(L,n,f) luaL_newlib(L,f) #endif /* basic integer type */ #if !defined(STRUCT_INT) #define STRUCT_INT long #endif typedef STRUCT_INT Inttype; /* corresponding unsigned version */ typedef unsigned STRUCT_INT Uinttype; /* maximum size (in bytes) for integral types */ #define MAXINTSIZE 32 /* is 'x' a power of 2? */ #define isp2(x) ((x) > 0 && ((x) & ((x) - 1)) == 0) /* dummy structure to get alignment requirements */ struct cD { char c; double d; }; #define PADDING (sizeof(struct cD) - sizeof(double)) #define MAXALIGN (PADDING > sizeof(int) ? PADDING : sizeof(int)) /* endian options */ #define BIG 0 #define LITTLE 1 static union { int dummy; char endian; } const native = {1}; typedef struct Header { int endian; int align; } Header; static int getnum (lua_State *L, const char **fmt, int df) { if (!isdigit(**fmt)) /* no number? */ return df; /* return default value */ else { int a = 0; do { if (a > (INT_MAX / 10) || a * 10 > (INT_MAX - (**fmt - '0'))) luaL_error(L, "integral size overflow"); a = a*10 + *((*fmt)++) - '0'; } while (isdigit(**fmt)); return a; } } #define defaultoptions(h) ((h)->endian = native.endian, (h)->align = 1) static size_t optsize (lua_State *L, char opt, const char **fmt) { switch (opt) { case 'B': case 'b': return sizeof(char); case 'H': case 'h': return sizeof(short); case 'L': case 'l': return sizeof(long); case 'T': return sizeof(size_t); case 'f': return sizeof(float); case 'd': return sizeof(double); case 'x': return 1; case 'c': return getnum(L, fmt, 1); case 'i': case 'I': { int sz = getnum(L, fmt, sizeof(int)); if (sz > MAXINTSIZE) luaL_error(L, "integral size %d is larger than limit of %d", sz, MAXINTSIZE); return sz; } default: return 0; /* other cases do not need alignment */ } } /* ** return number of bytes needed to align an element of size 'size' ** at current position 'len' */ static int gettoalign (size_t len, Header *h, int opt, size_t size) { if (size == 0 || opt == 'c') return 0; if (size > (size_t)h->align) size = h->align; /* respect max. alignment */ return (size - (len & (size - 1))) & (size - 1); } /* ** options to control endianess and alignment */ static void controloptions (lua_State *L, int opt, const char **fmt, Header *h) { switch (opt) { case ' ': return; /* ignore white spaces */ case '>': h->endian = BIG; return; case '<': h->endian = LITTLE; return; case '!': { int a = getnum(L, fmt, MAXALIGN); if (!isp2(a)) luaL_error(L, "alignment %d is not a power of 2", a); h->align = a; return; } default: { const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt); luaL_argerror(L, 1, msg); } } } static void putinteger (lua_State *L, luaL_Buffer *b, int arg, int endian, int size) { lua_Number n = luaL_checknumber(L, arg); Uinttype value; char buff[MAXINTSIZE]; if (n < 0) value = (Uinttype)(Inttype)n; else value = (Uinttype)n; if (endian == LITTLE) { int i; for (i = 0; i < size; i++) { buff[i] = (value & 0xff); value >>= 8; } } else { int i; for (i = size - 1; i >= 0; i--) { buff[i] = (value & 0xff); value >>= 8; } } luaL_addlstring(b, buff, size); } static void correctbytes (char *b, int size, int endian) { if (endian != native.endian) { int i = 0; while (i < --size) { char temp = b[i]; b[i++] = b[size]; b[size] = temp; } } } static int b_pack (lua_State *L) { luaL_Buffer b; const char *fmt = luaL_checkstring(L, 1); Header h; int arg = 2; size_t totalsize = 0; defaultoptions(&h); lua_pushnil(L); /* mark to separate arguments from string buffer */ luaL_buffinit(L, &b); while (*fmt != '\0') { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); int toalign = gettoalign(totalsize, &h, opt, size); totalsize += toalign; while (toalign-- > 0) luaL_addchar(&b, '\0'); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ putinteger(L, &b, arg++, h.endian, size); break; } case 'x': { luaL_addchar(&b, '\0'); break; } case 'f': { float f = (float)luaL_checknumber(L, arg++); correctbytes((char *)&f, size, h.endian); luaL_addlstring(&b, (char *)&f, size); break; } case 'd': { double d = luaL_checknumber(L, arg++); correctbytes((char *)&d, size, h.endian); luaL_addlstring(&b, (char *)&d, size); break; } case 'c': case 's': { size_t l; const char *s = luaL_checklstring(L, arg++, &l); if (size == 0) size = l; luaL_argcheck(L, l >= (size_t)size, arg, "string too short"); luaL_addlstring(&b, s, size); if (opt == 's') { luaL_addchar(&b, '\0'); /* add zero at the end */ size++; } break; } default: controloptions(L, opt, &fmt, &h); } totalsize += size; } luaL_pushresult(&b); return 1; } static lua_Number getinteger (const char *buff, int endian, int issigned, int size) { Uinttype l = 0; int i; if (endian == BIG) { for (i = 0; i < size; i++) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } else { for (i = size - 1; i >= 0; i--) { l <<= 8; l |= (Uinttype)(unsigned char)buff[i]; } } if (!issigned) return (lua_Number)l; else { /* signed format */ Uinttype mask = (Uinttype)(~((Uinttype)0)) << (size*8 - 1); if (l & mask) /* negative value? */ l |= mask; /* signal extension */ return (lua_Number)(Inttype)l; } } static int b_unpack (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t ld; const char *data = luaL_checklstring(L, 2, &ld); size_t pos = luaL_optinteger(L, 3, 1) - 1; defaultoptions(&h); lua_settop(L, 2); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); luaL_checkstack(L, 1, "too many results"); switch (opt) { case 'b': case 'B': case 'h': case 'H': case 'l': case 'L': case 'T': case 'i': case 'I': { /* integer types */ int issigned = islower(opt); lua_Number res = getinteger(data+pos, h.endian, issigned, size); lua_pushnumber(L, res); break; } case 'x': { break; } case 'f': { float f; memcpy(&f, data+pos, size); correctbytes((char *)&f, sizeof(f), h.endian); lua_pushnumber(L, f); break; } case 'd': { double d; memcpy(&d, data+pos, size); correctbytes((char *)&d, sizeof(d), h.endian); lua_pushnumber(L, d); break; } case 'c': { if (size == 0) { if (!lua_isnumber(L, -1)) luaL_error(L, "format `c0' needs a previous size"); size = lua_tonumber(L, -1); lua_pop(L, 1); luaL_argcheck(L, pos+size <= ld, 2, "data string too short"); } lua_pushlstring(L, data+pos, size); break; } case 's': { const char *e = (const char *)memchr(data+pos, '\0', ld - pos); if (e == NULL) luaL_error(L, "unfinished string in data"); size = (e - (data+pos)) + 1; lua_pushlstring(L, data+pos, size - 1); break; } default: controloptions(L, opt, &fmt, &h); } pos += size; } lua_pushinteger(L, pos + 1); return lua_gettop(L) - 2; } static int b_size (lua_State *L) { Header h; const char *fmt = luaL_checkstring(L, 1); size_t pos = 0; defaultoptions(&h); while (*fmt) { int opt = *fmt++; size_t size = optsize(L, opt, &fmt); pos += gettoalign(pos, &h, opt, size); if (opt == 's') luaL_argerror(L, 1, "option 's' has no fixed size"); else if (opt == 'c' && size == 0) luaL_argerror(L, 1, "option 'c0' has no fixed size"); if (!isalnum(opt)) controloptions(L, opt, &fmt, &h); pos += size; } lua_pushinteger(L, pos); return 1; } /* }====================================================== */ static const struct luaL_Reg thislib[] = { {"pack", b_pack}, {"unpack", b_unpack}, {"size", b_size}, {NULL, NULL} }; LUALIB_API int luaopen_struct (lua_State *L); LUALIB_API int luaopen_struct (lua_State *L) { luaL_register(L, "struct", thislib); return 1; } /****************************************************************************** * Copyright (C) 2010-2012 Lua.org, PUC-Rio. 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. ******************************************************************************/
./CrossVul/dataset_final_sorted/CWE-190/c/bad_130_0
crossvul-cpp_data_bad_5400_2
/* * Copyright (c) 1999-2000 Image Power, Inc. and the University of * British Columbia. * Copyright (c) 2001-2003 Michael David Adams. * All rights reserved. */ /* __START_OF_JASPER_LICENSE__ * * JasPer License Version 2.0 * * Copyright (c) 2001-2006 Michael David Adams * Copyright (c) 1999-2000 Image Power, Inc. * Copyright (c) 1999-2000 The University of British Columbia * * All rights reserved. * * Permission is hereby granted, free of charge, to any person (the * "User") 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, 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: * * 1. The above copyright notices and this permission notice (which * includes the disclaimer below) shall be included in all copies or * substantial portions of the Software. * * 2. The name of a copyright holder shall not be used to endorse or * promote products derived from the Software without specific prior * written permission. * * THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS * LICENSE. NO USE OF THE SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER * THIS DISCLAIMER. THE SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS * "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 OF THIRD PARTY RIGHTS. IN NO * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL * INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. NO ASSURANCES ARE * PROVIDED BY THE COPYRIGHT HOLDERS THAT THE SOFTWARE DOES NOT INFRINGE * THE PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS OF ANY OTHER ENTITY. * EACH COPYRIGHT HOLDER DISCLAIMS ANY LIABILITY TO THE USER FOR CLAIMS * BROUGHT BY ANY OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL * PROPERTY RIGHTS OR OTHERWISE. AS A CONDITION TO EXERCISING THE RIGHTS * GRANTED HEREUNDER, EACH USER HEREBY ASSUMES SOLE RESPONSIBILITY TO SECURE * ANY OTHER INTELLECTUAL PROPERTY RIGHTS NEEDED, IF ANY. THE SOFTWARE * IS NOT FAULT-TOLERANT AND IS NOT INTENDED FOR USE IN MISSION-CRITICAL * SYSTEMS, SUCH AS THOSE USED IN THE OPERATION OF NUCLEAR FACILITIES, * AIRCRAFT NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL * SYSTEMS, DIRECT LIFE SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH * THE FAILURE OF THE SOFTWARE OR SYSTEM COULD LEAD DIRECTLY TO DEATH, * PERSONAL INJURY, OR SEVERE PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH * RISK ACTIVITIES"). THE COPYRIGHT HOLDERS SPECIFICALLY DISCLAIM ANY * EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR HIGH RISK ACTIVITIES. * * __END_OF_JASPER_LICENSE__ */ /* * I/O Stream Library * * $Id$ */ /******************************************************************************\ * Includes. \******************************************************************************/ #include <assert.h> #if defined(HAVE_FCNTL_H) #include <fcntl.h> #endif #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <ctype.h> #if defined(HAVE_UNISTD_H) #include <unistd.h> #endif #if defined(WIN32) || defined(HAVE_IO_H) #include <io.h> #endif #include "jasper/jas_debug.h" #include "jasper/jas_types.h" #include "jasper/jas_stream.h" #include "jasper/jas_malloc.h" #include "jasper/jas_math.h" /******************************************************************************\ * Local function prototypes. \******************************************************************************/ static int jas_strtoopenmode(const char *s); static void jas_stream_destroy(jas_stream_t *stream); static jas_stream_t *jas_stream_create(void); static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize); static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt); static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt); static long mem_seek(jas_stream_obj_t *obj, long offset, int origin); static int mem_close(jas_stream_obj_t *obj); static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt); static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt); static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin); static int sfile_close(jas_stream_obj_t *obj); static int file_read(jas_stream_obj_t *obj, char *buf, int cnt); static int file_write(jas_stream_obj_t *obj, char *buf, int cnt); static long file_seek(jas_stream_obj_t *obj, long offset, int origin); static int file_close(jas_stream_obj_t *obj); /******************************************************************************\ * Local data. \******************************************************************************/ static jas_stream_ops_t jas_stream_fileops = { file_read, file_write, file_seek, file_close }; static jas_stream_ops_t jas_stream_sfileops = { sfile_read, sfile_write, sfile_seek, sfile_close }; static jas_stream_ops_t jas_stream_memops = { mem_read, mem_write, mem_seek, mem_close }; /******************************************************************************\ * Code for opening and closing streams. \******************************************************************************/ static jas_stream_t *jas_stream_create() { jas_stream_t *stream; if (!(stream = jas_malloc(sizeof(jas_stream_t)))) { return 0; } stream->openmode_ = 0; stream->bufmode_ = 0; stream->flags_ = 0; stream->bufbase_ = 0; stream->bufstart_ = 0; stream->bufsize_ = 0; stream->ptr_ = 0; stream->cnt_ = 0; stream->ops_ = 0; stream->obj_ = 0; stream->rwcnt_ = 0; stream->rwlimit_ = -1; return stream; } jas_stream_t *jas_stream_memopen(char *buf, int bufsize) { jas_stream_t *stream; jas_stream_memobj_t *obj; JAS_DBGLOG(100, ("jas_stream_memopen(%p, %d)\n", buf, bufsize)); if (!(stream = jas_stream_create())) { return 0; } /* A stream associated with a memory buffer is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Since the stream data is already resident in memory, buffering is not necessary. */ /* But... It still may be faster to use buffering anyways. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a memory stream. */ stream->ops_ = &jas_stream_memops; /* Allocate memory for the underlying memory stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_memobj_t)))) { jas_stream_destroy(stream); return 0; } stream->obj_ = (void *) obj; /* Initialize a few important members of the memory stream object. */ obj->myalloc_ = 0; obj->buf_ = 0; /* If the buffer size specified is nonpositive, then the buffer is allocated internally and automatically grown as needed. */ if (bufsize <= 0) { obj->bufsize_ = 1024; obj->growable_ = 1; } else { obj->bufsize_ = bufsize; obj->growable_ = 0; } if (buf) { obj->buf_ = (unsigned char *) buf; } else { obj->buf_ = jas_malloc(obj->bufsize_); obj->myalloc_ = 1; } if (!obj->buf_) { jas_stream_close(stream); return 0; } JAS_DBGLOG(100, ("jas_stream_memopen buffer buf=%p myalloc=%d\n", obj->buf_, obj->myalloc_)); if (bufsize > 0 && buf) { /* If a buffer was supplied by the caller and its length is positive, make the associated buffer data appear in the stream initially. */ obj->len_ = bufsize; } else { /* The stream is initially empty. */ obj->len_ = 0; } obj->pos_ = 0; return stream; } jas_stream_t *jas_stream_fopen(const char *filename, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; int openflags; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; /* Open the underlying file. */ if ((obj->fd = open(filename, openflags, JAS_STREAM_PERMS)) < 0) { // Free the underlying file object, since it will not otherwise // be freed. jas_free(obj); jas_stream_destroy(stream); return 0; } /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_freopen(const char *path, const char *mode, FILE *fp) { jas_stream_t *stream; int openflags; /* Eliminate compiler warning about unused variable. */ path = 0; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); /* Determine the correct flags to use for opening the file. */ if ((stream->openmode_ & JAS_STREAM_READ) && (stream->openmode_ & JAS_STREAM_WRITE)) { openflags = O_RDWR; } else if (stream->openmode_ & JAS_STREAM_READ) { openflags = O_RDONLY; } else if (stream->openmode_ & JAS_STREAM_WRITE) { openflags = O_WRONLY; } else { openflags = 0; } if (stream->openmode_ & JAS_STREAM_APPEND) { openflags |= O_APPEND; } if (stream->openmode_ & JAS_STREAM_BINARY) { openflags |= O_BINARY; } if (stream->openmode_ & JAS_STREAM_CREATE) { openflags |= O_CREAT | O_TRUNC; } stream->obj_ = JAS_CAST(void *, fp); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_sfileops; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); return stream; } jas_stream_t *jas_stream_tmpfile() { jas_stream_t *stream; jas_stream_fileobj_t *obj; if (!(stream = jas_stream_create())) { return 0; } /* A temporary file stream is always opened for both reading and writing in binary mode. */ stream->openmode_ = JAS_STREAM_READ | JAS_STREAM_WRITE | JAS_STREAM_BINARY; /* Allocate memory for the underlying temporary file object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = -1; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = obj; /* Choose a file name. */ tmpnam(obj->pathname); /* Open the underlying file. */ if ((obj->fd = open(obj->pathname, O_CREAT | O_EXCL | O_RDWR | O_TRUNC | O_BINARY, JAS_STREAM_PERMS)) < 0) { jas_stream_destroy(stream); return 0; } /* Unlink the file so that it will disappear if the program terminates abnormally. */ /* Under UNIX, one can unlink an open file and continue to do I/O on it. Not all operating systems support this functionality, however. For example, under Microsoft Windows the unlink operation will fail, since the file is open. */ if (unlink(obj->pathname)) { /* We will try unlinking the file again after it is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_DELONCLOSE; } /* Use full buffering. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); stream->ops_ = &jas_stream_fileops; return stream; } jas_stream_t *jas_stream_fdopen(int fd, const char *mode) { jas_stream_t *stream; jas_stream_fileobj_t *obj; /* Allocate a stream object. */ if (!(stream = jas_stream_create())) { return 0; } /* Parse the mode string. */ stream->openmode_ = jas_strtoopenmode(mode); #if defined(WIN32) /* Argh!!! Someone ought to banish text mode (i.e., O_TEXT) to the greatest depths of purgatory! */ /* Ensure that the file descriptor is in binary mode, if the caller has specified the binary mode flag. Arguably, the caller ought to take care of this, but text mode is a ugly wart anyways, so we save the caller some grief by handling this within the stream library. */ /* This ugliness is mainly for the benefit of those who run the JasPer software under Windows from shells that insist on opening files in text mode. For example, in the Cygwin environment, shells often open files in text mode when I/O redirection is used. Grr... */ if (stream->openmode_ & JAS_STREAM_BINARY) { setmode(fd, O_BINARY); } #endif /* Allocate space for the underlying file stream object. */ if (!(obj = jas_malloc(sizeof(jas_stream_fileobj_t)))) { jas_stream_destroy(stream); return 0; } obj->fd = fd; obj->flags = 0; obj->pathname[0] = '\0'; stream->obj_ = (void *) obj; /* Do not close the underlying file descriptor when the stream is closed. */ obj->flags |= JAS_STREAM_FILEOBJ_NOCLOSE; /* By default, use full buffering for this type of stream. */ jas_stream_initbuf(stream, JAS_STREAM_FULLBUF, 0, 0); /* Select the operations for a file stream object. */ stream->ops_ = &jas_stream_fileops; return stream; } static void jas_stream_destroy(jas_stream_t *stream) { /* If the memory for the buffer was allocated with malloc, free this memory. */ if ((stream->bufmode_ & JAS_STREAM_FREEBUF) && stream->bufbase_) { JAS_DBGLOG(100, ("jas_stream_destroy freeing buffer %p\n", stream->bufbase_)); jas_free(stream->bufbase_); stream->bufbase_ = 0; } jas_free(stream); } int jas_stream_close(jas_stream_t *stream) { /* Flush buffer if necessary. */ jas_stream_flush(stream); /* Close the underlying stream object. */ (*stream->ops_->close_)(stream->obj_); jas_stream_destroy(stream); return 0; } /******************************************************************************\ * Code for reading and writing streams. \******************************************************************************/ int jas_stream_getc_func(jas_stream_t *stream) { assert(stream->ptr_ - stream->bufbase_ <= stream->bufsize_ + JAS_STREAM_MAXPUTBACK); return jas_stream_getc_macro(stream); } int jas_stream_putc_func(jas_stream_t *stream, int c) { assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); return jas_stream_putc_macro(stream, c); } int jas_stream_ungetc(jas_stream_t *stream, int c) { if (!stream->ptr_ || stream->ptr_ == stream->bufbase_) { return -1; } /* Reset the EOF indicator (since we now have at least one character to read). */ stream->flags_ &= ~JAS_STREAM_EOF; --stream->rwcnt_; --stream->ptr_; ++stream->cnt_; *stream->ptr_ = c; return 0; } int jas_stream_read(jas_stream_t *stream, void *buf, int cnt) { int n; int c; char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if ((c = jas_stream_getc(stream)) == EOF) { return n; } *bufptr++ = c; ++n; } return n; } int jas_stream_write(jas_stream_t *stream, const void *buf, int cnt) { int n; const char *bufptr; bufptr = buf; n = 0; while (n < cnt) { if (jas_stream_putc(stream, *bufptr) == EOF) { return n; } ++bufptr; ++n; } return n; } /* Note: This function uses a fixed size buffer. Therefore, it cannot handle invocations that will produce more output than can be held by the buffer. */ int jas_stream_printf(jas_stream_t *stream, const char *fmt, ...) { va_list ap; char buf[4096]; int ret; va_start(ap, fmt); ret = vsnprintf(buf, sizeof buf, fmt, ap); jas_stream_puts(stream, buf); va_end(ap); return ret; } int jas_stream_puts(jas_stream_t *stream, const char *s) { while (*s != '\0') { if (jas_stream_putc_macro(stream, *s) == EOF) { return -1; } ++s; } return 0; } char *jas_stream_gets(jas_stream_t *stream, char *buf, int bufsize) { int c; char *bufptr; assert(bufsize > 0); bufptr = buf; while (bufsize > 1) { if ((c = jas_stream_getc(stream)) == EOF) { break; } *bufptr++ = c; --bufsize; if (c == '\n') { break; } } *bufptr = '\0'; return buf; } int jas_stream_gobble(jas_stream_t *stream, int n) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_getc(stream) == EOF) { return n - m; } } return n; } int jas_stream_pad(jas_stream_t *stream, int n, int c) { int m; m = n; for (m = n; m > 0; --m) { if (jas_stream_putc(stream, c) == EOF) return n - m; } return n; } /******************************************************************************\ * Code for getting and setting the stream position. \******************************************************************************/ int jas_stream_isseekable(jas_stream_t *stream) { if (stream->ops_ == &jas_stream_memops) { return 1; } else if (stream->ops_ == &jas_stream_fileops) { if ((*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR) < 0) { return 0; } return 1; } else { return 0; } } int jas_stream_rewind(jas_stream_t *stream) { return jas_stream_seek(stream, 0, SEEK_SET); } long jas_stream_seek(jas_stream_t *stream, long offset, int origin) { long newpos; /* The buffer cannot be in use for both reading and writing. */ assert(!((stream->bufmode_ & JAS_STREAM_RDBUF) && (stream->bufmode_ & JAS_STREAM_WRBUF))); /* Reset the EOF indicator (since we may not be at the EOF anymore). */ stream->flags_ &= ~JAS_STREAM_EOF; if (stream->bufmode_ & JAS_STREAM_RDBUF) { if (origin == SEEK_CUR) { offset -= stream->cnt_; } } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { if (jas_stream_flush(stream)) { return -1; } } stream->cnt_ = 0; stream->ptr_ = stream->bufstart_; stream->bufmode_ &= ~(JAS_STREAM_RDBUF | JAS_STREAM_WRBUF); if ((newpos = (*stream->ops_->seek_)(stream->obj_, offset, origin)) < 0) { return -1; } return newpos; } long jas_stream_tell(jas_stream_t *stream) { int adjust; int offset; if (stream->bufmode_ & JAS_STREAM_RDBUF) { adjust = -stream->cnt_; } else if (stream->bufmode_ & JAS_STREAM_WRBUF) { adjust = stream->ptr_ - stream->bufstart_; } else { adjust = 0; } if ((offset = (*stream->ops_->seek_)(stream->obj_, 0, SEEK_CUR)) < 0) { return -1; } return offset + adjust; } /******************************************************************************\ * Buffer initialization code. \******************************************************************************/ static void jas_stream_initbuf(jas_stream_t *stream, int bufmode, char *buf, int bufsize) { /* If this function is being called, the buffer should not have been initialized yet. */ assert(!stream->bufbase_); if (bufmode != JAS_STREAM_UNBUF) { /* The full- or line-buffered mode is being employed. */ if (!buf) { /* The caller has not specified a buffer to employ, so allocate one. */ if ((stream->bufbase_ = jas_malloc(JAS_STREAM_BUFSIZE + JAS_STREAM_MAXPUTBACK))) { stream->bufmode_ |= JAS_STREAM_FREEBUF; stream->bufsize_ = JAS_STREAM_BUFSIZE; } else { /* The buffer allocation has failed. Resort to unbuffered operation. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } } else { /* The caller has specified a buffer to employ. */ /* The buffer must be large enough to accommodate maximum putback. */ assert(bufsize > JAS_STREAM_MAXPUTBACK); stream->bufbase_ = JAS_CAST(uchar *, buf); stream->bufsize_ = bufsize - JAS_STREAM_MAXPUTBACK; } } else { /* The unbuffered mode is being employed. */ /* A buffer should not have been supplied by the caller. */ assert(!buf); /* Use a trivial one-character buffer. */ stream->bufbase_ = stream->tinybuf_; stream->bufsize_ = 1; } stream->bufstart_ = &stream->bufbase_[JAS_STREAM_MAXPUTBACK]; stream->ptr_ = stream->bufstart_; stream->cnt_ = 0; stream->bufmode_ |= bufmode & JAS_STREAM_BUFMODEMASK; } /******************************************************************************\ * Buffer filling and flushing code. \******************************************************************************/ int jas_stream_flush(jas_stream_t *stream) { if (stream->bufmode_ & JAS_STREAM_RDBUF) { return 0; } return jas_stream_flushbuf(stream, EOF); } int jas_stream_fillbuf(jas_stream_t *stream, int getflag) { int c; /* The stream must not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for reading. */ if ((stream->openmode_ & JAS_STREAM_READ) == 0) { return EOF; } /* Make a half-hearted attempt to confirm that the buffer is not currently being used for writing. This check is not intended to be foolproof! */ assert((stream->bufmode_ & JAS_STREAM_WRBUF) == 0); assert(stream->ptr_ - stream->bufstart_ <= stream->bufsize_); /* Mark the buffer as being used for reading. */ stream->bufmode_ |= JAS_STREAM_RDBUF; /* Read new data into the buffer. */ stream->ptr_ = stream->bufstart_; if ((stream->cnt_ = (*stream->ops_->read_)(stream->obj_, (char *) stream->bufstart_, stream->bufsize_)) <= 0) { if (stream->cnt_ < 0) { stream->flags_ |= JAS_STREAM_ERR; } else { stream->flags_ |= JAS_STREAM_EOF; } stream->cnt_ = 0; return EOF; } assert(stream->cnt_ > 0); /* Get or peek at the first character in the buffer. */ c = (getflag) ? jas_stream_getc2(stream) : (*stream->ptr_); return c; } int jas_stream_flushbuf(jas_stream_t *stream, int c) { int len; int n; /* The stream should not be in an error or EOF state. */ if ((stream->flags_ & (JAS_STREAM_ERRMASK)) != 0) { return EOF; } /* The stream must be open for writing. */ if ((stream->openmode_ & (JAS_STREAM_WRITE | JAS_STREAM_APPEND)) == 0) { return EOF; } /* The buffer should not currently be in use for reading. */ assert(!(stream->bufmode_ & JAS_STREAM_RDBUF)); /* Note: Do not use the quantity stream->cnt to determine the number of characters in the buffer! Depending on how this function was called, the stream->cnt value may be "off-by-one". */ len = stream->ptr_ - stream->bufstart_; if (len > 0) { n = (*stream->ops_->write_)(stream->obj_, (char *) stream->bufstart_, len); if (n != len) { stream->flags_ |= JAS_STREAM_ERR; return EOF; } } stream->cnt_ = stream->bufsize_; stream->ptr_ = stream->bufstart_; stream->bufmode_ |= JAS_STREAM_WRBUF; if (c != EOF) { assert(stream->cnt_ > 0); return jas_stream_putc2(stream, c); } return 0; } /******************************************************************************\ * Miscellaneous code. \******************************************************************************/ static int jas_strtoopenmode(const char *s) { int openmode = 0; while (*s != '\0') { switch (*s) { case 'r': openmode |= JAS_STREAM_READ; break; case 'w': openmode |= JAS_STREAM_WRITE | JAS_STREAM_CREATE; break; case 'b': openmode |= JAS_STREAM_BINARY; break; case 'a': openmode |= JAS_STREAM_APPEND; break; case '+': openmode |= JAS_STREAM_READ | JAS_STREAM_WRITE; break; default: break; } ++s; } return openmode; } int jas_stream_copy(jas_stream_t *out, jas_stream_t *in, int n) { int all; int c; int m; all = (n < 0) ? 1 : 0; m = n; while (all || m > 0) { if ((c = jas_stream_getc_macro(in)) == EOF) { /* The next character of input could not be read. */ /* Return with an error if an I/O error occured (not including EOF) or if an explicit copy count was specified. */ return (!all || jas_stream_error(in)) ? (-1) : 0; } if (jas_stream_putc_macro(out, c) == EOF) { return -1; } --m; } return 0; } long jas_stream_setrwcount(jas_stream_t *stream, long rwcnt) { int old; old = stream->rwcnt_; stream->rwcnt_ = rwcnt; return old; } int jas_stream_display(jas_stream_t *stream, FILE *fp, int n) { unsigned char buf[16]; int i; int j; int m; int c; int display; int cnt; cnt = n - (n % 16); display = 1; for (i = 0; i < n; i += 16) { if (n > 16 && i > 0) { display = (i >= cnt) ? 1 : 0; } if (display) { fprintf(fp, "%08x:", i); } m = JAS_MIN(n - i, 16); for (j = 0; j < m; ++j) { if ((c = jas_stream_getc(stream)) == EOF) { abort(); return -1; } buf[j] = c; } if (display) { for (j = 0; j < m; ++j) { fprintf(fp, " %02x", buf[j]); } fputc(' ', fp); for (; j < 16; ++j) { fprintf(fp, " "); } for (j = 0; j < m; ++j) { if (isprint(buf[j])) { fputc(buf[j], fp); } else { fputc(' ', fp); } } fprintf(fp, "\n"); } } return 0; } long jas_stream_length(jas_stream_t *stream) { long oldpos; long pos; if ((oldpos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, 0, SEEK_END) < 0) { return -1; } if ((pos = jas_stream_tell(stream)) < 0) { return -1; } if (jas_stream_seek(stream, oldpos, SEEK_SET) < 0) { return -1; } return pos; } /******************************************************************************\ * Memory stream object. \******************************************************************************/ static int mem_read(jas_stream_obj_t *obj, char *buf, int cnt) { int n; assert(cnt >= 0); assert(buf); JAS_DBGLOG(100, ("mem_read(%p, %p, %d)\n", obj, buf, cnt)); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; n = m->len_ - m->pos_; cnt = JAS_MIN(n, cnt); memcpy(buf, &m->buf_[m->pos_], cnt); m->pos_ += cnt; return cnt; } static int mem_resize(jas_stream_memobj_t *m, int bufsize) { unsigned char *buf; //assert(m->buf_); assert(bufsize >= 0); JAS_DBGLOG(100, ("mem_resize(%p, %d)\n", m, bufsize)); if (!(buf = jas_realloc2(m->buf_, bufsize, sizeof(unsigned char))) && bufsize) { JAS_DBGLOG(100, ("mem_resize realloc failed\n")); return -1; } JAS_DBGLOG(100, ("mem_resize realloc succeeded\n")); m->buf_ = buf; m->bufsize_ = bufsize; return 0; } static int mem_write(jas_stream_obj_t *obj, char *buf, int cnt) { int n; int ret; jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newbufsize; long newpos; assert(buf); assert(cnt >= 0); JAS_DBGLOG(100, ("mem_write(%p, %p, %d)\n", obj, buf, cnt)); newpos = m->pos_ + cnt; if (newpos > m->bufsize_ && m->growable_) { newbufsize = m->bufsize_; while (newbufsize < newpos) { newbufsize <<= 1; assert(newbufsize >= 0); } JAS_DBGLOG(100, ("mem_write resizing from %d to %z\n", m->bufsize_, newbufsize)); JAS_DBGLOG(100, ("mem_write resizing from %d to %ul\n", m->bufsize_, JAS_CAST(unsigned long, newbufsize))); if (mem_resize(m, newbufsize)) { return -1; } } if (m->pos_ > m->len_) { /* The current position is beyond the end of the file, so pad the file to the current position with zeros. */ n = JAS_MIN(m->pos_, m->bufsize_) - m->len_; if (n > 0) { memset(&m->buf_[m->len_], 0, n); m->len_ += n; } if (m->pos_ != m->len_) { /* The buffer is not big enough. */ return 0; } } n = m->bufsize_ - m->pos_; ret = JAS_MIN(n, cnt); if (ret > 0) { memcpy(&m->buf_[m->pos_], buf, ret); m->pos_ += ret; } if (m->pos_ > m->len_) { m->len_ = m->pos_; } assert(ret == cnt); return ret; } static long mem_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; long newpos; JAS_DBGLOG(100, ("mem_seek(%p, %ld, %d)\n", obj, offset, origin)); switch (origin) { case SEEK_SET: newpos = offset; break; case SEEK_END: newpos = m->len_ - offset; break; case SEEK_CUR: newpos = m->pos_ + offset; break; default: abort(); break; } if (newpos < 0) { return -1; } m->pos_ = newpos; return m->pos_; } static int mem_close(jas_stream_obj_t *obj) { JAS_DBGLOG(100, ("mem_close(%p)\n", obj)); jas_stream_memobj_t *m = (jas_stream_memobj_t *)obj; JAS_DBGLOG(100, ("mem_close myalloc=%d\n", m->myalloc_)); if (m->myalloc_ && m->buf_) { JAS_DBGLOG(100, ("mem_close freeing buffer %p\n", m->buf_)); jas_free(m->buf_); m->buf_ = 0; } jas_free(obj); return 0; } /******************************************************************************\ * File stream object. \******************************************************************************/ static int file_read(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_read(%p, %p, %d)\n", obj, buf, cnt)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return read(fileobj->fd, buf, cnt); } static int file_write(jas_stream_obj_t *obj, char *buf, int cnt) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_write(%p, %p, %d)\n", obj, buf, cnt)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return write(fileobj->fd, buf, cnt); } static long file_seek(jas_stream_obj_t *obj, long offset, int origin) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_seek(%p, %ld, %d)\n", obj, offset, origin)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); return lseek(fileobj->fd, offset, origin); } static int file_close(jas_stream_obj_t *obj) { jas_stream_fileobj_t *fileobj; JAS_DBGLOG(100, ("file_close(%p)\n", obj)); fileobj = JAS_CAST(jas_stream_fileobj_t *, obj); int ret; ret = close(fileobj->fd); if (fileobj->flags & JAS_STREAM_FILEOBJ_DELONCLOSE) { unlink(fileobj->pathname); } jas_free(fileobj); return ret; } /******************************************************************************\ * Stdio file stream object. \******************************************************************************/ static int sfile_read(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; size_t n; int result; JAS_DBGLOG(100, ("sfile_read(%p, %p, %d)\n", obj, buf, cnt)); fp = JAS_CAST(FILE *, obj); n = fread(buf, 1, cnt, fp); if (n != cnt) { result = (!ferror(fp) && feof(fp)) ? 0 : -1; } result = JAS_CAST(int, n); return result; } static int sfile_write(jas_stream_obj_t *obj, char *buf, int cnt) { FILE *fp; size_t n; JAS_DBGLOG(100, ("sfile_write(%p, %p, %d)\n", obj, buf, cnt)); fp = JAS_CAST(FILE *, obj); n = fwrite(buf, 1, cnt, fp); return (n != JAS_CAST(size_t, cnt)) ? (-1) : cnt; } static long sfile_seek(jas_stream_obj_t *obj, long offset, int origin) { FILE *fp; JAS_DBGLOG(100, ("sfile_seek(%p, %ld, %d)\n", obj, offset, origin)); fp = JAS_CAST(FILE *, obj); return fseek(fp, offset, origin); } static int sfile_close(jas_stream_obj_t *obj) { FILE *fp; JAS_DBGLOG(100, ("sfile_close(%p)\n", obj)); fp = JAS_CAST(FILE *, obj); return fclose(fp); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_5400_2
crossvul-cpp_data_good_1943_0
/* Configuration file parsing and CONFIG GET/SET commands implementation. * * Copyright (c) 2009-2012, Salvatore Sanfilippo <antirez at gmail dot com> * All rights reserved. * * 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 Redis 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. */ #include "server.h" #include "cluster.h" #include <fcntl.h> #include <sys/stat.h> /*----------------------------------------------------------------------------- * Config file name-value maps. *----------------------------------------------------------------------------*/ typedef struct configEnum { const char *name; const int val; } configEnum; configEnum maxmemory_policy_enum[] = { {"volatile-lru", MAXMEMORY_VOLATILE_LRU}, {"volatile-lfu", MAXMEMORY_VOLATILE_LFU}, {"volatile-random",MAXMEMORY_VOLATILE_RANDOM}, {"volatile-ttl",MAXMEMORY_VOLATILE_TTL}, {"allkeys-lru",MAXMEMORY_ALLKEYS_LRU}, {"allkeys-lfu",MAXMEMORY_ALLKEYS_LFU}, {"allkeys-random",MAXMEMORY_ALLKEYS_RANDOM}, {"noeviction",MAXMEMORY_NO_EVICTION}, {NULL, 0} }; configEnum syslog_facility_enum[] = { {"user", LOG_USER}, {"local0", LOG_LOCAL0}, {"local1", LOG_LOCAL1}, {"local2", LOG_LOCAL2}, {"local3", LOG_LOCAL3}, {"local4", LOG_LOCAL4}, {"local5", LOG_LOCAL5}, {"local6", LOG_LOCAL6}, {"local7", LOG_LOCAL7}, {NULL, 0} }; configEnum loglevel_enum[] = { {"debug", LL_DEBUG}, {"verbose", LL_VERBOSE}, {"notice", LL_NOTICE}, {"warning", LL_WARNING}, {NULL,0} }; configEnum supervised_mode_enum[] = { {"upstart", SUPERVISED_UPSTART}, {"systemd", SUPERVISED_SYSTEMD}, {"auto", SUPERVISED_AUTODETECT}, {"no", SUPERVISED_NONE}, {NULL, 0} }; configEnum aof_fsync_enum[] = { {"everysec", AOF_FSYNC_EVERYSEC}, {"always", AOF_FSYNC_ALWAYS}, {"no", AOF_FSYNC_NO}, {NULL, 0} }; configEnum repl_diskless_load_enum[] = { {"disabled", REPL_DISKLESS_LOAD_DISABLED}, {"on-empty-db", REPL_DISKLESS_LOAD_WHEN_DB_EMPTY}, {"swapdb", REPL_DISKLESS_LOAD_SWAPDB}, {NULL, 0} }; configEnum tls_auth_clients_enum[] = { {"no", TLS_CLIENT_AUTH_NO}, {"yes", TLS_CLIENT_AUTH_YES}, {"optional", TLS_CLIENT_AUTH_OPTIONAL}, {NULL, 0} }; configEnum oom_score_adj_enum[] = { {"no", OOM_SCORE_ADJ_NO}, {"yes", OOM_SCORE_RELATIVE}, {"relative", OOM_SCORE_RELATIVE}, {"absolute", OOM_SCORE_ADJ_ABSOLUTE}, {NULL, 0} }; /* Output buffer limits presets. */ clientBufferLimitsConfig clientBufferLimitsDefaults[CLIENT_TYPE_OBUF_COUNT] = { {0, 0, 0}, /* normal */ {1024*1024*256, 1024*1024*64, 60}, /* slave */ {1024*1024*32, 1024*1024*8, 60} /* pubsub */ }; /* OOM Score defaults */ int configOOMScoreAdjValuesDefaults[CONFIG_OOM_COUNT] = { 0, 200, 800 }; /* Generic config infrastructure function pointers * int is_valid_fn(val, err) * Return 1 when val is valid, and 0 when invalid. * Optionally set err to a static error string. * int update_fn(val, prev, err) * This function is called only for CONFIG SET command (not at config file parsing) * It is called after the actual config is applied, * Return 1 for success, and 0 for failure. * Optionally set err to a static error string. * On failure the config change will be reverted. */ /* Configuration values that require no special handling to set, get, load or * rewrite. */ typedef struct boolConfigData { int *config; /* The pointer to the server config this value is stored in */ const int default_value; /* The default value of the config on rewrite */ int (*is_valid_fn)(int val, char **err); /* Optional function to check validity of new value (generic doc above) */ int (*update_fn)(int val, int prev, char **err); /* Optional function to apply new value at runtime (generic doc above) */ } boolConfigData; typedef struct stringConfigData { char **config; /* Pointer to the server config this value is stored in. */ const char *default_value; /* Default value of the config on rewrite. */ int (*is_valid_fn)(char* val, char **err); /* Optional function to check validity of new value (generic doc above) */ int (*update_fn)(char* val, char* prev, char **err); /* Optional function to apply new value at runtime (generic doc above) */ int convert_empty_to_null; /* Boolean indicating if empty strings should be stored as a NULL value. */ } stringConfigData; typedef struct enumConfigData { int *config; /* The pointer to the server config this value is stored in */ configEnum *enum_value; /* The underlying enum type this data represents */ const int default_value; /* The default value of the config on rewrite */ int (*is_valid_fn)(int val, char **err); /* Optional function to check validity of new value (generic doc above) */ int (*update_fn)(int val, int prev, char **err); /* Optional function to apply new value at runtime (generic doc above) */ } enumConfigData; typedef enum numericType { NUMERIC_TYPE_INT, NUMERIC_TYPE_UINT, NUMERIC_TYPE_LONG, NUMERIC_TYPE_ULONG, NUMERIC_TYPE_LONG_LONG, NUMERIC_TYPE_ULONG_LONG, NUMERIC_TYPE_SIZE_T, NUMERIC_TYPE_SSIZE_T, NUMERIC_TYPE_OFF_T, NUMERIC_TYPE_TIME_T, } numericType; typedef struct numericConfigData { union { int *i; unsigned int *ui; long *l; unsigned long *ul; long long *ll; unsigned long long *ull; size_t *st; ssize_t *sst; off_t *ot; time_t *tt; } config; /* The pointer to the numeric config this value is stored in */ int is_memory; /* Indicates if this value can be loaded as a memory value */ numericType numeric_type; /* An enum indicating the type of this value */ long long lower_bound; /* The lower bound of this numeric value */ long long upper_bound; /* The upper bound of this numeric value */ const long long default_value; /* The default value of the config on rewrite */ int (*is_valid_fn)(long long val, char **err); /* Optional function to check validity of new value (generic doc above) */ int (*update_fn)(long long val, long long prev, char **err); /* Optional function to apply new value at runtime (generic doc above) */ } numericConfigData; typedef union typeData { boolConfigData yesno; stringConfigData string; enumConfigData enumd; numericConfigData numeric; } typeData; typedef struct typeInterface { /* Called on server start, to init the server with default value */ void (*init)(typeData data); /* Called on server start, should return 1 on success, 0 on error and should set err */ int (*load)(typeData data, sds *argc, int argv, char **err); /* Called on server startup and CONFIG SET, returns 1 on success, 0 on error * and can set a verbose err string, update is true when called from CONFIG SET */ int (*set)(typeData data, sds value, int update, char **err); /* Called on CONFIG GET, required to add output to the client */ void (*get)(client *c, typeData data); /* Called on CONFIG REWRITE, required to rewrite the config state */ void (*rewrite)(typeData data, const char *name, struct rewriteConfigState *state); } typeInterface; typedef struct standardConfig { const char *name; /* The user visible name of this config */ const char *alias; /* An alias that can also be used for this config */ const int modifiable; /* Can this value be updated by CONFIG SET? */ typeInterface interface; /* The function pointers that define the type interface */ typeData data; /* The type specific data exposed used by the interface */ } standardConfig; standardConfig configs[]; /*----------------------------------------------------------------------------- * Enum access functions *----------------------------------------------------------------------------*/ /* Get enum value from name. If there is no match INT_MIN is returned. */ int configEnumGetValue(configEnum *ce, char *name) { while(ce->name != NULL) { if (!strcasecmp(ce->name,name)) return ce->val; ce++; } return INT_MIN; } /* Get enum name from value. If no match is found NULL is returned. */ const char *configEnumGetName(configEnum *ce, int val) { while(ce->name != NULL) { if (ce->val == val) return ce->name; ce++; } return NULL; } /* Wrapper for configEnumGetName() returning "unknown" instead of NULL if * there is no match. */ const char *configEnumGetNameOrUnknown(configEnum *ce, int val) { const char *name = configEnumGetName(ce,val); return name ? name : "unknown"; } /* Used for INFO generation. */ const char *evictPolicyToString(void) { return configEnumGetNameOrUnknown(maxmemory_policy_enum,server.maxmemory_policy); } /*----------------------------------------------------------------------------- * Config file parsing *----------------------------------------------------------------------------*/ int yesnotoi(char *s) { if (!strcasecmp(s,"yes")) return 1; else if (!strcasecmp(s,"no")) return 0; else return -1; } void appendServerSaveParams(time_t seconds, int changes) { server.saveparams = zrealloc(server.saveparams,sizeof(struct saveparam)*(server.saveparamslen+1)); server.saveparams[server.saveparamslen].seconds = seconds; server.saveparams[server.saveparamslen].changes = changes; server.saveparamslen++; } void resetServerSaveParams(void) { zfree(server.saveparams); server.saveparams = NULL; server.saveparamslen = 0; } void queueLoadModule(sds path, sds *argv, int argc) { int i; struct moduleLoadQueueEntry *loadmod; loadmod = zmalloc(sizeof(struct moduleLoadQueueEntry)); loadmod->argv = zmalloc(sizeof(robj*)*argc); loadmod->path = sdsnew(path); loadmod->argc = argc; for (i = 0; i < argc; i++) { loadmod->argv[i] = createRawStringObject(argv[i],sdslen(argv[i])); } listAddNodeTail(server.loadmodule_queue,loadmod); } /* Parse an array of CONFIG_OOM_COUNT sds strings, validate and populate * server.oom_score_adj_values if valid. */ static int updateOOMScoreAdjValues(sds *args, char **err, int apply) { int i; int values[CONFIG_OOM_COUNT]; for (i = 0; i < CONFIG_OOM_COUNT; i++) { char *eptr; long long val = strtoll(args[i], &eptr, 10); if (*eptr != '\0' || val < -2000 || val > 2000) { if (err) *err = "Invalid oom-score-adj-values, elements must be between -2000 and 2000."; return C_ERR; } values[i] = val; } /* Verify that the values make sense. If they don't omit a warning but * keep the configuration, which may still be valid for privileged processes. */ if (values[CONFIG_OOM_REPLICA] < values[CONFIG_OOM_MASTER] || values[CONFIG_OOM_BGCHILD] < values[CONFIG_OOM_REPLICA]) { serverLog(LOG_WARNING, "The oom-score-adj-values configuration may not work for non-privileged processes! " "Please consult the documentation."); } /* Store values, retain previous config for rollback in case we fail. */ int old_values[CONFIG_OOM_COUNT]; for (i = 0; i < CONFIG_OOM_COUNT; i++) { old_values[i] = server.oom_score_adj_values[i]; server.oom_score_adj_values[i] = values[i]; } /* When parsing the config file, we want to apply only when all is done. */ if (!apply) return C_OK; /* Update */ if (setOOMScoreAdj(-1) == C_ERR) { /* Roll back */ for (i = 0; i < CONFIG_OOM_COUNT; i++) server.oom_score_adj_values[i] = old_values[i]; if (err) *err = "Failed to apply oom-score-adj-values configuration, check server logs."; return C_ERR; } return C_OK; } void initConfigValues() { for (standardConfig *config = configs; config->name != NULL; config++) { config->interface.init(config->data); } } void loadServerConfigFromString(char *config) { char *err = NULL; int linenum = 0, totlines, i; int slaveof_linenum = 0; sds *lines; lines = sdssplitlen(config,strlen(config),"\n",1,&totlines); for (i = 0; i < totlines; i++) { sds *argv; int argc; linenum = i+1; lines[i] = sdstrim(lines[i]," \t\r\n"); /* Skip comments and blank lines */ if (lines[i][0] == '#' || lines[i][0] == '\0') continue; /* Split into arguments */ argv = sdssplitargs(lines[i],&argc); if (argv == NULL) { err = "Unbalanced quotes in configuration line"; goto loaderr; } /* Skip this line if the resulting command vector is empty. */ if (argc == 0) { sdsfreesplitres(argv,argc); continue; } sdstolower(argv[0]); /* Iterate the configs that are standard */ int match = 0; for (standardConfig *config = configs; config->name != NULL; config++) { if ((!strcasecmp(argv[0],config->name) || (config->alias && !strcasecmp(argv[0],config->alias)))) { if (argc != 2) { err = "wrong number of arguments"; goto loaderr; } if (!config->interface.set(config->data, argv[1], 0, &err)) { goto loaderr; } match = 1; break; } } if (match) { sdsfreesplitres(argv,argc); continue; } /* Execute config directives */ if (!strcasecmp(argv[0],"bind") && argc >= 2) { int j, addresses = argc-1; if (addresses > CONFIG_BINDADDR_MAX) { err = "Too many bind addresses specified"; goto loaderr; } /* Free old bind addresses */ for (j = 0; j < server.bindaddr_count; j++) { zfree(server.bindaddr[j]); } for (j = 0; j < addresses; j++) server.bindaddr[j] = zstrdup(argv[j+1]); server.bindaddr_count = addresses; } else if (!strcasecmp(argv[0],"unixsocketperm") && argc == 2) { errno = 0; server.unixsocketperm = (mode_t)strtol(argv[1], NULL, 8); if (errno || server.unixsocketperm > 0777) { err = "Invalid socket file permissions"; goto loaderr; } } else if (!strcasecmp(argv[0],"save")) { if (argc == 3) { int seconds = atoi(argv[1]); int changes = atoi(argv[2]); if (seconds < 1 || changes < 0) { err = "Invalid save parameters"; goto loaderr; } appendServerSaveParams(seconds,changes); } else if (argc == 2 && !strcasecmp(argv[1],"")) { resetServerSaveParams(); } } else if (!strcasecmp(argv[0],"dir") && argc == 2) { if (chdir(argv[1]) == -1) { serverLog(LL_WARNING,"Can't chdir to '%s': %s", argv[1], strerror(errno)); exit(1); } } else if (!strcasecmp(argv[0],"logfile") && argc == 2) { FILE *logfp; zfree(server.logfile); server.logfile = zstrdup(argv[1]); if (server.logfile[0] != '\0') { /* Test if we are able to open the file. The server will not * be able to abort just for this problem later... */ logfp = fopen(server.logfile,"a"); if (logfp == NULL) { err = sdscatprintf(sdsempty(), "Can't open the log file: %s", strerror(errno)); goto loaderr; } fclose(logfp); } } else if (!strcasecmp(argv[0],"include") && argc == 2) { loadServerConfig(argv[1],NULL); } else if ((!strcasecmp(argv[0],"client-query-buffer-limit")) && argc == 2) { server.client_max_querybuf_len = memtoll(argv[1],NULL); } else if ((!strcasecmp(argv[0],"slaveof") || !strcasecmp(argv[0],"replicaof")) && argc == 3) { slaveof_linenum = linenum; sdsfree(server.masterhost); if (!strcasecmp(argv[1], "no") && !strcasecmp(argv[2], "one")) { server.masterhost = NULL; continue; } server.masterhost = sdsnew(argv[1]); char *ptr; server.masterport = strtol(argv[2], &ptr, 10); if (server.masterport < 0 || server.masterport > 65535 || *ptr != '\0') { err = "Invalid master port"; goto loaderr; } server.repl_state = REPL_STATE_CONNECT; } else if (!strcasecmp(argv[0],"requirepass") && argc == 2) { if (strlen(argv[1]) > CONFIG_AUTHPASS_MAX_LEN) { err = "Password is longer than CONFIG_AUTHPASS_MAX_LEN"; goto loaderr; } /* The old "requirepass" directive just translates to setting * a password to the default user. The only thing we do * additionally is to remember the cleartext password in this * case, for backward compatibility with Redis <= 5. */ ACLSetUser(DefaultUser,"resetpass",-1); sdsfree(server.requirepass); server.requirepass = NULL; if (sdslen(argv[1])) { sds aclop = sdscatprintf(sdsempty(),">%s",argv[1]); ACLSetUser(DefaultUser,aclop,sdslen(aclop)); sdsfree(aclop); server.requirepass = sdsnew(argv[1]); } else { ACLSetUser(DefaultUser,"nopass",-1); } } else if (!strcasecmp(argv[0],"list-max-ziplist-entries") && argc == 2){ /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"list-max-ziplist-value") && argc == 2) { /* DEAD OPTION */ } else if (!strcasecmp(argv[0],"rename-command") && argc == 3) { struct redisCommand *cmd = lookupCommand(argv[1]); int retval; if (!cmd) { err = "No such command in rename-command"; goto loaderr; } /* If the target command name is the empty string we just * remove it from the command table. */ retval = dictDelete(server.commands, argv[1]); serverAssert(retval == DICT_OK); /* Otherwise we re-add the command under a different name. */ if (sdslen(argv[2]) != 0) { sds copy = sdsdup(argv[2]); retval = dictAdd(server.commands, copy, cmd); if (retval != DICT_OK) { sdsfree(copy); err = "Target command name already exists"; goto loaderr; } } } else if (!strcasecmp(argv[0],"cluster-config-file") && argc == 2) { zfree(server.cluster_configfile); server.cluster_configfile = zstrdup(argv[1]); } else if (!strcasecmp(argv[0],"client-output-buffer-limit") && argc == 5) { int class = getClientTypeByName(argv[1]); unsigned long long hard, soft; int soft_seconds; if (class == -1 || class == CLIENT_TYPE_MASTER) { err = "Unrecognized client limit class: the user specified " "an invalid one, or 'master' which has no buffer limits."; goto loaderr; } hard = memtoll(argv[2],NULL); soft = memtoll(argv[3],NULL); soft_seconds = atoi(argv[4]); if (soft_seconds < 0) { err = "Negative number of seconds in soft limit is invalid"; goto loaderr; } server.client_obuf_limits[class].hard_limit_bytes = hard; server.client_obuf_limits[class].soft_limit_bytes = soft; server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; } else if (!strcasecmp(argv[0],"oom-score-adj-values") && argc == 1 + CONFIG_OOM_COUNT) { if (updateOOMScoreAdjValues(&argv[1], &err, 0) == C_ERR) goto loaderr; } else if (!strcasecmp(argv[0],"notify-keyspace-events") && argc == 2) { int flags = keyspaceEventsStringToFlags(argv[1]); if (flags == -1) { err = "Invalid event class character. Use 'g$lshzxeA'."; goto loaderr; } server.notify_keyspace_events = flags; } else if (!strcasecmp(argv[0],"user") && argc >= 2) { int argc_err; if (ACLAppendUserForLoading(argv,argc,&argc_err) == C_ERR) { char buf[1024]; char *errmsg = ACLSetUserStringError(); snprintf(buf,sizeof(buf),"Error in user declaration '%s': %s", argv[argc_err],errmsg); err = buf; goto loaderr; } } else if (!strcasecmp(argv[0],"loadmodule") && argc >= 2) { queueLoadModule(argv[1],&argv[2],argc-2); } else if (!strcasecmp(argv[0],"sentinel")) { /* argc == 1 is handled by main() as we need to enter the sentinel * mode ASAP. */ if (argc != 1) { if (!server.sentinel_mode) { err = "sentinel directive while not in sentinel mode"; goto loaderr; } err = sentinelHandleConfiguration(argv+1,argc-1); if (err) goto loaderr; } } else { err = "Bad directive or wrong number of arguments"; goto loaderr; } sdsfreesplitres(argv,argc); } /* Sanity checks. */ if (server.cluster_enabled && server.masterhost) { linenum = slaveof_linenum; i = linenum-1; err = "replicaof directive not allowed in cluster mode"; goto loaderr; } sdsfreesplitres(lines,totlines); return; loaderr: fprintf(stderr, "\n*** FATAL CONFIG FILE ERROR (Redis %s) ***\n", REDIS_VERSION); fprintf(stderr, "Reading the configuration file, at line %d\n", linenum); fprintf(stderr, ">>> '%s'\n", lines[i]); fprintf(stderr, "%s\n", err); exit(1); } /* Load the server configuration from the specified filename. * The function appends the additional configuration directives stored * in the 'options' string to the config file before loading. * * Both filename and options can be NULL, in such a case are considered * empty. This way loadServerConfig can be used to just load a file or * just load a string. */ void loadServerConfig(char *filename, char *options) { sds config = sdsempty(); char buf[CONFIG_MAX_LINE+1]; /* Load the file content */ if (filename) { FILE *fp; if (filename[0] == '-' && filename[1] == '\0') { fp = stdin; } else { if ((fp = fopen(filename,"r")) == NULL) { serverLog(LL_WARNING, "Fatal error, can't open config file '%s': %s", filename, strerror(errno)); exit(1); } } while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL) config = sdscat(config,buf); if (fp != stdin) fclose(fp); } /* Append the additional options */ if (options) { config = sdscat(config,"\n"); config = sdscat(config,options); } loadServerConfigFromString(config); sdsfree(config); } /*----------------------------------------------------------------------------- * CONFIG SET implementation *----------------------------------------------------------------------------*/ #define config_set_bool_field(_name,_var) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ int yn = yesnotoi(o->ptr); \ if (yn == -1) goto badfmt; \ _var = yn; #define config_set_numerical_field(_name,_var,min,max) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ if (getLongLongFromObject(o,&ll) == C_ERR) goto badfmt; \ if (min != LLONG_MIN && ll < min) goto badfmt; \ if (max != LLONG_MAX && ll > max) goto badfmt; \ _var = ll; #define config_set_memory_field(_name,_var) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { \ ll = memtoll(o->ptr,&err); \ if (err || ll < 0) goto badfmt; \ _var = ll; #define config_set_special_field(_name) \ } else if (!strcasecmp(c->argv[2]->ptr,_name)) { #define config_set_special_field_with_alias(_name1,_name2) \ } else if (!strcasecmp(c->argv[2]->ptr,_name1) || \ !strcasecmp(c->argv[2]->ptr,_name2)) { #define config_set_else } else void configSetCommand(client *c) { robj *o; long long ll; int err; char *errstr = NULL; serverAssertWithInfo(c,c->argv[2],sdsEncodedObject(c->argv[2])); serverAssertWithInfo(c,c->argv[3],sdsEncodedObject(c->argv[3])); o = c->argv[3]; /* Iterate the configs that are standard */ for (standardConfig *config = configs; config->name != NULL; config++) { if(config->modifiable && (!strcasecmp(c->argv[2]->ptr,config->name) || (config->alias && !strcasecmp(c->argv[2]->ptr,config->alias)))) { if (!config->interface.set(config->data,o->ptr,1,&errstr)) { goto badfmt; } addReply(c,shared.ok); return; } } if (0) { /* this starts the config_set macros else-if chain. */ /* Special fields that can't be handled with general macros. */ config_set_special_field("requirepass") { if (sdslen(o->ptr) > CONFIG_AUTHPASS_MAX_LEN) goto badfmt; /* The old "requirepass" directive just translates to setting * a password to the default user. The only thing we do * additionally is to remember the cleartext password in this * case, for backward compatibility with Redis <= 5. */ ACLSetUser(DefaultUser,"resetpass",-1); sdsfree(server.requirepass); server.requirepass = NULL; if (sdslen(o->ptr)) { sds aclop = sdscatprintf(sdsempty(),">%s",(char*)o->ptr); ACLSetUser(DefaultUser,aclop,sdslen(aclop)); sdsfree(aclop); server.requirepass = sdsnew(o->ptr); } else { ACLSetUser(DefaultUser,"nopass",-1); } } config_set_special_field("save") { int vlen, j; sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); /* Perform sanity check before setting the new config: * - Even number of args * - Seconds >= 1, changes >= 0 */ if (vlen & 1) { sdsfreesplitres(v,vlen); goto badfmt; } for (j = 0; j < vlen; j++) { char *eptr; long val; val = strtoll(v[j], &eptr, 10); if (eptr[0] != '\0' || ((j & 1) == 0 && val < 1) || ((j & 1) == 1 && val < 0)) { sdsfreesplitres(v,vlen); goto badfmt; } } /* Finally set the new config */ resetServerSaveParams(); for (j = 0; j < vlen; j += 2) { time_t seconds; int changes; seconds = strtoll(v[j],NULL,10); changes = strtoll(v[j+1],NULL,10); appendServerSaveParams(seconds, changes); } sdsfreesplitres(v,vlen); } config_set_special_field("dir") { if (chdir((char*)o->ptr) == -1) { addReplyErrorFormat(c,"Changing directory: %s", strerror(errno)); return; } } config_set_special_field("client-output-buffer-limit") { int vlen, j; sds *v = sdssplitlen(o->ptr,sdslen(o->ptr)," ",1,&vlen); /* We need a multiple of 4: <class> <hard> <soft> <soft_seconds> */ if (vlen % 4) { sdsfreesplitres(v,vlen); goto badfmt; } /* Sanity check of single arguments, so that we either refuse the * whole configuration string or accept it all, even if a single * error in a single client class is present. */ for (j = 0; j < vlen; j++) { long val; if ((j % 4) == 0) { int class = getClientTypeByName(v[j]); if (class == -1 || class == CLIENT_TYPE_MASTER) { sdsfreesplitres(v,vlen); goto badfmt; } } else { val = memtoll(v[j], &err); if (err || val < 0) { sdsfreesplitres(v,vlen); goto badfmt; } } } /* Finally set the new config */ for (j = 0; j < vlen; j += 4) { int class; unsigned long long hard, soft; int soft_seconds; class = getClientTypeByName(v[j]); hard = memtoll(v[j+1],NULL); soft = memtoll(v[j+2],NULL); soft_seconds = strtoll(v[j+3],NULL,10); server.client_obuf_limits[class].hard_limit_bytes = hard; server.client_obuf_limits[class].soft_limit_bytes = soft; server.client_obuf_limits[class].soft_limit_seconds = soft_seconds; } sdsfreesplitres(v,vlen); } config_set_special_field("oom-score-adj-values") { int vlen; int success = 1; sds *v = sdssplitlen(o->ptr, sdslen(o->ptr), " ", 1, &vlen); if (vlen != CONFIG_OOM_COUNT || updateOOMScoreAdjValues(v, &errstr, 1) == C_ERR) success = 0; sdsfreesplitres(v, vlen); if (!success) goto badfmt; } config_set_special_field("notify-keyspace-events") { int flags = keyspaceEventsStringToFlags(o->ptr); if (flags == -1) goto badfmt; server.notify_keyspace_events = flags; /* Numerical fields. * config_set_numerical_field(name,var,min,max) */ } config_set_numerical_field( "watchdog-period",ll,0,INT_MAX) { if (ll) enableWatchdog(ll); else disableWatchdog(); /* Memory fields. * config_set_memory_field(name,var) */ } config_set_memory_field( "client-query-buffer-limit",server.client_max_querybuf_len) { /* Everything else is an error... */ } config_set_else { addReplyErrorFormat(c,"Unsupported CONFIG parameter: %s", (char*)c->argv[2]->ptr); return; } /* On success we just return a generic OK for all the options. */ addReply(c,shared.ok); return; badfmt: /* Bad format errors */ if (errstr) { addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s' - %s", (char*)o->ptr, (char*)c->argv[2]->ptr, errstr); } else { addReplyErrorFormat(c,"Invalid argument '%s' for CONFIG SET '%s'", (char*)o->ptr, (char*)c->argv[2]->ptr); } } /*----------------------------------------------------------------------------- * CONFIG GET implementation *----------------------------------------------------------------------------*/ #define config_get_string_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,_var ? _var : ""); \ matches++; \ } \ } while(0); #define config_get_bool_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,_var ? "yes" : "no"); \ matches++; \ } \ } while(0); #define config_get_numerical_field(_name,_var) do { \ if (stringmatch(pattern,_name,1)) { \ ll2string(buf,sizeof(buf),_var); \ addReplyBulkCString(c,_name); \ addReplyBulkCString(c,buf); \ matches++; \ } \ } while(0); void configGetCommand(client *c) { robj *o = c->argv[2]; void *replylen = addReplyDeferredLen(c); char *pattern = o->ptr; char buf[128]; int matches = 0; serverAssertWithInfo(c,o,sdsEncodedObject(o)); /* Iterate the configs that are standard */ for (standardConfig *config = configs; config->name != NULL; config++) { if (stringmatch(pattern,config->name,1)) { addReplyBulkCString(c,config->name); config->interface.get(c,config->data); matches++; } if (config->alias && stringmatch(pattern,config->alias,1)) { addReplyBulkCString(c,config->alias); config->interface.get(c,config->data); matches++; } } /* String values */ config_get_string_field("logfile",server.logfile); /* Numerical values */ config_get_numerical_field("client-query-buffer-limit",server.client_max_querybuf_len); config_get_numerical_field("watchdog-period",server.watchdog_period); /* Everything we can't handle with macros follows. */ if (stringmatch(pattern,"dir",1)) { char buf[1024]; if (getcwd(buf,sizeof(buf)) == NULL) buf[0] = '\0'; addReplyBulkCString(c,"dir"); addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"save",1)) { sds buf = sdsempty(); int j; for (j = 0; j < server.saveparamslen; j++) { buf = sdscatprintf(buf,"%jd %d", (intmax_t)server.saveparams[j].seconds, server.saveparams[j].changes); if (j != server.saveparamslen-1) buf = sdscatlen(buf," ",1); } addReplyBulkCString(c,"save"); addReplyBulkCString(c,buf); sdsfree(buf); matches++; } if (stringmatch(pattern,"client-output-buffer-limit",1)) { sds buf = sdsempty(); int j; for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) { buf = sdscatprintf(buf,"%s %llu %llu %ld", getClientTypeName(j), server.client_obuf_limits[j].hard_limit_bytes, server.client_obuf_limits[j].soft_limit_bytes, (long) server.client_obuf_limits[j].soft_limit_seconds); if (j != CLIENT_TYPE_OBUF_COUNT-1) buf = sdscatlen(buf," ",1); } addReplyBulkCString(c,"client-output-buffer-limit"); addReplyBulkCString(c,buf); sdsfree(buf); matches++; } if (stringmatch(pattern,"unixsocketperm",1)) { char buf[32]; snprintf(buf,sizeof(buf),"%o",server.unixsocketperm); addReplyBulkCString(c,"unixsocketperm"); addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"slaveof",1) || stringmatch(pattern,"replicaof",1)) { char *optname = stringmatch(pattern,"slaveof",1) ? "slaveof" : "replicaof"; char buf[256]; addReplyBulkCString(c,optname); if (server.masterhost) snprintf(buf,sizeof(buf),"%s %d", server.masterhost, server.masterport); else buf[0] = '\0'; addReplyBulkCString(c,buf); matches++; } if (stringmatch(pattern,"notify-keyspace-events",1)) { sds flags = keyspaceEventsFlagsToString(server.notify_keyspace_events); addReplyBulkCString(c,"notify-keyspace-events"); addReplyBulkSds(c,flags); matches++; } if (stringmatch(pattern,"bind",1)) { sds aux = sdsjoin(server.bindaddr,server.bindaddr_count," "); addReplyBulkCString(c,"bind"); addReplyBulkCString(c,aux); sdsfree(aux); matches++; } if (stringmatch(pattern,"requirepass",1)) { addReplyBulkCString(c,"requirepass"); sds password = server.requirepass; if (password) { addReplyBulkCBuffer(c,password,sdslen(password)); } else { addReplyBulkCString(c,""); } matches++; } if (stringmatch(pattern,"oom-score-adj-values",0)) { sds buf = sdsempty(); int j; for (j = 0; j < CONFIG_OOM_COUNT; j++) { buf = sdscatprintf(buf,"%d", server.oom_score_adj_values[j]); if (j != CONFIG_OOM_COUNT-1) buf = sdscatlen(buf," ",1); } addReplyBulkCString(c,"oom-score-adj-values"); addReplyBulkCString(c,buf); sdsfree(buf); matches++; } setDeferredMapLen(c,replylen,matches); } /*----------------------------------------------------------------------------- * CONFIG REWRITE implementation *----------------------------------------------------------------------------*/ #define REDIS_CONFIG_REWRITE_SIGNATURE "# Generated by CONFIG REWRITE" /* We use the following dictionary type to store where a configuration * option is mentioned in the old configuration file, so it's * like "maxmemory" -> list of line numbers (first line is zero). */ uint64_t dictSdsCaseHash(const void *key); int dictSdsKeyCaseCompare(void *privdata, const void *key1, const void *key2); void dictSdsDestructor(void *privdata, void *val); void dictListDestructor(void *privdata, void *val); /* Sentinel config rewriting is implemented inside sentinel.c by * rewriteConfigSentinelOption(). */ void rewriteConfigSentinelOption(struct rewriteConfigState *state); dictType optionToLineDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ dictListDestructor /* val destructor */ }; dictType optionSetDictType = { dictSdsCaseHash, /* hash function */ NULL, /* key dup */ NULL, /* val dup */ dictSdsKeyCaseCompare, /* key compare */ dictSdsDestructor, /* key destructor */ NULL /* val destructor */ }; /* The config rewrite state. */ struct rewriteConfigState { dict *option_to_line; /* Option -> list of config file lines map */ dict *rewritten; /* Dictionary of already processed options */ int numlines; /* Number of lines in current config */ sds *lines; /* Current lines as an array of sds strings */ int has_tail; /* True if we already added directives that were not present in the original config file. */ int force_all; /* True if we want all keywords to be force written. Currently only used for testing. */ }; /* Append the new line to the current configuration state. */ void rewriteConfigAppendLine(struct rewriteConfigState *state, sds line) { state->lines = zrealloc(state->lines, sizeof(char*) * (state->numlines+1)); state->lines[state->numlines++] = line; } /* Populate the option -> list of line numbers map. */ void rewriteConfigAddLineNumberToOption(struct rewriteConfigState *state, sds option, int linenum) { list *l = dictFetchValue(state->option_to_line,option); if (l == NULL) { l = listCreate(); dictAdd(state->option_to_line,sdsdup(option),l); } listAddNodeTail(l,(void*)(long)linenum); } /* Add the specified option to the set of processed options. * This is useful as only unused lines of processed options will be blanked * in the config file, while options the rewrite process does not understand * remain untouched. */ void rewriteConfigMarkAsProcessed(struct rewriteConfigState *state, const char *option) { sds opt = sdsnew(option); if (dictAdd(state->rewritten,opt,NULL) != DICT_OK) sdsfree(opt); } /* Read the old file, split it into lines to populate a newly created * config rewrite state, and return it to the caller. * * If it is impossible to read the old file, NULL is returned. * If the old file does not exist at all, an empty state is returned. */ struct rewriteConfigState *rewriteConfigReadOldFile(char *path) { FILE *fp = fopen(path,"r"); if (fp == NULL && errno != ENOENT) return NULL; char buf[CONFIG_MAX_LINE+1]; int linenum = -1; struct rewriteConfigState *state = zmalloc(sizeof(*state)); state->option_to_line = dictCreate(&optionToLineDictType,NULL); state->rewritten = dictCreate(&optionSetDictType,NULL); state->numlines = 0; state->lines = NULL; state->has_tail = 0; state->force_all = 0; if (fp == NULL) return state; /* Read the old file line by line, populate the state. */ while(fgets(buf,CONFIG_MAX_LINE+1,fp) != NULL) { int argc; sds *argv; sds line = sdstrim(sdsnew(buf),"\r\n\t "); linenum++; /* Zero based, so we init at -1 */ /* Handle comments and empty lines. */ if (line[0] == '#' || line[0] == '\0') { if (!state->has_tail && !strcmp(line,REDIS_CONFIG_REWRITE_SIGNATURE)) state->has_tail = 1; rewriteConfigAppendLine(state,line); continue; } /* Not a comment, split into arguments. */ argv = sdssplitargs(line,&argc); if (argv == NULL) { /* Apparently the line is unparsable for some reason, for * instance it may have unbalanced quotes. Load it as a * comment. */ sds aux = sdsnew("# ??? "); aux = sdscatsds(aux,line); sdsfree(line); rewriteConfigAppendLine(state,aux); continue; } sdstolower(argv[0]); /* We only want lowercase config directives. */ /* Now we populate the state according to the content of this line. * Append the line and populate the option -> line numbers map. */ rewriteConfigAppendLine(state,line); /* Translate options using the word "slave" to the corresponding name * "replica", before adding such option to the config name -> lines * mapping. */ char *p = strstr(argv[0],"slave"); if (p) { sds alt = sdsempty(); alt = sdscatlen(alt,argv[0],p-argv[0]);; alt = sdscatlen(alt,"replica",7); alt = sdscatlen(alt,p+5,strlen(p+5)); sdsfree(argv[0]); argv[0] = alt; } rewriteConfigAddLineNumberToOption(state,argv[0],linenum); sdsfreesplitres(argv,argc); } fclose(fp); return state; } /* Rewrite the specified configuration option with the new "line". * It progressively uses lines of the file that were already used for the same * configuration option in the old version of the file, removing that line from * the map of options -> line numbers. * * If there are lines associated with a given configuration option and * "force" is non-zero, the line is appended to the configuration file. * Usually "force" is true when an option has not its default value, so it * must be rewritten even if not present previously. * * The first time a line is appended into a configuration file, a comment * is added to show that starting from that point the config file was generated * by CONFIG REWRITE. * * "line" is either used, or freed, so the caller does not need to free it * in any way. */ void rewriteConfigRewriteLine(struct rewriteConfigState *state, const char *option, sds line, int force) { sds o = sdsnew(option); list *l = dictFetchValue(state->option_to_line,o); rewriteConfigMarkAsProcessed(state,option); if (!l && !force && !state->force_all) { /* Option not used previously, and we are not forced to use it. */ sdsfree(line); sdsfree(o); return; } if (l) { listNode *ln = listFirst(l); int linenum = (long) ln->value; /* There are still lines in the old configuration file we can reuse * for this option. Replace the line with the new one. */ listDelNode(l,ln); if (listLength(l) == 0) dictDelete(state->option_to_line,o); sdsfree(state->lines[linenum]); state->lines[linenum] = line; } else { /* Append a new line. */ if (!state->has_tail) { rewriteConfigAppendLine(state, sdsnew(REDIS_CONFIG_REWRITE_SIGNATURE)); state->has_tail = 1; } rewriteConfigAppendLine(state,line); } sdsfree(o); } /* Write the long long 'bytes' value as a string in a way that is parsable * inside redis.conf. If possible uses the GB, MB, KB notation. */ int rewriteConfigFormatMemory(char *buf, size_t len, long long bytes) { int gb = 1024*1024*1024; int mb = 1024*1024; int kb = 1024; if (bytes && (bytes % gb) == 0) { return snprintf(buf,len,"%lldgb",bytes/gb); } else if (bytes && (bytes % mb) == 0) { return snprintf(buf,len,"%lldmb",bytes/mb); } else if (bytes && (bytes % kb) == 0) { return snprintf(buf,len,"%lldkb",bytes/kb); } else { return snprintf(buf,len,"%lld",bytes); } } /* Rewrite a simple "option-name <bytes>" configuration option. */ void rewriteConfigBytesOption(struct rewriteConfigState *state, const char *option, long long value, long long defvalue) { char buf[64]; int force = value != defvalue; sds line; rewriteConfigFormatMemory(buf,sizeof(buf),value); line = sdscatprintf(sdsempty(),"%s %s",option,buf); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a yes/no option. */ void rewriteConfigYesNoOption(struct rewriteConfigState *state, const char *option, int value, int defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %s",option, value ? "yes" : "no"); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a string option. */ void rewriteConfigStringOption(struct rewriteConfigState *state, const char *option, char *value, const char *defvalue) { int force = 1; sds line; /* String options set to NULL need to be not present at all in the * configuration file to be set to NULL again at the next reboot. */ if (value == NULL) { rewriteConfigMarkAsProcessed(state,option); return; } /* Set force to zero if the value is set to its default. */ if (defvalue && strcmp(value,defvalue) == 0) force = 0; line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatrepr(line, value, strlen(value)); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite a numerical (long long range) option. */ void rewriteConfigNumericalOption(struct rewriteConfigState *state, const char *option, long long value, long long defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %lld",option,value); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite an octal option. */ void rewriteConfigOctalOption(struct rewriteConfigState *state, char *option, int value, int defvalue) { int force = value != defvalue; sds line = sdscatprintf(sdsempty(),"%s %o",option,value); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite an enumeration option. It takes as usually state and option name, * and in addition the enumeration array and the default value for the * option. */ void rewriteConfigEnumOption(struct rewriteConfigState *state, const char *option, int value, configEnum *ce, int defval) { sds line; const char *name = configEnumGetNameOrUnknown(ce,value); int force = value != defval; line = sdscatprintf(sdsempty(),"%s %s",option,name); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the save option. */ void rewriteConfigSaveOption(struct rewriteConfigState *state) { int j; sds line; /* In Sentinel mode we don't need to rewrite the save parameters */ if (server.sentinel_mode) { rewriteConfigMarkAsProcessed(state,"save"); return; } /* Note that if there are no save parameters at all, all the current * config line with "save" will be detected as orphaned and deleted, * resulting into no RDB persistence as expected. */ for (j = 0; j < server.saveparamslen; j++) { line = sdscatprintf(sdsempty(),"save %ld %d", (long) server.saveparams[j].seconds, server.saveparams[j].changes); rewriteConfigRewriteLine(state,"save",line,1); } /* Mark "save" as processed in case server.saveparamslen is zero. */ rewriteConfigMarkAsProcessed(state,"save"); } /* Rewrite the user option. */ void rewriteConfigUserOption(struct rewriteConfigState *state) { /* If there is a user file defined we just mark this configuration * directive as processed, so that all the lines containing users * inside the config file gets discarded. */ if (server.acl_filename[0] != '\0') { rewriteConfigMarkAsProcessed(state,"user"); return; } /* Otherwise scan the list of users and rewrite every line. Note that * in case the list here is empty, the effect will just be to comment * all the users directive inside the config file. */ raxIterator ri; raxStart(&ri,Users); raxSeek(&ri,"^",NULL,0); while(raxNext(&ri)) { user *u = ri.data; sds line = sdsnew("user "); line = sdscatsds(line,u->name); line = sdscatlen(line," ",1); sds descr = ACLDescribeUser(u); line = sdscatsds(line,descr); sdsfree(descr); rewriteConfigRewriteLine(state,"user",line,1); } raxStop(&ri); /* Mark "user" as processed in case there are no defined users. */ rewriteConfigMarkAsProcessed(state,"user"); } /* Rewrite the dir option, always using absolute paths.*/ void rewriteConfigDirOption(struct rewriteConfigState *state) { char cwd[1024]; if (getcwd(cwd,sizeof(cwd)) == NULL) { rewriteConfigMarkAsProcessed(state,"dir"); return; /* no rewrite on error. */ } rewriteConfigStringOption(state,"dir",cwd,NULL); } /* Rewrite the slaveof option. */ void rewriteConfigSlaveofOption(struct rewriteConfigState *state, char *option) { sds line; /* If this is a master, we want all the slaveof config options * in the file to be removed. Note that if this is a cluster instance * we don't want a slaveof directive inside redis.conf. */ if (server.cluster_enabled || server.masterhost == NULL) { rewriteConfigMarkAsProcessed(state,option); return; } line = sdscatprintf(sdsempty(),"%s %s %d", option, server.masterhost, server.masterport); rewriteConfigRewriteLine(state,option,line,1); } /* Rewrite the notify-keyspace-events option. */ void rewriteConfigNotifykeyspaceeventsOption(struct rewriteConfigState *state) { int force = server.notify_keyspace_events != 0; char *option = "notify-keyspace-events"; sds line, flags; flags = keyspaceEventsFlagsToString(server.notify_keyspace_events); line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatrepr(line, flags, sdslen(flags)); sdsfree(flags); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the client-output-buffer-limit option. */ void rewriteConfigClientoutputbufferlimitOption(struct rewriteConfigState *state) { int j; char *option = "client-output-buffer-limit"; for (j = 0; j < CLIENT_TYPE_OBUF_COUNT; j++) { int force = (server.client_obuf_limits[j].hard_limit_bytes != clientBufferLimitsDefaults[j].hard_limit_bytes) || (server.client_obuf_limits[j].soft_limit_bytes != clientBufferLimitsDefaults[j].soft_limit_bytes) || (server.client_obuf_limits[j].soft_limit_seconds != clientBufferLimitsDefaults[j].soft_limit_seconds); sds line; char hard[64], soft[64]; rewriteConfigFormatMemory(hard,sizeof(hard), server.client_obuf_limits[j].hard_limit_bytes); rewriteConfigFormatMemory(soft,sizeof(soft), server.client_obuf_limits[j].soft_limit_bytes); char *typename = getClientTypeName(j); if (!strcmp(typename,"slave")) typename = "replica"; line = sdscatprintf(sdsempty(),"%s %s %s %s %ld", option, typename, hard, soft, (long) server.client_obuf_limits[j].soft_limit_seconds); rewriteConfigRewriteLine(state,option,line,force); } } /* Rewrite the oom-score-adj-values option. */ void rewriteConfigOOMScoreAdjValuesOption(struct rewriteConfigState *state) { int force = 0; int j; char *option = "oom-score-adj-values"; sds line; line = sdsnew(option); line = sdscatlen(line, " ", 1); for (j = 0; j < CONFIG_OOM_COUNT; j++) { if (server.oom_score_adj_values[j] != configOOMScoreAdjValuesDefaults[j]) force = 1; line = sdscatprintf(line, "%d", server.oom_score_adj_values[j]); if (j+1 != CONFIG_OOM_COUNT) line = sdscatlen(line, " ", 1); } rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the bind option. */ void rewriteConfigBindOption(struct rewriteConfigState *state) { int force = 1; sds line, addresses; char *option = "bind"; /* Nothing to rewrite if we don't have bind addresses. */ if (server.bindaddr_count == 0) { rewriteConfigMarkAsProcessed(state,option); return; } /* Rewrite as bind <addr1> <addr2> ... <addrN> */ addresses = sdsjoin(server.bindaddr,server.bindaddr_count," "); line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatsds(line, addresses); sdsfree(addresses); rewriteConfigRewriteLine(state,option,line,force); } /* Rewrite the requirepass option. */ void rewriteConfigRequirepassOption(struct rewriteConfigState *state, char *option) { int force = 1; sds line; sds password = server.requirepass; /* If there is no password set, we don't want the requirepass option * to be present in the configuration at all. */ if (password == NULL) { rewriteConfigMarkAsProcessed(state,option); return; } line = sdsnew(option); line = sdscatlen(line, " ", 1); line = sdscatsds(line, password); rewriteConfigRewriteLine(state,option,line,force); } /* Glue together the configuration lines in the current configuration * rewrite state into a single string, stripping multiple empty lines. */ sds rewriteConfigGetContentFromState(struct rewriteConfigState *state) { sds content = sdsempty(); int j, was_empty = 0; for (j = 0; j < state->numlines; j++) { /* Every cluster of empty lines is turned into a single empty line. */ if (sdslen(state->lines[j]) == 0) { if (was_empty) continue; was_empty = 1; } else { was_empty = 0; } content = sdscatsds(content,state->lines[j]); content = sdscatlen(content,"\n",1); } return content; } /* Free the configuration rewrite state. */ void rewriteConfigReleaseState(struct rewriteConfigState *state) { sdsfreesplitres(state->lines,state->numlines); dictRelease(state->option_to_line); dictRelease(state->rewritten); zfree(state); } /* At the end of the rewrite process the state contains the remaining * map between "option name" => "lines in the original config file". * Lines used by the rewrite process were removed by the function * rewriteConfigRewriteLine(), all the other lines are "orphaned" and * should be replaced by empty lines. * * This function does just this, iterating all the option names and * blanking all the lines still associated. */ void rewriteConfigRemoveOrphaned(struct rewriteConfigState *state) { dictIterator *di = dictGetIterator(state->option_to_line); dictEntry *de; while((de = dictNext(di)) != NULL) { list *l = dictGetVal(de); sds option = dictGetKey(de); /* Don't blank lines about options the rewrite process * don't understand. */ if (dictFind(state->rewritten,option) == NULL) { serverLog(LL_DEBUG,"Not rewritten option: %s", option); continue; } while(listLength(l)) { listNode *ln = listFirst(l); int linenum = (long) ln->value; sdsfree(state->lines[linenum]); state->lines[linenum] = sdsempty(); listDelNode(l,ln); } } dictReleaseIterator(di); } /* This function replaces the old configuration file with the new content * in an atomic manner. * * The function returns 0 on success, otherwise -1 is returned and errno * is set accordingly. */ int rewriteConfigOverwriteFile(char *configfile, sds content) { int fd = -1; int retval = -1; char tmp_conffile[PATH_MAX]; const char *tmp_suffix = ".XXXXXX"; size_t offset = 0; ssize_t written_bytes = 0; int tmp_path_len = snprintf(tmp_conffile, sizeof(tmp_conffile), "%s%s", configfile, tmp_suffix); if (tmp_path_len <= 0 || (unsigned int)tmp_path_len >= sizeof(tmp_conffile)) { serverLog(LL_WARNING, "Config file full path is too long"); errno = ENAMETOOLONG; return retval; } #ifdef _GNU_SOURCE fd = mkostemp(tmp_conffile, O_CLOEXEC); #else /* There's a theoretical chance here to leak the FD if a module thread forks & execv in the middle */ fd = mkstemp(tmp_conffile); #endif if (fd == -1) { serverLog(LL_WARNING, "Could not create tmp config file (%s)", strerror(errno)); return retval; } while (offset < sdslen(content)) { written_bytes = write(fd, content + offset, sdslen(content) - offset); if (written_bytes <= 0) { if (errno == EINTR) continue; /* FD is blocking, no other retryable errors */ serverLog(LL_WARNING, "Failed after writing (%zd) bytes to tmp config file (%s)", offset, strerror(errno)); goto cleanup; } offset+=written_bytes; } if (fsync(fd)) serverLog(LL_WARNING, "Could not sync tmp config file to disk (%s)", strerror(errno)); else if (fchmod(fd, 0644 & ~server.umask) == -1) serverLog(LL_WARNING, "Could not chmod config file (%s)", strerror(errno)); else if (rename(tmp_conffile, configfile) == -1) serverLog(LL_WARNING, "Could not rename tmp config file (%s)", strerror(errno)); else { retval = 0; serverLog(LL_DEBUG, "Rewritten config file (%s) successfully", configfile); } cleanup: close(fd); if (retval) unlink(tmp_conffile); return retval; } /* Rewrite the configuration file at "path". * If the configuration file already exists, we try at best to retain comments * and overall structure. * * Configuration parameters that are at their default value, unless already * explicitly included in the old configuration file, are not rewritten. * The force_all flag overrides this behavior and forces everything to be * written. This is currently only used for testing purposes. * * On error -1 is returned and errno is set accordingly, otherwise 0. */ int rewriteConfig(char *path, int force_all) { struct rewriteConfigState *state; sds newcontent; int retval; /* Step 1: read the old config into our rewrite state. */ if ((state = rewriteConfigReadOldFile(path)) == NULL) return -1; if (force_all) state->force_all = 1; /* Step 2: rewrite every single option, replacing or appending it inside * the rewrite state. */ /* Iterate the configs that are standard */ for (standardConfig *config = configs; config->name != NULL; config++) { config->interface.rewrite(config->data, config->name, state); } rewriteConfigBindOption(state); rewriteConfigOctalOption(state,"unixsocketperm",server.unixsocketperm,CONFIG_DEFAULT_UNIX_SOCKET_PERM); rewriteConfigStringOption(state,"logfile",server.logfile,CONFIG_DEFAULT_LOGFILE); rewriteConfigSaveOption(state); rewriteConfigUserOption(state); rewriteConfigDirOption(state); rewriteConfigSlaveofOption(state,"replicaof"); rewriteConfigRequirepassOption(state,"requirepass"); rewriteConfigBytesOption(state,"client-query-buffer-limit",server.client_max_querybuf_len,PROTO_MAX_QUERYBUF_LEN); rewriteConfigStringOption(state,"cluster-config-file",server.cluster_configfile,CONFIG_DEFAULT_CLUSTER_CONFIG_FILE); rewriteConfigNotifykeyspaceeventsOption(state); rewriteConfigClientoutputbufferlimitOption(state); rewriteConfigOOMScoreAdjValuesOption(state); /* Rewrite Sentinel config if in Sentinel mode. */ if (server.sentinel_mode) rewriteConfigSentinelOption(state); /* Step 3: remove all the orphaned lines in the old file, that is, lines * that were used by a config option and are no longer used, like in case * of multiple "save" options or duplicated options. */ rewriteConfigRemoveOrphaned(state); /* Step 4: generate a new configuration file from the modified state * and write it into the original file. */ newcontent = rewriteConfigGetContentFromState(state); retval = rewriteConfigOverwriteFile(server.configfile,newcontent); sdsfree(newcontent); rewriteConfigReleaseState(state); return retval; } /*----------------------------------------------------------------------------- * Configs that fit one of the major types and require no special handling *----------------------------------------------------------------------------*/ #define LOADBUF_SIZE 256 static char loadbuf[LOADBUF_SIZE]; #define MODIFIABLE_CONFIG 1 #define IMMUTABLE_CONFIG 0 #define embedCommonConfig(config_name, config_alias, is_modifiable) \ .name = (config_name), \ .alias = (config_alias), \ .modifiable = (is_modifiable), #define embedConfigInterface(initfn, setfn, getfn, rewritefn) .interface = { \ .init = (initfn), \ .set = (setfn), \ .get = (getfn), \ .rewrite = (rewritefn) \ }, /* What follows is the generic config types that are supported. To add a new * config with one of these types, add it to the standardConfig table with * the creation macro for each type. * * Each type contains the following: * * A function defining how to load this type on startup. * * A function defining how to update this type on CONFIG SET. * * A function defining how to serialize this type on CONFIG SET. * * A function defining how to rewrite this type on CONFIG REWRITE. * * A Macro defining how to create this type. */ /* Bool Configs */ static void boolConfigInit(typeData data) { *data.yesno.config = data.yesno.default_value; } static int boolConfigSet(typeData data, sds value, int update, char **err) { int yn = yesnotoi(value); if (yn == -1) { *err = "argument must be 'yes' or 'no'"; return 0; } if (data.yesno.is_valid_fn && !data.yesno.is_valid_fn(yn, err)) return 0; int prev = *(data.yesno.config); *(data.yesno.config) = yn; if (update && data.yesno.update_fn && !data.yesno.update_fn(yn, prev, err)) { *(data.yesno.config) = prev; return 0; } return 1; } static void boolConfigGet(client *c, typeData data) { addReplyBulkCString(c, *data.yesno.config ? "yes" : "no"); } static void boolConfigRewrite(typeData data, const char *name, struct rewriteConfigState *state) { rewriteConfigYesNoOption(state, name,*(data.yesno.config), data.yesno.default_value); } #define createBoolConfig(name, alias, modifiable, config_addr, default, is_valid, update) { \ embedCommonConfig(name, alias, modifiable) \ embedConfigInterface(boolConfigInit, boolConfigSet, boolConfigGet, boolConfigRewrite) \ .data.yesno = { \ .config = &(config_addr), \ .default_value = (default), \ .is_valid_fn = (is_valid), \ .update_fn = (update), \ } \ } /* String Configs */ static void stringConfigInit(typeData data) { if (data.string.convert_empty_to_null) { *data.string.config = data.string.default_value ? zstrdup(data.string.default_value) : NULL; } else { *data.string.config = zstrdup(data.string.default_value); } } static int stringConfigSet(typeData data, sds value, int update, char **err) { if (data.string.is_valid_fn && !data.string.is_valid_fn(value, err)) return 0; char *prev = *data.string.config; if (data.string.convert_empty_to_null) { *data.string.config = value[0] ? zstrdup(value) : NULL; } else { *data.string.config = zstrdup(value); } if (update && data.string.update_fn && !data.string.update_fn(*data.string.config, prev, err)) { zfree(*data.string.config); *data.string.config = prev; return 0; } zfree(prev); return 1; } static void stringConfigGet(client *c, typeData data) { addReplyBulkCString(c, *data.string.config ? *data.string.config : ""); } static void stringConfigRewrite(typeData data, const char *name, struct rewriteConfigState *state) { rewriteConfigStringOption(state, name,*(data.string.config), data.string.default_value); } #define ALLOW_EMPTY_STRING 0 #define EMPTY_STRING_IS_NULL 1 #define createStringConfig(name, alias, modifiable, empty_to_null, config_addr, default, is_valid, update) { \ embedCommonConfig(name, alias, modifiable) \ embedConfigInterface(stringConfigInit, stringConfigSet, stringConfigGet, stringConfigRewrite) \ .data.string = { \ .config = &(config_addr), \ .default_value = (default), \ .is_valid_fn = (is_valid), \ .update_fn = (update), \ .convert_empty_to_null = (empty_to_null), \ } \ } /* Enum configs */ static void enumConfigInit(typeData data) { *data.enumd.config = data.enumd.default_value; } static int enumConfigSet(typeData data, sds value, int update, char **err) { int enumval = configEnumGetValue(data.enumd.enum_value, value); if (enumval == INT_MIN) { sds enumerr = sdsnew("argument must be one of the following: "); configEnum *enumNode = data.enumd.enum_value; while(enumNode->name != NULL) { enumerr = sdscatlen(enumerr, enumNode->name, strlen(enumNode->name)); enumerr = sdscatlen(enumerr, ", ", 2); enumNode++; } sdsrange(enumerr,0,-3); /* Remove final ", ". */ strncpy(loadbuf, enumerr, LOADBUF_SIZE); loadbuf[LOADBUF_SIZE - 1] = '\0'; sdsfree(enumerr); *err = loadbuf; return 0; } if (data.enumd.is_valid_fn && !data.enumd.is_valid_fn(enumval, err)) return 0; int prev = *(data.enumd.config); *(data.enumd.config) = enumval; if (update && data.enumd.update_fn && !data.enumd.update_fn(enumval, prev, err)) { *(data.enumd.config) = prev; return 0; } return 1; } static void enumConfigGet(client *c, typeData data) { addReplyBulkCString(c, configEnumGetNameOrUnknown(data.enumd.enum_value,*data.enumd.config)); } static void enumConfigRewrite(typeData data, const char *name, struct rewriteConfigState *state) { rewriteConfigEnumOption(state, name,*(data.enumd.config), data.enumd.enum_value, data.enumd.default_value); } #define createEnumConfig(name, alias, modifiable, enum, config_addr, default, is_valid, update) { \ embedCommonConfig(name, alias, modifiable) \ embedConfigInterface(enumConfigInit, enumConfigSet, enumConfigGet, enumConfigRewrite) \ .data.enumd = { \ .config = &(config_addr), \ .default_value = (default), \ .is_valid_fn = (is_valid), \ .update_fn = (update), \ .enum_value = (enum), \ } \ } /* Gets a 'long long val' and sets it into the union, using a macro to get * compile time type check. */ #define SET_NUMERIC_TYPE(val) \ if (data.numeric.numeric_type == NUMERIC_TYPE_INT) { \ *(data.numeric.config.i) = (int) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_UINT) { \ *(data.numeric.config.ui) = (unsigned int) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_LONG) { \ *(data.numeric.config.l) = (long) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_ULONG) { \ *(data.numeric.config.ul) = (unsigned long) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_LONG_LONG) { \ *(data.numeric.config.ll) = (long long) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_ULONG_LONG) { \ *(data.numeric.config.ull) = (unsigned long long) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_SIZE_T) { \ *(data.numeric.config.st) = (size_t) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_SSIZE_T) { \ *(data.numeric.config.sst) = (ssize_t) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_OFF_T) { \ *(data.numeric.config.ot) = (off_t) val; \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_TIME_T) { \ *(data.numeric.config.tt) = (time_t) val; \ } /* Gets a 'long long val' and sets it with the value from the union, using a * macro to get compile time type check. */ #define GET_NUMERIC_TYPE(val) \ if (data.numeric.numeric_type == NUMERIC_TYPE_INT) { \ val = *(data.numeric.config.i); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_UINT) { \ val = *(data.numeric.config.ui); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_LONG) { \ val = *(data.numeric.config.l); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_ULONG) { \ val = *(data.numeric.config.ul); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_LONG_LONG) { \ val = *(data.numeric.config.ll); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_ULONG_LONG) { \ val = *(data.numeric.config.ull); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_SIZE_T) { \ val = *(data.numeric.config.st); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_SSIZE_T) { \ val = *(data.numeric.config.sst); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_OFF_T) { \ val = *(data.numeric.config.ot); \ } else if (data.numeric.numeric_type == NUMERIC_TYPE_TIME_T) { \ val = *(data.numeric.config.tt); \ } /* Numeric configs */ static void numericConfigInit(typeData data) { SET_NUMERIC_TYPE(data.numeric.default_value) } static int numericBoundaryCheck(typeData data, long long ll, char **err) { if (data.numeric.numeric_type == NUMERIC_TYPE_ULONG_LONG || data.numeric.numeric_type == NUMERIC_TYPE_UINT || data.numeric.numeric_type == NUMERIC_TYPE_SIZE_T) { /* Boundary check for unsigned types */ unsigned long long ull = ll; unsigned long long upper_bound = data.numeric.upper_bound; unsigned long long lower_bound = data.numeric.lower_bound; if (ull > upper_bound || ull < lower_bound) { snprintf(loadbuf, LOADBUF_SIZE, "argument must be between %llu and %llu inclusive", lower_bound, upper_bound); *err = loadbuf; return 0; } } else { /* Boundary check for signed types */ if (ll > data.numeric.upper_bound || ll < data.numeric.lower_bound) { snprintf(loadbuf, LOADBUF_SIZE, "argument must be between %lld and %lld inclusive", data.numeric.lower_bound, data.numeric.upper_bound); *err = loadbuf; return 0; } } return 1; } static int numericConfigSet(typeData data, sds value, int update, char **err) { long long ll, prev = 0; if (data.numeric.is_memory) { int memerr; ll = memtoll(value, &memerr); if (memerr || ll < 0) { *err = "argument must be a memory value"; return 0; } } else { if (!string2ll(value, sdslen(value),&ll)) { *err = "argument couldn't be parsed into an integer" ; return 0; } } if (!numericBoundaryCheck(data, ll, err)) return 0; if (data.numeric.is_valid_fn && !data.numeric.is_valid_fn(ll, err)) return 0; GET_NUMERIC_TYPE(prev) SET_NUMERIC_TYPE(ll) if (update && data.numeric.update_fn && !data.numeric.update_fn(ll, prev, err)) { SET_NUMERIC_TYPE(prev) return 0; } return 1; } static void numericConfigGet(client *c, typeData data) { char buf[128]; long long value = 0; GET_NUMERIC_TYPE(value) ll2string(buf, sizeof(buf), value); addReplyBulkCString(c, buf); } static void numericConfigRewrite(typeData data, const char *name, struct rewriteConfigState *state) { long long value = 0; GET_NUMERIC_TYPE(value) if (data.numeric.is_memory) { rewriteConfigBytesOption(state, name, value, data.numeric.default_value); } else { rewriteConfigNumericalOption(state, name, value, data.numeric.default_value); } } #define INTEGER_CONFIG 0 #define MEMORY_CONFIG 1 #define embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) { \ embedCommonConfig(name, alias, modifiable) \ embedConfigInterface(numericConfigInit, numericConfigSet, numericConfigGet, numericConfigRewrite) \ .data.numeric = { \ .lower_bound = (lower), \ .upper_bound = (upper), \ .default_value = (default), \ .is_valid_fn = (is_valid), \ .update_fn = (update), \ .is_memory = (memory), #define createIntConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_INT, \ .config.i = &(config_addr) \ } \ } #define createUIntConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_UINT, \ .config.ui = &(config_addr) \ } \ } #define createLongConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_LONG, \ .config.l = &(config_addr) \ } \ } #define createULongConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_ULONG, \ .config.ul = &(config_addr) \ } \ } #define createLongLongConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_LONG_LONG, \ .config.ll = &(config_addr) \ } \ } #define createULongLongConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_ULONG_LONG, \ .config.ull = &(config_addr) \ } \ } #define createSizeTConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_SIZE_T, \ .config.st = &(config_addr) \ } \ } #define createSSizeTConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_SSIZE_T, \ .config.sst = &(config_addr) \ } \ } #define createTimeTConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_TIME_T, \ .config.tt = &(config_addr) \ } \ } #define createOffTConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ embedCommonNumericalConfig(name, alias, modifiable, lower, upper, config_addr, default, memory, is_valid, update) \ .numeric_type = NUMERIC_TYPE_OFF_T, \ .config.ot = &(config_addr) \ } \ } static int isValidActiveDefrag(int val, char **err) { #ifndef HAVE_DEFRAG if (val) { *err = "Active defragmentation cannot be enabled: it " "requires a Redis server compiled with a modified Jemalloc " "like the one shipped by default with the Redis source " "distribution"; return 0; } #else UNUSED(val); UNUSED(err); #endif return 1; } static int isValidDBfilename(char *val, char **err) { if (!pathIsBaseName(val)) { *err = "dbfilename can't be a path, just a filename"; return 0; } return 1; } static int isValidAOFfilename(char *val, char **err) { if (!pathIsBaseName(val)) { *err = "appendfilename can't be a path, just a filename"; return 0; } return 1; } static int updateHZ(long long val, long long prev, char **err) { UNUSED(prev); UNUSED(err); /* Hz is more a hint from the user, so we accept values out of range * but cap them to reasonable values. */ server.config_hz = val; if (server.config_hz < CONFIG_MIN_HZ) server.config_hz = CONFIG_MIN_HZ; if (server.config_hz > CONFIG_MAX_HZ) server.config_hz = CONFIG_MAX_HZ; server.hz = server.config_hz; return 1; } static int updateJemallocBgThread(int val, int prev, char **err) { UNUSED(prev); UNUSED(err); set_jemalloc_bg_thread(val); return 1; } static int updateReplBacklogSize(long long val, long long prev, char **err) { /* resizeReplicationBacklog sets server.repl_backlog_size, and relies on * being able to tell when the size changes, so restore prev before calling it. */ UNUSED(err); server.repl_backlog_size = prev; resizeReplicationBacklog(val); return 1; } static int updateMaxmemory(long long val, long long prev, char **err) { UNUSED(prev); UNUSED(err); if (val) { size_t used = zmalloc_used_memory()-freeMemoryGetNotCountedMemory(); if ((unsigned long long)val < used) { serverLog(LL_WARNING,"WARNING: the new maxmemory value set via CONFIG SET (%llu) is smaller than the current memory usage (%zu). This will result in key eviction and/or the inability to accept new write commands depending on the maxmemory-policy.", server.maxmemory, used); } freeMemoryIfNeededAndSafe(); } return 1; } static int updateGoodSlaves(long long val, long long prev, char **err) { UNUSED(val); UNUSED(prev); UNUSED(err); refreshGoodSlavesCount(); return 1; } static int updateAppendonly(int val, int prev, char **err) { UNUSED(prev); if (val == 0 && server.aof_state != AOF_OFF) { stopAppendOnly(); } else if (val && server.aof_state == AOF_OFF) { if (startAppendOnly() == C_ERR) { *err = "Unable to turn on AOF. Check server logs."; return 0; } } return 1; } static int updateMaxclients(long long val, long long prev, char **err) { /* Try to check if the OS is capable of supporting so many FDs. */ if (val > prev) { adjustOpenFilesLimit(); if (server.maxclients != val) { static char msg[128]; sprintf(msg, "The operating system is not able to handle the specified number of clients, try with %d", server.maxclients); *err = msg; if (server.maxclients > prev) { server.maxclients = prev; adjustOpenFilesLimit(); } return 0; } if ((unsigned int) aeGetSetSize(server.el) < server.maxclients + CONFIG_FDSET_INCR) { if (aeResizeSetSize(server.el, server.maxclients + CONFIG_FDSET_INCR) == AE_ERR) { *err = "The event loop API used by Redis is not able to handle the specified number of clients"; return 0; } } } return 1; } static int updateOOMScoreAdj(int val, int prev, char **err) { UNUSED(prev); if (val) { if (setOOMScoreAdj(-1) == C_ERR) { *err = "Failed to set current oom_score_adj. Check server logs."; return 0; } } return 1; } #ifdef USE_OPENSSL static int updateTlsCfg(char *val, char *prev, char **err) { UNUSED(val); UNUSED(prev); UNUSED(err); /* If TLS is enabled, try to configure OpenSSL. */ if ((server.tls_port || server.tls_replication || server.tls_cluster) && tlsConfigure(&server.tls_ctx_config) == C_ERR) { *err = "Unable to update TLS configuration. Check server logs."; return 0; } return 1; } static int updateTlsCfgBool(int val, int prev, char **err) { UNUSED(val); UNUSED(prev); return updateTlsCfg(NULL, NULL, err); } static int updateTlsCfgInt(long long val, long long prev, char **err) { UNUSED(val); UNUSED(prev); return updateTlsCfg(NULL, NULL, err); } #endif /* USE_OPENSSL */ standardConfig configs[] = { /* Bool configs */ createBoolConfig("rdbchecksum", NULL, IMMUTABLE_CONFIG, server.rdb_checksum, 1, NULL, NULL), createBoolConfig("daemonize", NULL, IMMUTABLE_CONFIG, server.daemonize, 0, NULL, NULL), createBoolConfig("io-threads-do-reads", NULL, IMMUTABLE_CONFIG, server.io_threads_do_reads, 0,NULL, NULL), /* Read + parse from threads? */ createBoolConfig("lua-replicate-commands", NULL, MODIFIABLE_CONFIG, server.lua_always_replicate_commands, 1, NULL, NULL), createBoolConfig("always-show-logo", NULL, IMMUTABLE_CONFIG, server.always_show_logo, 0, NULL, NULL), createBoolConfig("protected-mode", NULL, MODIFIABLE_CONFIG, server.protected_mode, 1, NULL, NULL), createBoolConfig("rdbcompression", NULL, MODIFIABLE_CONFIG, server.rdb_compression, 1, NULL, NULL), createBoolConfig("rdb-del-sync-files", NULL, MODIFIABLE_CONFIG, server.rdb_del_sync_files, 0, NULL, NULL), createBoolConfig("activerehashing", NULL, MODIFIABLE_CONFIG, server.activerehashing, 1, NULL, NULL), createBoolConfig("stop-writes-on-bgsave-error", NULL, MODIFIABLE_CONFIG, server.stop_writes_on_bgsave_err, 1, NULL, NULL), createBoolConfig("dynamic-hz", NULL, MODIFIABLE_CONFIG, server.dynamic_hz, 1, NULL, NULL), /* Adapt hz to # of clients.*/ createBoolConfig("lazyfree-lazy-eviction", NULL, MODIFIABLE_CONFIG, server.lazyfree_lazy_eviction, 0, NULL, NULL), createBoolConfig("lazyfree-lazy-expire", NULL, MODIFIABLE_CONFIG, server.lazyfree_lazy_expire, 0, NULL, NULL), createBoolConfig("lazyfree-lazy-server-del", NULL, MODIFIABLE_CONFIG, server.lazyfree_lazy_server_del, 0, NULL, NULL), createBoolConfig("lazyfree-lazy-user-del", NULL, MODIFIABLE_CONFIG, server.lazyfree_lazy_user_del , 0, NULL, NULL), createBoolConfig("repl-disable-tcp-nodelay", NULL, MODIFIABLE_CONFIG, server.repl_disable_tcp_nodelay, 0, NULL, NULL), createBoolConfig("repl-diskless-sync", NULL, MODIFIABLE_CONFIG, server.repl_diskless_sync, 0, NULL, NULL), createBoolConfig("gopher-enabled", NULL, MODIFIABLE_CONFIG, server.gopher_enabled, 0, NULL, NULL), createBoolConfig("aof-rewrite-incremental-fsync", NULL, MODIFIABLE_CONFIG, server.aof_rewrite_incremental_fsync, 1, NULL, NULL), createBoolConfig("no-appendfsync-on-rewrite", NULL, MODIFIABLE_CONFIG, server.aof_no_fsync_on_rewrite, 0, NULL, NULL), createBoolConfig("cluster-require-full-coverage", NULL, MODIFIABLE_CONFIG, server.cluster_require_full_coverage, 1, NULL, NULL), createBoolConfig("rdb-save-incremental-fsync", NULL, MODIFIABLE_CONFIG, server.rdb_save_incremental_fsync, 1, NULL, NULL), createBoolConfig("aof-load-truncated", NULL, MODIFIABLE_CONFIG, server.aof_load_truncated, 1, NULL, NULL), createBoolConfig("aof-use-rdb-preamble", NULL, MODIFIABLE_CONFIG, server.aof_use_rdb_preamble, 1, NULL, NULL), createBoolConfig("cluster-replica-no-failover", "cluster-slave-no-failover", MODIFIABLE_CONFIG, server.cluster_slave_no_failover, 0, NULL, NULL), /* Failover by default. */ createBoolConfig("replica-lazy-flush", "slave-lazy-flush", MODIFIABLE_CONFIG, server.repl_slave_lazy_flush, 0, NULL, NULL), createBoolConfig("replica-serve-stale-data", "slave-serve-stale-data", MODIFIABLE_CONFIG, server.repl_serve_stale_data, 1, NULL, NULL), createBoolConfig("replica-read-only", "slave-read-only", MODIFIABLE_CONFIG, server.repl_slave_ro, 1, NULL, NULL), createBoolConfig("replica-ignore-maxmemory", "slave-ignore-maxmemory", MODIFIABLE_CONFIG, server.repl_slave_ignore_maxmemory, 1, NULL, NULL), createBoolConfig("jemalloc-bg-thread", NULL, MODIFIABLE_CONFIG, server.jemalloc_bg_thread, 1, NULL, updateJemallocBgThread), createBoolConfig("activedefrag", NULL, MODIFIABLE_CONFIG, server.active_defrag_enabled, 0, isValidActiveDefrag, NULL), createBoolConfig("syslog-enabled", NULL, IMMUTABLE_CONFIG, server.syslog_enabled, 0, NULL, NULL), createBoolConfig("cluster-enabled", NULL, IMMUTABLE_CONFIG, server.cluster_enabled, 0, NULL, NULL), createBoolConfig("appendonly", NULL, MODIFIABLE_CONFIG, server.aof_enabled, 0, NULL, updateAppendonly), createBoolConfig("cluster-allow-reads-when-down", NULL, MODIFIABLE_CONFIG, server.cluster_allow_reads_when_down, 0, NULL, NULL), /* String Configs */ createStringConfig("aclfile", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, server.acl_filename, "", NULL, NULL), createStringConfig("unixsocket", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.unixsocket, NULL, NULL, NULL), createStringConfig("pidfile", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.pidfile, NULL, NULL, NULL), createStringConfig("replica-announce-ip", "slave-announce-ip", MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.slave_announce_ip, NULL, NULL, NULL), createStringConfig("masteruser", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.masteruser, NULL, NULL, NULL), createStringConfig("masterauth", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.masterauth, NULL, NULL, NULL), createStringConfig("cluster-announce-ip", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.cluster_announce_ip, NULL, NULL, NULL), createStringConfig("syslog-ident", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, server.syslog_ident, "redis", NULL, NULL), createStringConfig("dbfilename", NULL, MODIFIABLE_CONFIG, ALLOW_EMPTY_STRING, server.rdb_filename, "dump.rdb", isValidDBfilename, NULL), createStringConfig("appendfilename", NULL, IMMUTABLE_CONFIG, ALLOW_EMPTY_STRING, server.aof_filename, "appendonly.aof", isValidAOFfilename, NULL), createStringConfig("server_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.server_cpulist, NULL, NULL, NULL), createStringConfig("bio_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.bio_cpulist, NULL, NULL, NULL), createStringConfig("aof_rewrite_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.aof_rewrite_cpulist, NULL, NULL, NULL), createStringConfig("bgsave_cpulist", NULL, IMMUTABLE_CONFIG, EMPTY_STRING_IS_NULL, server.bgsave_cpulist, NULL, NULL, NULL), createStringConfig("ignore-warnings", NULL, MODIFIABLE_CONFIG, ALLOW_EMPTY_STRING, server.ignore_warnings, "ARM64-COW-BUG", NULL, NULL), /* Enum Configs */ createEnumConfig("supervised", NULL, IMMUTABLE_CONFIG, supervised_mode_enum, server.supervised_mode, SUPERVISED_NONE, NULL, NULL), createEnumConfig("syslog-facility", NULL, IMMUTABLE_CONFIG, syslog_facility_enum, server.syslog_facility, LOG_LOCAL0, NULL, NULL), createEnumConfig("repl-diskless-load", NULL, MODIFIABLE_CONFIG, repl_diskless_load_enum, server.repl_diskless_load, REPL_DISKLESS_LOAD_DISABLED, NULL, NULL), createEnumConfig("loglevel", NULL, MODIFIABLE_CONFIG, loglevel_enum, server.verbosity, LL_NOTICE, NULL, NULL), createEnumConfig("maxmemory-policy", NULL, MODIFIABLE_CONFIG, maxmemory_policy_enum, server.maxmemory_policy, MAXMEMORY_NO_EVICTION, NULL, NULL), createEnumConfig("appendfsync", NULL, MODIFIABLE_CONFIG, aof_fsync_enum, server.aof_fsync, AOF_FSYNC_EVERYSEC, NULL, NULL), createEnumConfig("oom-score-adj", NULL, MODIFIABLE_CONFIG, oom_score_adj_enum, server.oom_score_adj, OOM_SCORE_ADJ_NO, NULL, updateOOMScoreAdj), /* Integer configs */ createIntConfig("databases", NULL, IMMUTABLE_CONFIG, 1, INT_MAX, server.dbnum, 16, INTEGER_CONFIG, NULL, NULL), createIntConfig("port", NULL, IMMUTABLE_CONFIG, 0, 65535, server.port, 6379, INTEGER_CONFIG, NULL, NULL), /* TCP port. */ createIntConfig("io-threads", NULL, IMMUTABLE_CONFIG, 1, 128, server.io_threads_num, 1, INTEGER_CONFIG, NULL, NULL), /* Single threaded by default */ createIntConfig("auto-aof-rewrite-percentage", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.aof_rewrite_perc, 100, INTEGER_CONFIG, NULL, NULL), createIntConfig("cluster-replica-validity-factor", "cluster-slave-validity-factor", MODIFIABLE_CONFIG, 0, INT_MAX, server.cluster_slave_validity_factor, 10, INTEGER_CONFIG, NULL, NULL), /* Slave max data age factor. */ createIntConfig("list-max-ziplist-size", NULL, MODIFIABLE_CONFIG, INT_MIN, INT_MAX, server.list_max_ziplist_size, -2, INTEGER_CONFIG, NULL, NULL), createIntConfig("tcp-keepalive", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.tcpkeepalive, 300, INTEGER_CONFIG, NULL, NULL), createIntConfig("cluster-migration-barrier", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.cluster_migration_barrier, 1, INTEGER_CONFIG, NULL, NULL), createIntConfig("active-defrag-cycle-min", NULL, MODIFIABLE_CONFIG, 1, 99, server.active_defrag_cycle_min, 1, INTEGER_CONFIG, NULL, NULL), /* Default: 1% CPU min (at lower threshold) */ createIntConfig("active-defrag-cycle-max", NULL, MODIFIABLE_CONFIG, 1, 99, server.active_defrag_cycle_max, 25, INTEGER_CONFIG, NULL, NULL), /* Default: 25% CPU max (at upper threshold) */ createIntConfig("active-defrag-threshold-lower", NULL, MODIFIABLE_CONFIG, 0, 1000, server.active_defrag_threshold_lower, 10, INTEGER_CONFIG, NULL, NULL), /* Default: don't defrag when fragmentation is below 10% */ createIntConfig("active-defrag-threshold-upper", NULL, MODIFIABLE_CONFIG, 0, 1000, server.active_defrag_threshold_upper, 100, INTEGER_CONFIG, NULL, NULL), /* Default: maximum defrag force at 100% fragmentation */ createIntConfig("lfu-log-factor", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.lfu_log_factor, 10, INTEGER_CONFIG, NULL, NULL), createIntConfig("lfu-decay-time", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.lfu_decay_time, 1, INTEGER_CONFIG, NULL, NULL), createIntConfig("replica-priority", "slave-priority", MODIFIABLE_CONFIG, 0, INT_MAX, server.slave_priority, 100, INTEGER_CONFIG, NULL, NULL), createIntConfig("repl-diskless-sync-delay", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.repl_diskless_sync_delay, 5, INTEGER_CONFIG, NULL, NULL), createIntConfig("maxmemory-samples", NULL, MODIFIABLE_CONFIG, 1, INT_MAX, server.maxmemory_samples, 5, INTEGER_CONFIG, NULL, NULL), createIntConfig("timeout", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.maxidletime, 0, INTEGER_CONFIG, NULL, NULL), /* Default client timeout: infinite */ createIntConfig("replica-announce-port", "slave-announce-port", MODIFIABLE_CONFIG, 0, 65535, server.slave_announce_port, 0, INTEGER_CONFIG, NULL, NULL), createIntConfig("tcp-backlog", NULL, IMMUTABLE_CONFIG, 0, INT_MAX, server.tcp_backlog, 511, INTEGER_CONFIG, NULL, NULL), /* TCP listen backlog. */ createIntConfig("cluster-announce-bus-port", NULL, MODIFIABLE_CONFIG, 0, 65535, server.cluster_announce_bus_port, 0, INTEGER_CONFIG, NULL, NULL), /* Default: Use +10000 offset. */ createIntConfig("cluster-announce-port", NULL, MODIFIABLE_CONFIG, 0, 65535, server.cluster_announce_port, 0, INTEGER_CONFIG, NULL, NULL), /* Use server.port */ createIntConfig("repl-timeout", NULL, MODIFIABLE_CONFIG, 1, INT_MAX, server.repl_timeout, 60, INTEGER_CONFIG, NULL, NULL), createIntConfig("repl-ping-replica-period", "repl-ping-slave-period", MODIFIABLE_CONFIG, 1, INT_MAX, server.repl_ping_slave_period, 10, INTEGER_CONFIG, NULL, NULL), createIntConfig("list-compress-depth", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.list_compress_depth, 0, INTEGER_CONFIG, NULL, NULL), createIntConfig("rdb-key-save-delay", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.rdb_key_save_delay, 0, INTEGER_CONFIG, NULL, NULL), createIntConfig("key-load-delay", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.key_load_delay, 0, INTEGER_CONFIG, NULL, NULL), createIntConfig("active-expire-effort", NULL, MODIFIABLE_CONFIG, 1, 10, server.active_expire_effort, 1, INTEGER_CONFIG, NULL, NULL), /* From 1 to 10. */ createIntConfig("hz", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.config_hz, CONFIG_DEFAULT_HZ, INTEGER_CONFIG, NULL, updateHZ), createIntConfig("min-replicas-to-write", "min-slaves-to-write", MODIFIABLE_CONFIG, 0, INT_MAX, server.repl_min_slaves_to_write, 0, INTEGER_CONFIG, NULL, updateGoodSlaves), createIntConfig("min-replicas-max-lag", "min-slaves-max-lag", MODIFIABLE_CONFIG, 0, INT_MAX, server.repl_min_slaves_max_lag, 10, INTEGER_CONFIG, NULL, updateGoodSlaves), /* Unsigned int configs */ createUIntConfig("maxclients", NULL, MODIFIABLE_CONFIG, 1, UINT_MAX, server.maxclients, 10000, INTEGER_CONFIG, NULL, updateMaxclients), /* Unsigned Long configs */ createULongConfig("active-defrag-max-scan-fields", NULL, MODIFIABLE_CONFIG, 1, LONG_MAX, server.active_defrag_max_scan_fields, 1000, INTEGER_CONFIG, NULL, NULL), /* Default: keys with more than 1000 fields will be processed separately */ createULongConfig("slowlog-max-len", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.slowlog_max_len, 128, INTEGER_CONFIG, NULL, NULL), createULongConfig("acllog-max-len", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.acllog_max_len, 128, INTEGER_CONFIG, NULL, NULL), /* Long Long configs */ createLongLongConfig("lua-time-limit", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.lua_time_limit, 5000, INTEGER_CONFIG, NULL, NULL),/* milliseconds */ createLongLongConfig("cluster-node-timeout", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, server.cluster_node_timeout, 15000, INTEGER_CONFIG, NULL, NULL), createLongLongConfig("slowlog-log-slower-than", NULL, MODIFIABLE_CONFIG, -1, LLONG_MAX, server.slowlog_log_slower_than, 10000, INTEGER_CONFIG, NULL, NULL), createLongLongConfig("latency-monitor-threshold", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, server.latency_monitor_threshold, 0, INTEGER_CONFIG, NULL, NULL), createLongLongConfig("proto-max-bulk-len", NULL, MODIFIABLE_CONFIG, 1024*1024, LONG_MAX, server.proto_max_bulk_len, 512ll*1024*1024, MEMORY_CONFIG, NULL, NULL), /* Bulk request max size */ createLongLongConfig("stream-node-max-entries", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, server.stream_node_max_entries, 100, INTEGER_CONFIG, NULL, NULL), createLongLongConfig("repl-backlog-size", NULL, MODIFIABLE_CONFIG, 1, LLONG_MAX, server.repl_backlog_size, 1024*1024, MEMORY_CONFIG, NULL, updateReplBacklogSize), /* Default: 1mb */ /* Unsigned Long Long configs */ createULongLongConfig("maxmemory", NULL, MODIFIABLE_CONFIG, 0, ULLONG_MAX, server.maxmemory, 0, MEMORY_CONFIG, NULL, updateMaxmemory), /* Size_t configs */ createSizeTConfig("hash-max-ziplist-entries", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.hash_max_ziplist_entries, 512, INTEGER_CONFIG, NULL, NULL), createSizeTConfig("set-max-intset-entries", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.set_max_intset_entries, 512, INTEGER_CONFIG, NULL, NULL), createSizeTConfig("zset-max-ziplist-entries", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.zset_max_ziplist_entries, 128, INTEGER_CONFIG, NULL, NULL), createSizeTConfig("active-defrag-ignore-bytes", NULL, MODIFIABLE_CONFIG, 1, LLONG_MAX, server.active_defrag_ignore_bytes, 100<<20, MEMORY_CONFIG, NULL, NULL), /* Default: don't defrag if frag overhead is below 100mb */ createSizeTConfig("hash-max-ziplist-value", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.hash_max_ziplist_value, 64, MEMORY_CONFIG, NULL, NULL), createSizeTConfig("stream-node-max-bytes", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.stream_node_max_bytes, 4096, MEMORY_CONFIG, NULL, NULL), createSizeTConfig("zset-max-ziplist-value", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.zset_max_ziplist_value, 64, MEMORY_CONFIG, NULL, NULL), createSizeTConfig("hll-sparse-max-bytes", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.hll_sparse_max_bytes, 3000, MEMORY_CONFIG, NULL, NULL), createSizeTConfig("tracking-table-max-keys", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.tracking_table_max_keys, 1000000, INTEGER_CONFIG, NULL, NULL), /* Default: 1 million keys max. */ /* Other configs */ createTimeTConfig("repl-backlog-ttl", NULL, MODIFIABLE_CONFIG, 0, LONG_MAX, server.repl_backlog_time_limit, 60*60, INTEGER_CONFIG, NULL, NULL), /* Default: 1 hour */ createOffTConfig("auto-aof-rewrite-min-size", NULL, MODIFIABLE_CONFIG, 0, LLONG_MAX, server.aof_rewrite_min_size, 64*1024*1024, MEMORY_CONFIG, NULL, NULL), #ifdef USE_OPENSSL createIntConfig("tls-port", NULL, IMMUTABLE_CONFIG, 0, 65535, server.tls_port, 0, INTEGER_CONFIG, NULL, updateTlsCfgInt), /* TCP port. */ createIntConfig("tls-session-cache-size", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.tls_ctx_config.session_cache_size, 20*1024, INTEGER_CONFIG, NULL, updateTlsCfgInt), createIntConfig("tls-session-cache-timeout", NULL, MODIFIABLE_CONFIG, 0, INT_MAX, server.tls_ctx_config.session_cache_timeout, 300, INTEGER_CONFIG, NULL, updateTlsCfgInt), createBoolConfig("tls-cluster", NULL, MODIFIABLE_CONFIG, server.tls_cluster, 0, NULL, updateTlsCfgBool), createBoolConfig("tls-replication", NULL, MODIFIABLE_CONFIG, server.tls_replication, 0, NULL, updateTlsCfgBool), createEnumConfig("tls-auth-clients", NULL, MODIFIABLE_CONFIG, tls_auth_clients_enum, server.tls_auth_clients, TLS_CLIENT_AUTH_YES, NULL, NULL), createBoolConfig("tls-prefer-server-ciphers", NULL, MODIFIABLE_CONFIG, server.tls_ctx_config.prefer_server_ciphers, 0, NULL, updateTlsCfgBool), createBoolConfig("tls-session-caching", NULL, MODIFIABLE_CONFIG, server.tls_ctx_config.session_caching, 1, NULL, updateTlsCfgBool), createStringConfig("tls-cert-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.cert_file, NULL, NULL, updateTlsCfg), createStringConfig("tls-key-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.key_file, NULL, NULL, updateTlsCfg), createStringConfig("tls-dh-params-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.dh_params_file, NULL, NULL, updateTlsCfg), createStringConfig("tls-ca-cert-file", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.ca_cert_file, NULL, NULL, updateTlsCfg), createStringConfig("tls-ca-cert-dir", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.ca_cert_dir, NULL, NULL, updateTlsCfg), createStringConfig("tls-protocols", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.protocols, NULL, NULL, updateTlsCfg), createStringConfig("tls-ciphers", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.ciphers, NULL, NULL, updateTlsCfg), createStringConfig("tls-ciphersuites", NULL, MODIFIABLE_CONFIG, EMPTY_STRING_IS_NULL, server.tls_ctx_config.ciphersuites, NULL, NULL, updateTlsCfg), #endif /* NULL Terminator */ {NULL} }; /*----------------------------------------------------------------------------- * CONFIG command entry point *----------------------------------------------------------------------------*/ void configCommand(client *c) { /* Only allow CONFIG GET while loading. */ if (server.loading && strcasecmp(c->argv[1]->ptr,"get")) { addReplyError(c,"Only CONFIG GET is allowed during loading"); return; } if (c->argc == 2 && !strcasecmp(c->argv[1]->ptr,"help")) { const char *help[] = { "GET <pattern> -- Return parameters matching the glob-like <pattern> and their values.", "SET <parameter> <value> -- Set parameter to value.", "RESETSTAT -- Reset statistics reported by INFO.", "REWRITE -- Rewrite the configuration file.", NULL }; addReplyHelp(c, help); } else if (!strcasecmp(c->argv[1]->ptr,"set") && c->argc == 4) { configSetCommand(c); } else if (!strcasecmp(c->argv[1]->ptr,"get") && c->argc == 3) { configGetCommand(c); } else if (!strcasecmp(c->argv[1]->ptr,"resetstat") && c->argc == 2) { resetServerStats(); resetCommandTableStats(); addReply(c,shared.ok); } else if (!strcasecmp(c->argv[1]->ptr,"rewrite") && c->argc == 2) { if (server.configfile == NULL) { addReplyError(c,"The server is running without a config file"); return; } if (rewriteConfig(server.configfile, 0) == -1) { serverLog(LL_WARNING,"CONFIG REWRITE failed: %s", strerror(errno)); addReplyErrorFormat(c,"Rewriting config file: %s", strerror(errno)); } else { serverLog(LL_WARNING,"CONFIG REWRITE executed with success."); addReply(c,shared.ok); } } else { addReplySubcommandSyntaxError(c); return; } }
./CrossVul/dataset_final_sorted/CWE-190/c/good_1943_0
crossvul-cpp_data_bad_5169_0
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2015 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Authors: Sascha Schumann <sascha@schumann.cx> | | Derick Rethans <derick@derickrethans.nl> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #if HAVE_LIBMCRYPT #if PHP_WIN32 # include "win32/winutil.h" #endif #include "php_mcrypt.h" #include "fcntl.h" #define NON_FREE #define MCRYPT2 #include "mcrypt.h" #include "php_ini.h" #include "php_globals.h" #include "ext/standard/info.h" #include "ext/standard/php_rand.h" #include "php_mcrypt_filter.h" static int le_mcrypt; typedef struct _php_mcrypt { MCRYPT td; zend_bool init; } php_mcrypt; /* {{{ arginfo */ ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_open, 0, 0, 4) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, cipher_directory) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, mode_directory) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic_init, 0, 0, 3) ZEND_ARG_INFO(0, td) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic, 0, 0, 2) ZEND_ARG_INFO(0, td) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mdecrypt_generic, 0, 0, 2) ZEND_ARG_INFO(0, td) ZEND_ARG_INFO(0, data) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_supported_key_sizes, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_self_test, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_close, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic_deinit, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_algorithm_mode, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_algorithm, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_mode, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_block_size, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_key_size, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_iv_size, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_algorithms_name, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_modes_name, 0, 0, 1) ZEND_ARG_INFO(0, td) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_self_test, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_algorithm_mode, 0, 0, 1) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_algorithm, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_mode, 0, 0, 1) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_algo_block_size, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_algo_key_size, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_supported_key_sizes, 0, 0, 1) ZEND_ARG_INFO(0, algorithm) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_list_algorithms, 0, 0, 0) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_list_modes, 0, 0, 0) ZEND_ARG_INFO(0, lib_dir) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_key_size, 0, 0, 2) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, module) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_block_size, 0, 0, 2) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, module) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_iv_size, 0, 0, 2) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, module) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_cipher_name, 0, 0, 1) ZEND_ARG_INFO(0, cipher) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_encrypt, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_decrypt, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_ecb, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_cbc, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_cfb, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_ofb, 0, 0, 5) ZEND_ARG_INFO(0, cipher) ZEND_ARG_INFO(0, key) ZEND_ARG_INFO(0, data) ZEND_ARG_INFO(0, mode) ZEND_ARG_INFO(0, iv) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_create_iv, 0, 0, 2) ZEND_ARG_INFO(0, size) ZEND_ARG_INFO(0, source) ZEND_END_ARG_INFO() /* }}} */ const zend_function_entry mcrypt_functions[] = { /* {{{ */ PHP_DEP_FE(mcrypt_ecb, arginfo_mcrypt_ecb) PHP_DEP_FE(mcrypt_cbc, arginfo_mcrypt_cbc) PHP_DEP_FE(mcrypt_cfb, arginfo_mcrypt_cfb) PHP_DEP_FE(mcrypt_ofb, arginfo_mcrypt_ofb) PHP_FE(mcrypt_get_key_size, arginfo_mcrypt_get_key_size) PHP_FE(mcrypt_get_block_size, arginfo_mcrypt_get_block_size) PHP_FE(mcrypt_get_cipher_name, arginfo_mcrypt_get_cipher_name) PHP_FE(mcrypt_create_iv, arginfo_mcrypt_create_iv) PHP_FE(mcrypt_list_algorithms, arginfo_mcrypt_list_algorithms) PHP_FE(mcrypt_list_modes, arginfo_mcrypt_list_modes) PHP_FE(mcrypt_get_iv_size, arginfo_mcrypt_get_iv_size) PHP_FE(mcrypt_encrypt, arginfo_mcrypt_encrypt) PHP_FE(mcrypt_decrypt, arginfo_mcrypt_decrypt) PHP_FE(mcrypt_module_open, arginfo_mcrypt_module_open) PHP_FE(mcrypt_generic_init, arginfo_mcrypt_generic_init) PHP_FE(mcrypt_generic, arginfo_mcrypt_generic) PHP_FE(mdecrypt_generic, arginfo_mdecrypt_generic) PHP_DEP_FALIAS(mcrypt_generic_end, mcrypt_generic_deinit, arginfo_mcrypt_generic_deinit) PHP_FE(mcrypt_generic_deinit, arginfo_mcrypt_generic_deinit) PHP_FE(mcrypt_enc_self_test, arginfo_mcrypt_enc_self_test) PHP_FE(mcrypt_enc_is_block_algorithm_mode, arginfo_mcrypt_enc_is_block_algorithm_mode) PHP_FE(mcrypt_enc_is_block_algorithm, arginfo_mcrypt_enc_is_block_algorithm) PHP_FE(mcrypt_enc_is_block_mode, arginfo_mcrypt_enc_is_block_mode) PHP_FE(mcrypt_enc_get_block_size, arginfo_mcrypt_enc_get_block_size) PHP_FE(mcrypt_enc_get_key_size, arginfo_mcrypt_enc_get_key_size) PHP_FE(mcrypt_enc_get_supported_key_sizes, arginfo_mcrypt_enc_get_supported_key_sizes) PHP_FE(mcrypt_enc_get_iv_size, arginfo_mcrypt_enc_get_iv_size) PHP_FE(mcrypt_enc_get_algorithms_name, arginfo_mcrypt_enc_get_algorithms_name) PHP_FE(mcrypt_enc_get_modes_name, arginfo_mcrypt_enc_get_modes_name) PHP_FE(mcrypt_module_self_test, arginfo_mcrypt_module_self_test) PHP_FE(mcrypt_module_is_block_algorithm_mode, arginfo_mcrypt_module_is_block_algorithm_mode) PHP_FE(mcrypt_module_is_block_algorithm, arginfo_mcrypt_module_is_block_algorithm) PHP_FE(mcrypt_module_is_block_mode, arginfo_mcrypt_module_is_block_mode) PHP_FE(mcrypt_module_get_algo_block_size, arginfo_mcrypt_module_get_algo_block_size) PHP_FE(mcrypt_module_get_algo_key_size, arginfo_mcrypt_module_get_algo_key_size) PHP_FE(mcrypt_module_get_supported_key_sizes, arginfo_mcrypt_module_get_supported_key_sizes) PHP_FE(mcrypt_module_close, arginfo_mcrypt_module_close) PHP_FE_END }; /* }}} */ static PHP_MINFO_FUNCTION(mcrypt); static PHP_MINIT_FUNCTION(mcrypt); static PHP_MSHUTDOWN_FUNCTION(mcrypt); ZEND_DECLARE_MODULE_GLOBALS(mcrypt) zend_module_entry mcrypt_module_entry = { STANDARD_MODULE_HEADER, "mcrypt", mcrypt_functions, PHP_MINIT(mcrypt), PHP_MSHUTDOWN(mcrypt), NULL, NULL, PHP_MINFO(mcrypt), NO_VERSION_YET, PHP_MODULE_GLOBALS(mcrypt), NULL, NULL, NULL, STANDARD_MODULE_PROPERTIES_EX }; #ifdef COMPILE_DL_MCRYPT ZEND_GET_MODULE(mcrypt) #endif #define MCRYPT_ARGS2 \ zval **cipher, **data, **key, **mode; \ int td; \ char *ndata; \ size_t bsize; \ size_t nr; \ size_t nsize #define MCRYPT_ARGS \ MCRYPT_ARGS2; \ zval **iv #define MCRYPT_SIZE \ bsize = mcrypt_get_block_size(Z_LVAL_PP(cipher)); \ nr = (Z_STRLEN_PP(data) + bsize - 1) / bsize; \ nsize = nr * bsize #define MCRYPT_CHECK_TD_CPY \ if (td < 0) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_FAILED); \ RETURN_FALSE; \ } \ ndata = ecalloc(nr, bsize); \ memcpy(ndata, Z_STRVAL_PP(data), Z_STRLEN_PP(data)) #define MCRYPT_CHECK_IV \ convert_to_string_ex(iv); \ if (Z_STRLEN_PP(iv) != bsize) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE); \ RETURN_FALSE; \ } #define MCRYPT_ACTION(x) \ if (Z_LVAL_PP(mode) == 0) { \ mcrypt_##x(td, ndata, nsize); \ } else { \ mdecrypt_##x(td, ndata, nsize); \ } \ end_mcrypt_##x(td) #define MCRYPT_IV_WRONG_SIZE "The IV parameter must be as long as the blocksize" #define MCRYPT_ENCRYPT 0 #define MCRYPT_DECRYPT 1 #define MCRYPT_GET_INI \ cipher_dir_string = MCG(algorithms_dir); \ module_dir_string = MCG(modes_dir); /* * #warning is not ANSI C * #warning Invalidate resource if the param count is wrong, or other problems * #warning occurred during functions. */ #define MCRYPT_GET_CRYPT_ARGS \ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sssZ|s", \ &cipher, &cipher_len, &key, &key_len, &data, &data_len, &mode, &iv, &iv_len) == FAILURE) { \ return; \ } #define MCRYPT_GET_TD_ARG \ zval *mcryptind; \ php_mcrypt *pm; \ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &mcryptind) == FAILURE) { \ return; \ } \ ZEND_FETCH_RESOURCE (pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); #define MCRYPT_GET_MODE_DIR_ARGS(DIRECTORY) \ char *dir = NULL; \ int dir_len; \ char *module; \ int module_len; \ if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, \ "s|s", &module, &module_len, &dir, &dir_len) == FAILURE) { \ return; \ } #define MCRYPT_OPEN_MODULE_FAILED "Module initialization failed" #define MCRYPT_ENTRY2_2_4(a,b) REGISTER_STRING_CONSTANT("MCRYPT_" #a, b, CONST_PERSISTENT) #define MCRYPT_ENTRY2_4(a) MCRYPT_ENTRY_NAMED(a, a) #define PHP_MCRYPT_INIT_CHECK \ if (!pm->init) { \ php_error_docref(NULL TSRMLS_CC, E_WARNING, "Operation disallowed prior to mcrypt_generic_init()."); \ RETURN_FALSE; \ } \ PHP_INI_BEGIN() STD_PHP_INI_ENTRY("mcrypt.algorithms_dir", NULL, PHP_INI_ALL, OnUpdateString, algorithms_dir, zend_mcrypt_globals, mcrypt_globals) STD_PHP_INI_ENTRY("mcrypt.modes_dir", NULL, PHP_INI_ALL, OnUpdateString, modes_dir, zend_mcrypt_globals, mcrypt_globals) PHP_INI_END() static void php_mcrypt_module_dtor(zend_rsrc_list_entry *rsrc TSRMLS_DC) /* {{{ */ { php_mcrypt *pm = (php_mcrypt *) rsrc->ptr; if (pm) { mcrypt_generic_deinit(pm->td); mcrypt_module_close(pm->td); efree(pm); pm = NULL; } } /* }}} */ typedef enum { RANDOM = 0, URANDOM, RAND } iv_source; static PHP_MINIT_FUNCTION(mcrypt) /* {{{ */ { le_mcrypt = zend_register_list_destructors_ex(php_mcrypt_module_dtor, NULL, "mcrypt", module_number); /* modes for mcrypt_??? routines */ REGISTER_LONG_CONSTANT("MCRYPT_ENCRYPT", 0, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("MCRYPT_DECRYPT", 1, CONST_PERSISTENT); /* sources for mcrypt_create_iv */ REGISTER_LONG_CONSTANT("MCRYPT_DEV_RANDOM", 0, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("MCRYPT_DEV_URANDOM", 1, CONST_PERSISTENT); REGISTER_LONG_CONSTANT("MCRYPT_RAND", 2, CONST_PERSISTENT); /* ciphers */ MCRYPT_ENTRY2_2_4(3DES, "tripledes"); MCRYPT_ENTRY2_2_4(ARCFOUR_IV, "arcfour-iv"); MCRYPT_ENTRY2_2_4(ARCFOUR, "arcfour"); MCRYPT_ENTRY2_2_4(BLOWFISH, "blowfish"); MCRYPT_ENTRY2_2_4(BLOWFISH_COMPAT, "blowfish-compat"); MCRYPT_ENTRY2_2_4(CAST_128, "cast-128"); MCRYPT_ENTRY2_2_4(CAST_256, "cast-256"); MCRYPT_ENTRY2_2_4(CRYPT, "crypt"); MCRYPT_ENTRY2_2_4(DES, "des"); MCRYPT_ENTRY2_2_4(ENIGNA, "crypt"); MCRYPT_ENTRY2_2_4(GOST, "gost"); MCRYPT_ENTRY2_2_4(LOKI97, "loki97"); MCRYPT_ENTRY2_2_4(PANAMA, "panama"); MCRYPT_ENTRY2_2_4(RC2, "rc2"); MCRYPT_ENTRY2_2_4(RIJNDAEL_128, "rijndael-128"); MCRYPT_ENTRY2_2_4(RIJNDAEL_192, "rijndael-192"); MCRYPT_ENTRY2_2_4(RIJNDAEL_256, "rijndael-256"); MCRYPT_ENTRY2_2_4(SAFER64, "safer-sk64"); MCRYPT_ENTRY2_2_4(SAFER128, "safer-sk128"); MCRYPT_ENTRY2_2_4(SAFERPLUS, "saferplus"); MCRYPT_ENTRY2_2_4(SERPENT, "serpent"); MCRYPT_ENTRY2_2_4(THREEWAY, "threeway"); MCRYPT_ENTRY2_2_4(TRIPLEDES, "tripledes"); MCRYPT_ENTRY2_2_4(TWOFISH, "twofish"); MCRYPT_ENTRY2_2_4(WAKE, "wake"); MCRYPT_ENTRY2_2_4(XTEA, "xtea"); MCRYPT_ENTRY2_2_4(IDEA, "idea"); MCRYPT_ENTRY2_2_4(MARS, "mars"); MCRYPT_ENTRY2_2_4(RC6, "rc6"); MCRYPT_ENTRY2_2_4(SKIPJACK, "skipjack"); /* modes */ MCRYPT_ENTRY2_2_4(MODE_CBC, "cbc"); MCRYPT_ENTRY2_2_4(MODE_CFB, "cfb"); MCRYPT_ENTRY2_2_4(MODE_ECB, "ecb"); MCRYPT_ENTRY2_2_4(MODE_NOFB, "nofb"); MCRYPT_ENTRY2_2_4(MODE_OFB, "ofb"); MCRYPT_ENTRY2_2_4(MODE_STREAM, "stream"); REGISTER_INI_ENTRIES(); php_stream_filter_register_factory("mcrypt.*", &php_mcrypt_filter_factory TSRMLS_CC); php_stream_filter_register_factory("mdecrypt.*", &php_mcrypt_filter_factory TSRMLS_CC); MCG(fd[RANDOM]) = -1; MCG(fd[URANDOM]) = -1; return SUCCESS; } /* }}} */ static PHP_MSHUTDOWN_FUNCTION(mcrypt) /* {{{ */ { php_stream_filter_unregister_factory("mcrypt.*" TSRMLS_CC); php_stream_filter_unregister_factory("mdecrypt.*" TSRMLS_CC); if (MCG(fd[RANDOM]) > 0) { close(MCG(fd[RANDOM])); } if (MCG(fd[URANDOM]) > 0) { close(MCG(fd[URANDOM])); } UNREGISTER_INI_ENTRIES(); return SUCCESS; } /* }}} */ #include "ext/standard/php_smart_str.h" PHP_MINFO_FUNCTION(mcrypt) /* {{{ */ { char **modules; char mcrypt_api_no[16]; int i, count; smart_str tmp1 = {0}; smart_str tmp2 = {0}; modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count); if (count == 0) { smart_str_appends(&tmp1, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp1, modules[i]); smart_str_appendc(&tmp1, ' '); } smart_str_0(&tmp1); mcrypt_free_p(modules, count); modules = mcrypt_list_modes(MCG(modes_dir), &count); if (count == 0) { smart_str_appends(&tmp2, "none"); } for (i = 0; i < count; i++) { smart_str_appends(&tmp2, modules[i]); smart_str_appendc(&tmp2, ' '); } smart_str_0 (&tmp2); mcrypt_free_p (modules, count); snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION); php_info_print_table_start(); php_info_print_table_header(2, "mcrypt support", "enabled"); php_info_print_table_header(2, "mcrypt_filter support", "enabled"); php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION); php_info_print_table_row(2, "Api No", mcrypt_api_no); php_info_print_table_row(2, "Supported ciphers", tmp1.c); php_info_print_table_row(2, "Supported modes", tmp2.c); smart_str_free(&tmp1); smart_str_free(&tmp2); php_info_print_table_end(); DISPLAY_INI_ENTRIES(); } /* }}} */ /* {{{ proto resource mcrypt_module_open(string cipher, string cipher_directory, string mode, string mode_directory) Opens the module of the algorithm and the mode to be used */ PHP_FUNCTION(mcrypt_module_open) { char *cipher, *cipher_dir; char *mode, *mode_dir; int cipher_len, cipher_dir_len; int mode_len, mode_dir_len; MCRYPT td; php_mcrypt *pm; if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &cipher, &cipher_len, &cipher_dir, &cipher_dir_len, &mode, &mode_len, &mode_dir, &mode_dir_len)) { return; } td = mcrypt_module_open ( cipher, cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir), mode, mode_dir_len > 0 ? mode_dir : MCG(modes_dir) ); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module"); RETURN_FALSE; } else { pm = emalloc(sizeof(php_mcrypt)); pm->td = td; pm->init = 0; ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt); } } /* }}} */ /* {{{ proto int mcrypt_generic_init(resource td, string key, string iv) This function initializes all buffers for the specific module */ PHP_FUNCTION(mcrypt_generic_init) { char *key, *iv; int key_len, iv_len; zval *mcryptind; unsigned char *key_s, *iv_s; int max_key_size, key_size, iv_size; php_mcrypt *pm; int result = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); max_key_size = mcrypt_enc_get_key_size(pm->td); iv_size = mcrypt_enc_get_iv_size(pm->td); if (key_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0"); } key_s = emalloc(key_len); memset(key_s, 0, key_len); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); if (key_len > max_key_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size); key_size = max_key_size; } else { key_size = key_len; } memcpy(key_s, key, key_len); if (iv_len != iv_size) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size); if (iv_len > iv_size) { iv_len = iv_size; } } memcpy(iv_s, iv, iv_len); mcrypt_generic_deinit(pm->td); result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s); /* If this function fails, close the mcrypt module to prevent crashes * when further functions want to access this resource */ if (result < 0) { zend_list_delete(Z_LVAL_P(mcryptind)); switch (result) { case -3: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect"); break; case -4: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error"); break; case -1: default: php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error"); break; } } else { pm->init = 1; } RETVAL_LONG(result); efree(iv_s); efree(key_s); } /* }}} */ /* {{{ proto string mcrypt_generic(resource td, string data) This function encrypts the plaintext */ PHP_FUNCTION(mcrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; unsigned char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt *, &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mcrypt_generic(pm->td, data_s, data_size); data_s[data_size] = '\0'; RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } /* }}} */ /* {{{ proto string mdecrypt_generic(resource td, string data) This function decrypts the plaintext */ PHP_FUNCTION(mdecrypt_generic) { zval *mcryptind; char *data; int data_len; php_mcrypt *pm; char* data_s; int block_size, data_size; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) { return; } ZEND_FETCH_RESOURCE(pm, php_mcrypt * , &mcryptind, -1, "MCrypt", le_mcrypt); PHP_MCRYPT_INIT_CHECK if (data_len == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed"); RETURN_FALSE } /* Check blocksize */ if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(pm->td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size + 1); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } mdecrypt_generic(pm->td, data_s, data_size); RETVAL_STRINGL(data_s, data_size, 1); efree(data_s); } /* }}} */ /* {{{ proto array mcrypt_enc_get_supported_key_sizes(resource td) This function decrypts the crypttext */ PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_TD_ARG array_init(return_value); key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } /* }}} */ /* {{{ proto int mcrypt_enc_self_test(resource td) This function runs the self test on the algorithm specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_self_test) { MCRYPT_GET_TD_ARG RETURN_LONG(mcrypt_enc_self_test(pm->td)); } /* }}} */ /* {{{ proto bool mcrypt_module_close(resource td) Free the descriptor td */ PHP_FUNCTION(mcrypt_module_close) { MCRYPT_GET_TD_ARG zend_list_delete(Z_LVAL_P(mcryptind)); RETURN_TRUE; } /* }}} */ /* {{{ proto bool mcrypt_generic_deinit(resource td) This function terminates encrypt specified by the descriptor td */ PHP_FUNCTION(mcrypt_generic_deinit) { MCRYPT_GET_TD_ARG if (mcrypt_generic_deinit(pm->td) < 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not terminate encryption specifier"); RETURN_FALSE } pm->init = 0; RETURN_TRUE } /* }}} */ /* {{{ proto bool mcrypt_enc_is_block_algorithm_mode(resource td) Returns TRUE if the mode is for use with block algorithms */ PHP_FUNCTION(mcrypt_enc_is_block_algorithm_mode) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_algorithm_mode(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } } /* }}} */ /* {{{ proto bool mcrypt_enc_is_block_algorithm(resource td) Returns TRUE if the alrogithm is a block algorithms */ PHP_FUNCTION(mcrypt_enc_is_block_algorithm) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_algorithm(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } } /* }}} */ /* {{{ proto bool mcrypt_enc_is_block_mode(resource td) Returns TRUE if the mode outputs blocks */ PHP_FUNCTION(mcrypt_enc_is_block_mode) { MCRYPT_GET_TD_ARG if (mcrypt_enc_is_block_mode(pm->td) == 1) { RETURN_TRUE } else { RETURN_FALSE } } /* }}} */ /* {{{ proto int mcrypt_enc_get_block_size(resource td) Returns the block size of the cipher specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_get_block_size) { MCRYPT_GET_TD_ARG RETURN_LONG(mcrypt_enc_get_block_size(pm->td)); } /* }}} */ /* {{{ proto int mcrypt_enc_get_key_size(resource td) Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_get_key_size) { MCRYPT_GET_TD_ARG RETURN_LONG(mcrypt_enc_get_key_size(pm->td)); } /* }}} */ /* {{{ proto int mcrypt_enc_get_iv_size(resource td) Returns the size of the IV in bytes of the algorithm specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_get_iv_size) { MCRYPT_GET_TD_ARG RETURN_LONG(mcrypt_enc_get_iv_size(pm->td)); } /* }}} */ /* {{{ proto string mcrypt_enc_get_algorithms_name(resource td) Returns the name of the algorithm specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_get_algorithms_name) { char *name; MCRYPT_GET_TD_ARG name = mcrypt_enc_get_algorithms_name(pm->td); RETVAL_STRING(name, 1); mcrypt_free(name); } /* }}} */ /* {{{ proto string mcrypt_enc_get_modes_name(resource td) Returns the name of the mode specified by the descriptor td */ PHP_FUNCTION(mcrypt_enc_get_modes_name) { char *name; MCRYPT_GET_TD_ARG name = mcrypt_enc_get_modes_name(pm->td); RETVAL_STRING(name, 1); mcrypt_free(name); } /* }}} */ /* {{{ proto bool mcrypt_module_self_test(string algorithm [, string lib_dir]) Does a self test of the module "module" */ PHP_FUNCTION(mcrypt_module_self_test) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); if (mcrypt_module_self_test(module, dir) == 0) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool mcrypt_module_is_block_algorithm_mode(string mode [, string lib_dir]) Returns TRUE if the mode is for use with block algorithms */ PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool mcrypt_module_is_block_algorithm(string algorithm [, string lib_dir]) Returns TRUE if the algorithm is a block algorithm */ PHP_FUNCTION(mcrypt_module_is_block_algorithm) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) if (mcrypt_module_is_block_algorithm(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto bool mcrypt_module_is_block_mode(string mode [, string lib_dir]) Returns TRUE if the mode outputs blocks of bytes */ PHP_FUNCTION(mcrypt_module_is_block_mode) { MCRYPT_GET_MODE_DIR_ARGS(modes_dir) if (mcrypt_module_is_block_mode(module, dir) == 1) { RETURN_TRUE; } else { RETURN_FALSE; } } /* }}} */ /* {{{ proto int mcrypt_module_get_algo_block_size(string algorithm [, string lib_dir]) Returns the block size of the algorithm */ PHP_FUNCTION(mcrypt_module_get_algo_block_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir)); } /* }}} */ /* {{{ proto int mcrypt_module_get_algo_key_size(string algorithm [, string lib_dir]) Returns the maximum supported key size of the algorithm */ PHP_FUNCTION(mcrypt_module_get_algo_key_size) { MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir); RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir)); } /* }}} */ /* {{{ proto array mcrypt_module_get_supported_key_sizes(string algorithm [, string lib_dir]) This function decrypts the crypttext */ PHP_FUNCTION(mcrypt_module_get_supported_key_sizes) { int i, count = 0; int *key_sizes; MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir) array_init(return_value); key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count); for (i = 0; i < count; i++) { add_index_long(return_value, i, key_sizes[i]); } mcrypt_free(key_sizes); } /* }}} */ /* {{{ proto array mcrypt_list_algorithms([string lib_dir]) List all algorithms in "module_dir" */ PHP_FUNCTION(mcrypt_list_algorithms) { char **modules; char *lib_dir = MCG(algorithms_dir); int lib_dir_len; int i, count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &lib_dir, &lib_dir_len) == FAILURE) { return; } array_init(return_value); modules = mcrypt_list_algorithms(lib_dir, &count); if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir"); } for (i = 0; i < count; i++) { add_index_string(return_value, i, modules[i], 1); } mcrypt_free_p(modules, count); } /* }}} */ /* {{{ proto array mcrypt_list_modes([string lib_dir]) List all modes "module_dir" */ PHP_FUNCTION(mcrypt_list_modes) { char **modules; char *lib_dir = MCG(modes_dir); int lib_dir_len; int i, count; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s", &lib_dir, &lib_dir_len) == FAILURE) { return; } array_init(return_value); modules = mcrypt_list_modes(lib_dir, &count); if (count == 0) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "No modes found in module dir"); } for (i = 0; i < count; i++) { add_index_string(return_value, i, modules[i], 1); } mcrypt_free_p(modules, count); } /* }}} */ /* {{{ proto int mcrypt_get_key_size(string cipher, string module) Get the key size of cipher */ PHP_FUNCTION(mcrypt_get_key_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_key_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } /* }}} */ /* {{{ proto int mcrypt_get_block_size(string cipher, string module) Get the key size of cipher */ PHP_FUNCTION(mcrypt_get_block_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_block_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } /* }}} */ /* {{{ proto int mcrypt_get_iv_size(string cipher, string module) Get the IV size of cipher (Usually the same as the blocksize) */ PHP_FUNCTION(mcrypt_get_iv_size) { char *cipher; char *module; int cipher_len, module_len; char *cipher_dir_string; char *module_dir_string; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cipher, &cipher_len, &module, &module_len) == FAILURE) { return; } td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string); if (td != MCRYPT_FAILED) { RETVAL_LONG(mcrypt_enc_get_iv_size(td)); mcrypt_module_close(td); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } /* }}} */ /* {{{ proto string mcrypt_get_cipher_name(string cipher) Get the key size of cipher */ PHP_FUNCTION(mcrypt_get_cipher_name) { char *cipher_dir_string; char *module_dir_string; char *cipher_name; char *cipher; int cipher_len; MCRYPT td; MCRYPT_GET_INI if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &cipher, &cipher_len) == FAILURE) { return; } /* The code below is actually not very nice, but I didn't see a better * method */ td = mcrypt_module_open(cipher, cipher_dir_string, "ecb", module_dir_string); if (td != MCRYPT_FAILED) { cipher_name = mcrypt_enc_get_algorithms_name(td); mcrypt_module_close(td); RETVAL_STRING(cipher_name,1); mcrypt_free(cipher_name); } else { td = mcrypt_module_open(cipher, cipher_dir_string, "stream", module_dir_string); if (td != MCRYPT_FAILED) { cipher_name = mcrypt_enc_get_algorithms_name(td); mcrypt_module_close(td); RETVAL_STRING(cipher_name,1); mcrypt_free(cipher_name); } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } } } /* }}} */ static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, int iv_len, int argc, int dencrypt, zval* return_value TSRMLS_DC) /* {{{ */ { char *cipher_dir_string; char *module_dir_string; int block_size, max_key_length, use_key_length, i, count, iv_size; unsigned long int data_size; int *key_length_sizes; char *key_s = NULL, *iv_s; char *data_s; MCRYPT td; MCRYPT_GET_INI td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string); if (td == MCRYPT_FAILED) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED); RETURN_FALSE; } /* Checking for key-length */ max_key_length = mcrypt_enc_get_key_size(td); if (key_len > max_key_length) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Size of key is too large for this algorithm"); } key_length_sizes = mcrypt_enc_get_supported_key_sizes(td, &count); if (count == 0 && key_length_sizes == NULL) { /* all lengths 1 - k_l_s = OK */ use_key_length = key_len; key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, use_key_length); } else if (count == 1) { /* only m_k_l = OK */ key_s = emalloc(key_length_sizes[0]); memset(key_s, 0, key_length_sizes[0]); memcpy(key_s, key, MIN(key_len, key_length_sizes[0])); use_key_length = key_length_sizes[0]; } else { /* dertermine smallest supported key > length of requested key */ use_key_length = max_key_length; /* start with max key length */ for (i = 0; i < count; i++) { if (key_length_sizes[i] >= key_len && key_length_sizes[i] < use_key_length) { use_key_length = key_length_sizes[i]; } } key_s = emalloc(use_key_length); memset(key_s, 0, use_key_length); memcpy(key_s, key, MIN(key_len, use_key_length)); } mcrypt_free (key_length_sizes); /* Check IV */ iv_s = NULL; iv_size = mcrypt_enc_get_iv_size (td); /* IV is required */ if (mcrypt_enc_mode_has_iv(td) == 1) { if (argc == 5) { if (iv_size != iv_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_IV_WRONG_SIZE); } else { iv_s = emalloc(iv_size + 1); memcpy(iv_s, iv, iv_size); } } else if (argc == 4) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Attempt to use an empty IV, which is NOT recommend"); iv_s = emalloc(iv_size + 1); memset(iv_s, 0, iv_size + 1); } } /* Check blocksize */ if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */ block_size = mcrypt_enc_get_block_size(td); data_size = (((data_len - 1) / block_size) + 1) * block_size; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } else { /* It's not a block algorithm */ data_size = data_len; data_s = emalloc(data_size); memset(data_s, 0, data_size); memcpy(data_s, data, data_len); } if (mcrypt_generic_init(td, key_s, use_key_length, iv_s) < 0) { php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed"); RETURN_FALSE; } if (dencrypt == MCRYPT_ENCRYPT) { mcrypt_generic(td, data_s, data_size); } else { mdecrypt_generic(td, data_s, data_size); } RETVAL_STRINGL(data_s, data_size, 1); /* freeing vars */ mcrypt_generic_end(td); if (key_s != NULL) { efree (key_s); } if (iv_s != NULL) { efree (iv_s); } efree (data_s); } /* }}} */ /* {{{ proto string mcrypt_encrypt(string cipher, string key, string data, string mode, string iv) OFB crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_encrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_ENCRYPT, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_decrypt(string cipher, string key, string data, string mode, string iv) OFB crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_decrypt) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_string_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, Z_STRVAL_PP(mode), iv, iv_len, ZEND_NUM_ARGS(), MCRYPT_DECRYPT, return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_ecb(int cipher, string key, string data, int mode, string iv) ECB crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_ecb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_cbc(int cipher, string key, string data, int mode, string iv) CBC crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_cbc) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cbc", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_cfb(int cipher, string key, string data, int mode, string iv) CFB crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_cfb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_ofb(int cipher, string key, string data, int mode, string iv) OFB crypt/decrypt data using key key with cipher cipher starting with iv */ PHP_FUNCTION(mcrypt_ofb) { zval **mode; char *cipher, *key, *data, *iv = NULL; int cipher_len, key_len, data_len, iv_len = 0; MCRYPT_GET_CRYPT_ARGS convert_to_long_ex(mode); php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, ZEND_NUM_ARGS(), Z_LVAL_PP(mode), return_value TSRMLS_CC); } /* }}} */ /* {{{ proto string mcrypt_create_iv(int size, int source) Create an initialization vector (IV) */ PHP_FUNCTION(mcrypt_create_iv) { char *iv; long source = RANDOM; long size; int n = 0; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) { return; } if (size <= 0 || size >= INT_MAX) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX); RETURN_FALSE; } iv = ecalloc(size + 1, 1); if (source == RANDOM || source == URANDOM) { #if PHP_WIN32 /* random/urandom equivalent on Windows */ BYTE *iv_b = (BYTE *) iv; if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){ efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data"); RETURN_FALSE; } n = size; #else int *fd = &MCG(fd[source]); size_t read_bytes = 0; if (*fd < 0) { *fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY); if (*fd < 0) { efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device"); RETURN_FALSE; } } while (read_bytes < size) { n = read(*fd, iv + read_bytes, size - read_bytes); if (n < 0) { break; } read_bytes += n; } n = read_bytes; if (n < size) { efree(iv); php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data"); RETURN_FALSE; } #endif } else { n = size; while (size) { iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX); } } RETURN_STRINGL(iv, n, 0); } /* }}} */ #endif /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: sw=4 ts=4 fdm=marker * vim<600: sw=4 ts=4 */
./CrossVul/dataset_final_sorted/CWE-190/c/bad_5169_0
crossvul-cpp_data_bad_673_0
/** * FreeRDP: A Remote Desktop Protocol Implementation * Graphical Objects * * Copyright 2011 Marc-Andre Moreau <marcandre.moreau@gmail.com> * Copyright 2016 Armin Novak <armin.novak@thincast.com> * Copyright 2016 Thincast Technologies GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <freerdp/log.h> #include <freerdp/gdi/dc.h> #include <freerdp/gdi/shape.h> #include <freerdp/gdi/region.h> #include <freerdp/gdi/bitmap.h> #include "clipping.h" #include "drawing.h" #include "brush.h" #include "graphics.h" #define TAG FREERDP_TAG("gdi") /* Bitmap Class */ HGDI_BITMAP gdi_create_bitmap(rdpGdi* gdi, UINT32 nWidth, UINT32 nHeight, UINT32 SrcFormat, BYTE* data) { UINT32 nSrcStep; UINT32 nDstStep; BYTE* pSrcData; BYTE* pDstData; HGDI_BITMAP bitmap; if (!gdi) return NULL; nDstStep = nWidth * GetBytesPerPixel(gdi->dstFormat); pDstData = _aligned_malloc(nHeight * nDstStep, 16); if (!pDstData) return NULL; pSrcData = data; nSrcStep = nWidth * GetBytesPerPixel(SrcFormat); if (!freerdp_image_copy(pDstData, gdi->dstFormat, nDstStep, 0, 0, nWidth, nHeight, pSrcData, SrcFormat, nSrcStep, 0, 0, &gdi->palette, FREERDP_FLIP_NONE)) { _aligned_free(pDstData); return NULL; } bitmap = gdi_CreateBitmap(nWidth, nHeight, gdi->dstFormat, pDstData); return bitmap; } static BOOL gdi_Bitmap_New(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap; rdpGdi* gdi = context->gdi; gdi_bitmap = (gdiBitmap*) bitmap; gdi_bitmap->hdc = gdi_CreateCompatibleDC(gdi->hdc); if (!gdi_bitmap->hdc) return FALSE; if (!bitmap->data) gdi_bitmap->bitmap = gdi_CreateCompatibleBitmap( gdi->hdc, bitmap->width, bitmap->height); else { UINT32 format = bitmap->format; gdi_bitmap->bitmap = gdi_create_bitmap(gdi, bitmap->width, bitmap->height, format, bitmap->data); } if (!gdi_bitmap->bitmap) { gdi_DeleteDC(gdi_bitmap->hdc); return FALSE; } gdi_bitmap->hdc->format = gdi_bitmap->bitmap->format; gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->bitmap); gdi_bitmap->org_bitmap = NULL; return TRUE; } static void gdi_Bitmap_Free(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; if (gdi_bitmap) { if (gdi_bitmap->hdc) gdi_SelectObject(gdi_bitmap->hdc, (HGDIOBJECT) gdi_bitmap->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_bitmap->bitmap); gdi_DeleteDC(gdi_bitmap->hdc); _aligned_free(bitmap->data); } free(bitmap); } static BOOL gdi_Bitmap_Paint(rdpContext* context, rdpBitmap* bitmap) { gdiBitmap* gdi_bitmap = (gdiBitmap*) bitmap; UINT32 width = bitmap->right - bitmap->left + 1; UINT32 height = bitmap->bottom - bitmap->top + 1; return gdi_BitBlt(context->gdi->primary->hdc, bitmap->left, bitmap->top, width, height, gdi_bitmap->hdc, 0, 0, GDI_SRCCOPY, &context->gdi->palette); } static BOOL gdi_Bitmap_Decompress(rdpContext* context, rdpBitmap* bitmap, const BYTE* pSrcData, UINT32 DstWidth, UINT32 DstHeight, UINT32 bpp, UINT32 length, BOOL compressed, UINT32 codecId) { UINT32 SrcSize = length; rdpGdi* gdi = context->gdi; bitmap->compressed = FALSE; bitmap->format = gdi->dstFormat; bitmap->length = DstWidth * DstHeight * GetBytesPerPixel(bitmap->format); bitmap->data = (BYTE*) _aligned_malloc(bitmap->length, 16); if (!bitmap->data) return FALSE; if (compressed) { if (bpp < 32) { if (!interleaved_decompress(context->codecs->interleaved, pSrcData, SrcSize, DstWidth, DstHeight, bpp, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, &gdi->palette)) return FALSE; } else { if (!planar_decompress(context->codecs->planar, pSrcData, SrcSize, DstWidth, DstHeight, bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, TRUE)) return FALSE; } } else { const UINT32 SrcFormat = gdi_get_pixel_format(bpp); const size_t sbpp = GetBytesPerPixel(SrcFormat); const size_t dbpp = GetBytesPerPixel(bitmap->format); if ((sbpp == 0) || (dbpp == 0)) return FALSE; else { const size_t dstSize = SrcSize * dbpp / sbpp; if (dstSize < bitmap->length) return FALSE; } if (!freerdp_image_copy(bitmap->data, bitmap->format, 0, 0, 0, DstWidth, DstHeight, pSrcData, SrcFormat, 0, 0, 0, &gdi->palette, FREERDP_FLIP_VERTICAL)) return FALSE; } return TRUE; } static BOOL gdi_Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary) { rdpGdi* gdi; if (!context) return FALSE; gdi = context->gdi; if (!gdi) return FALSE; if (primary) gdi->drawing = gdi->primary; else gdi->drawing = (gdiBitmap*) bitmap; return TRUE; } /* Glyph Class */ static BOOL gdi_Glyph_New(rdpContext* context, const rdpGlyph* glyph) { BYTE* data; gdiGlyph* gdi_glyph; if (!context || !glyph) return FALSE; gdi_glyph = (gdiGlyph*) glyph; gdi_glyph->hdc = gdi_GetDC(); if (!gdi_glyph->hdc) return FALSE; gdi_glyph->hdc->format = PIXEL_FORMAT_MONO; data = freerdp_glyph_convert(glyph->cx, glyph->cy, glyph->aj); if (!data) { gdi_DeleteDC(gdi_glyph->hdc); return FALSE; } gdi_glyph->bitmap = gdi_CreateBitmap(glyph->cx, glyph->cy, PIXEL_FORMAT_MONO, data); if (!gdi_glyph->bitmap) { gdi_DeleteDC(gdi_glyph->hdc); _aligned_free(data); return FALSE; } gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->bitmap); gdi_glyph->org_bitmap = NULL; return TRUE; } static void gdi_Glyph_Free(rdpContext* context, rdpGlyph* glyph) { gdiGlyph* gdi_glyph; gdi_glyph = (gdiGlyph*) glyph; if (gdi_glyph) { gdi_SelectObject(gdi_glyph->hdc, (HGDIOBJECT) gdi_glyph->org_bitmap); gdi_DeleteObject((HGDIOBJECT) gdi_glyph->bitmap); gdi_DeleteDC(gdi_glyph->hdc); free(glyph->aj); free(glyph); } } static BOOL gdi_Glyph_Draw(rdpContext* context, const rdpGlyph* glyph, INT32 x, INT32 y, INT32 w, INT32 h, INT32 sx, INT32 sy, BOOL fOpRedundant) { gdiGlyph* gdi_glyph; rdpGdi* gdi; HGDI_BRUSH brush; BOOL rc = FALSE; if (!context || !glyph) return FALSE; gdi = context->gdi; gdi_glyph = (gdiGlyph*) glyph; if (!fOpRedundant && 0) { GDI_RECT rect = { 0 }; if (x > 0) rect.left = x; if (y > 0) rect.top = y; if (x + w > 0) rect.right = x + w - 1; if (y + h > 0) rect.bottom = y + h - 1; if ((rect.left < rect.right) && (rect.top < rect.bottom)) { brush = gdi_CreateSolidBrush(gdi->drawing->hdc->bkColor); if (!brush) return FALSE; gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } } brush = gdi_CreateSolidBrush(gdi->drawing->hdc->textColor); if (!brush) return FALSE; gdi_SelectObject(gdi->drawing->hdc, (HGDIOBJECT)brush); rc = gdi_BitBlt(gdi->drawing->hdc, x, y, w, h, gdi_glyph->hdc, sx, sy, GDI_GLYPH_ORDER, &context->gdi->palette); gdi_DeleteObject((HGDIOBJECT)brush); return rc; } static BOOL gdi_Glyph_SetBounds(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; return gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); } static BOOL gdi_Glyph_BeginDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor, BOOL fOpRedundant) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; if (!fOpRedundant) { if (!gdi_decode_color(gdi, bgcolor, &bgcolor, NULL)) return FALSE; if (!gdi_decode_color(gdi, fgcolor, &fgcolor, NULL)) return FALSE; gdi_SetClipRgn(gdi->drawing->hdc, x, y, width, height); gdi_SetTextColor(gdi->drawing->hdc, bgcolor); gdi_SetBkColor(gdi->drawing->hdc, fgcolor); if (1) { GDI_RECT rect = { 0 }; HGDI_BRUSH brush = gdi_CreateSolidBrush(fgcolor); if (!brush) return FALSE; if (x > 0) rect.left = x; if (y > 0) rect.top = y; rect.right = x + width - 1; rect.bottom = y + height - 1; if ((x + width > rect.left) && (y + height > rect.top)) gdi_FillRect(gdi->drawing->hdc, &rect, brush); gdi_DeleteObject((HGDIOBJECT)brush); } return gdi_SetNullClipRgn(gdi->drawing->hdc); } return TRUE; } static BOOL gdi_Glyph_EndDraw(rdpContext* context, INT32 x, INT32 y, INT32 width, INT32 height, UINT32 bgcolor, UINT32 fgcolor) { rdpGdi* gdi; if (!context || !context->gdi) return FALSE; gdi = context->gdi; if (!gdi->drawing || !gdi->drawing->hdc) return FALSE; gdi_SetNullClipRgn(gdi->drawing->hdc); return TRUE; } /* Graphics Module */ BOOL gdi_register_graphics(rdpGraphics* graphics) { rdpBitmap bitmap; rdpGlyph glyph; bitmap.size = sizeof(gdiBitmap); bitmap.New = gdi_Bitmap_New; bitmap.Free = gdi_Bitmap_Free; bitmap.Paint = gdi_Bitmap_Paint; bitmap.Decompress = gdi_Bitmap_Decompress; bitmap.SetSurface = gdi_Bitmap_SetSurface; graphics_register_bitmap(graphics, &bitmap); glyph.size = sizeof(gdiGlyph); glyph.New = gdi_Glyph_New; glyph.Free = gdi_Glyph_Free; glyph.Draw = gdi_Glyph_Draw; glyph.BeginDraw = gdi_Glyph_BeginDraw; glyph.EndDraw = gdi_Glyph_EndDraw; glyph.SetBounds = gdi_Glyph_SetBounds; graphics_register_glyph(graphics, &glyph); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_673_0
crossvul-cpp_data_good_3221_0
/* Audio File Library Copyright (C) 1998, 2011-2012, Michael Pruett <michael@68k.org> Copyright (C) 2001, Silicon Graphics, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* sfconvert is a program which can convert various parameters of sound files. */ #include "config.h" #ifdef __USE_SGI_HEADERS__ #include <dmedia/audiofile.h> #else #include <audiofile.h> #endif #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "printinfo.h" void printversion (void); void printusage (void); void usageerror (void); bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid); int firstBitSet(int x) { int position=0; while (x!=0) { x>>=1; ++position; } return position; } #ifndef __has_builtin #define __has_builtin(x) 0 #endif int multiplyCheckOverflow(int a, int b, int *result) { #if (defined __GNUC__ && __GNUC__ >= 5) || ( __clang__ && __has_builtin(__builtin_mul_overflow)) return __builtin_mul_overflow(a, b, result); #else if (firstBitSet(a)+firstBitSet(b)>31) // int is signed, so we can't use 32 bits return true; *result = a * b; return false; #endif } int main (int argc, char **argv) { if (argc == 2) { if (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-v")) { printversion(); exit(EXIT_SUCCESS); } if (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")) { printusage(); exit(EXIT_SUCCESS); } } if (argc < 3) usageerror(); const char *inFileName = argv[1]; const char *outFileName = argv[2]; int outFileFormat = AF_FILE_UNKNOWN; int outSampleFormat = -1, outSampleWidth = -1, outChannelCount = -1; int outCompression = AF_COMPRESSION_NONE; double outMaxAmp = 1.0; int i = 3; while (i < argc) { if (!strcmp(argv[i], "format")) { if (i + 1 >= argc) usageerror(); if (!strcmp(argv[i+1], "aiff")) outFileFormat = AF_FILE_AIFF; else if (!strcmp(argv[i+1], "aifc")) outFileFormat = AF_FILE_AIFFC; else if (!strcmp(argv[i+1], "wave")) outFileFormat = AF_FILE_WAVE; else if (!strcmp(argv[i+1], "next")) outFileFormat = AF_FILE_NEXTSND; else if (!strcmp(argv[i+1], "bics")) outFileFormat = AF_FILE_BICSF; else if (!strcmp(argv[i+1], "smp")) outFileFormat = AF_FILE_SAMPLEVISION; else if (!strcmp(argv[i+1], "voc")) outFileFormat = AF_FILE_VOC; else if (!strcmp(argv[i+1], "nist")) outFileFormat = AF_FILE_NIST_SPHERE; else if (!strcmp(argv[i+1], "caf")) outFileFormat = AF_FILE_CAF; else if (!strcmp(argv[i+1], "flac")) outFileFormat = AF_FILE_FLAC; else { fprintf(stderr, "sfconvert: Unknown format %s.\n", argv[i+1]); exit(EXIT_FAILURE); } // Increment for argument. i++; } else if (!strcmp(argv[i], "channels")) { if (i + 1 >= argc) usageerror(); outChannelCount = atoi(argv[i+1]); if (outChannelCount < 1) usageerror(); // Increment for argument. i++; } else if (!strcmp(argv[i], "float")) { if (i + 1 >= argc) usageerror(); outSampleFormat = AF_SAMPFMT_FLOAT; outSampleWidth = 32; outMaxAmp = atof(argv[i+1]); // outMaxAmp is currently unused. (void) outMaxAmp; // Increment for argument. i++; } else if (!strcmp(argv[i], "integer")) { if (i + 2 >= argc) usageerror(); outSampleWidth = atoi(argv[i+1]); if (outSampleWidth < 1 || outSampleWidth > 32) usageerror(); if (!strcmp(argv[i+2], "2scomp")) outSampleFormat = AF_SAMPFMT_TWOSCOMP; else if (!strcmp(argv[i+2], "unsigned")) outSampleFormat = AF_SAMPFMT_UNSIGNED; else usageerror(); // Increment for arguments. i += 2; } else if (!strcmp(argv[i], "compression")) { if (i + 1 >= argc) usageerror(); if (!strcmp(argv[i+1], "none")) outCompression = AF_COMPRESSION_NONE; else if (!strcmp(argv[i+1], "ulaw")) outCompression = AF_COMPRESSION_G711_ULAW; else if (!strcmp(argv[i+1], "alaw")) outCompression = AF_COMPRESSION_G711_ALAW; else if (!strcmp(argv[i+1], "ima")) outCompression = AF_COMPRESSION_IMA; else if (!strcmp(argv[i+1], "msadpcm")) outCompression = AF_COMPRESSION_MS_ADPCM; else if (!strcmp(argv[i+1], "flac")) outCompression = AF_COMPRESSION_FLAC; else if (!strcmp(argv[i+1], "alac")) outCompression = AF_COMPRESSION_ALAC; else { fprintf(stderr, "sfconvert: Unknown compression format %s.\n", argv[i+1]); exit(EXIT_FAILURE); } i++; } else { printf("Unrecognized command %s\n", argv[i]); } i++; } AFfilehandle inFile = afOpenFile(inFileName, "r", AF_NULL_FILESETUP); if (!inFile) { printf("Could not open file '%s' for reading.\n", inFileName); return EXIT_FAILURE; } // Get audio format parameters from input file. int fileFormat = afGetFileFormat(inFile, NULL); int channelCount = afGetChannels(inFile, AF_DEFAULT_TRACK); double sampleRate = afGetRate(inFile, AF_DEFAULT_TRACK); int sampleFormat, sampleWidth; afGetSampleFormat(inFile, AF_DEFAULT_TRACK, &sampleFormat, &sampleWidth); // Initialize output audio format parameters. AFfilesetup outFileSetup = afNewFileSetup(); if (outFileFormat == -1) outFileFormat = fileFormat; if (outSampleFormat == -1 || outSampleWidth == -1) { outSampleFormat = sampleFormat; outSampleWidth = sampleWidth; } if (outChannelCount == -1) outChannelCount = channelCount; afInitFileFormat(outFileSetup, outFileFormat); afInitCompression(outFileSetup, AF_DEFAULT_TRACK, outCompression); afInitSampleFormat(outFileSetup, AF_DEFAULT_TRACK, outSampleFormat, outSampleWidth); afInitChannels(outFileSetup, AF_DEFAULT_TRACK, outChannelCount); afInitRate(outFileSetup, AF_DEFAULT_TRACK, sampleRate); AFfilehandle outFile = afOpenFile(outFileName, "w", outFileSetup); if (!outFile) { printf("Could not open file '%s' for writing.\n", outFileName); return EXIT_FAILURE; } afFreeFileSetup(outFileSetup); /* Set the output file's virtual audio format parameters to match the audio format parameters of the input file. */ afSetVirtualChannels(outFile, AF_DEFAULT_TRACK, channelCount); afSetVirtualSampleFormat(outFile, AF_DEFAULT_TRACK, sampleFormat, sampleWidth); bool success = copyaudiodata(inFile, outFile, AF_DEFAULT_TRACK); afCloseFile(inFile); afCloseFile(outFile); if (!success) { unlink(outFileName); return EXIT_FAILURE; } printfileinfo(inFileName); putchar('\n'); printfileinfo(outFileName); return EXIT_SUCCESS; } void printusage (void) { printf("usage: sfconvert infile outfile [ options ... ] [ output keywords ... ]\n"); printf("\n"); printf("Where keywords specify format of input or output soundfile:\n"); printf(" format f file format f (see below)\n"); printf(" compression c compression format c (see below)\n"); printf(" byteorder e endian (e is big or little)\n"); printf(" channels n n-channel file (1 or 2)\n"); printf(" integer n s n-bit integer file, where s is one of\n"); printf(" 2scomp: 2's complement signed data\n"); printf(" unsigned: unsigned data\n"); printf(" float m floating point file, maxamp m (usually 1.0)\n"); printf("\n"); printf("Currently supported file formats are:\n"); printf("\n"); printf(" aiff Audio Interchange File Format\n"); printf(" aifc AIFF-C File Format\n"); printf(" next NeXT/Sun Format\n"); printf(" wave MS RIFF WAVE Format\n"); printf(" bics Berkeley/IRCAM/CARL Sound File Format\n"); printf(" smp Sample Vision Format\n"); printf(" voc Creative Voice File\n"); printf(" nist NIST SPHERE Format\n"); printf(" caf Core Audio Format\n"); printf("\n"); printf("Currently supported compression formats are:\n"); printf("\n"); printf(" ulaw G.711 u-law\n"); printf(" alaw G.711 A-law\n"); printf(" ima IMA ADPCM\n"); printf(" msadpcm MS ADPCM\n"); printf(" flac FLAC\n"); printf(" alac Apple Lossless Audio Codec\n"); printf("\n"); } void usageerror (void) { printusage(); exit(EXIT_FAILURE); } void printversion (void) { printf("sfconvert: Audio File Library version %s\n", VERSION); } /* Copy audio data from one file to another. This function assumes that the virtual sample formats of the two files match. */ bool copyaudiodata (AFfilehandle infile, AFfilehandle outfile, int trackid) { int frameSize = afGetVirtualFrameSize(infile, trackid, 1); int kBufferFrameCount = 65536; int bufferSize; while (multiplyCheckOverflow(kBufferFrameCount, frameSize, &bufferSize)) kBufferFrameCount /= 2; void *buffer = malloc(bufferSize); AFframecount totalFrames = afGetFrameCount(infile, AF_DEFAULT_TRACK); AFframecount totalFramesWritten = 0; bool success = true; while (totalFramesWritten < totalFrames) { AFframecount framesToRead = totalFrames - totalFramesWritten; if (framesToRead > kBufferFrameCount) framesToRead = kBufferFrameCount; AFframecount framesRead = afReadFrames(infile, trackid, buffer, framesToRead); if (framesRead < framesToRead) { fprintf(stderr, "Bad read of audio track data.\n"); success = false; break; } AFframecount framesWritten = afWriteFrames(outfile, trackid, buffer, framesRead); if (framesWritten < framesRead) { fprintf(stderr, "Bad write of audio track data.\n"); success = false; break; } totalFramesWritten += framesWritten; } free(buffer); return success; }
./CrossVul/dataset_final_sorted/CWE-190/c/good_3221_0
crossvul-cpp_data_good_3226_0
/* dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2013 by Dave Coffin, dcoffin a cybercom o net This is a command-line ANSI C program to convert raw photos from any digital camera on any computer running any operating system. No license is required to download and use dcraw.c. However, to lawfully redistribute dcraw, you must either (a) offer, at no extra charge, full source code* for all executable files containing RESTRICTED functions, (b) distribute this code under the GPL Version 2 or later, (c) remove all RESTRICTED functions, re-implement them, or copy them from an earlier, unrestricted Revision of dcraw.c, or (d) purchase a license from the author. The functions that process Foveon images have been RESTRICTED since Revision 1.237. All other code remains free for all uses. *If you have not modified dcraw.c in any way, a link to my homepage qualifies as "full source code". $Revision: 1.456 $ $Date: 2013/06/16 18:01:08 $ */ #define getbits(n) getbithuff(n,0) char * CLASS foveon_gets (int offset, char *str, int len) { int i; fseek (ifp, offset, SEEK_SET); for (i=0; i < len-1; i++) if ((str[i] = get2()) == 0) break; str[i] = 0; return str; } void CLASS parse_foveon() { int entries, img=0, off, len, tag, save, i, wide, high, pent, poff[256][2]; char name[64], value[64]; order = 0x4949; /* Little-endian */ fseek (ifp, 36, SEEK_SET); flip = get4(); fseek (ifp, -4, SEEK_END); fseek (ifp, get4(), SEEK_SET); if (get4() != 0x64434553) return; /* SECd */ entries = (get4(),get4()); while (entries--) { off = get4(); len = get4(); tag = get4(); save = ftell(ifp); fseek (ifp, off, SEEK_SET); if (get4() != (0x20434553 | (tag << 24))) return; switch (tag) { case 0x47414d49: /* IMAG */ case 0x32414d49: /* IMA2 */ fseek (ifp, 8, SEEK_CUR); pent = get4(); wide = get4(); high = get4(); if (wide > raw_width && high > raw_height) { switch (pent) { case 5: load_flags = 1; case 6: load_raw = &CLASS foveon_sd_load_raw; break; case 30: load_raw = &CLASS foveon_dp_load_raw; break; default: load_raw = 0; } raw_width = wide; raw_height = high; data_offset = off+28; is_foveon = 1; } fseek (ifp, off+28, SEEK_SET); if (fgetc(ifp) == 0xff && fgetc(ifp) == 0xd8 && thumb_length < len-28) { thumb_offset = off+28; thumb_length = len-28; write_thumb = &CLASS jpeg_thumb; } if (++img == 2 && !thumb_length) { thumb_offset = off+24; thumb_width = wide; thumb_height = high; write_thumb = &CLASS foveon_thumb; } break; case 0x464d4143: /* CAMF */ meta_offset = off+8; meta_length = len-28; break; case 0x504f5250: /* PROP */ pent = (get4(),get4()); fseek (ifp, 12, SEEK_CUR); off += pent*8 + 24; if ((unsigned) pent > 256) pent=256; for (i=0; i < pent*2; i++) poff[0][i] = off + get4()*2; for (i=0; i < pent; i++) { foveon_gets (poff[i][0], name, 64); foveon_gets (poff[i][1], value, 64); if (!strcmp (name, "ISO")) iso_speed = atoi(value); if (!strcmp (name, "CAMMANUF")) strcpy (make, value); if (!strcmp (name, "CAMMODEL")) strcpy (model, value); if (!strcmp (name, "WB_DESC")) strcpy (model2, value); if (!strcmp (name, "TIME")) timestamp = atoi(value); if (!strcmp (name, "EXPTIME")) shutter = atoi(value) / 1000000.0; if (!strcmp (name, "APERTURE")) aperture = atof(value); if (!strcmp (name, "FLENGTH")) focal_len = atof(value); } #ifdef LOCALTIME timestamp = mktime (gmtime (&timestamp)); #endif } fseek (ifp, save, SEEK_SET); } } /* RESTRICTED code starts here */ void CLASS foveon_decoder (unsigned size, unsigned code) { static unsigned huff[1024]; struct decode *cur; int i, len; if (!code) { for (i=0; i < size; i++) huff[i] = get4(); memset (first_decode, 0, sizeof first_decode); free_decode = first_decode; } cur = free_decode++; if (free_decode > first_decode+2048) { #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_DECODE_RAW; #else fprintf (stderr,_("%s: decoder table overflow\n"), ifname); longjmp (failure, 2); #endif } if (code) for (i=0; i < size; i++) if (huff[i] == code) { cur->leaf = i; return; } if ((len = code >> 27) > 26) return; code = (len+1) << 27 | (code & 0x3ffffff) << 1; cur->branch[0] = free_decode; foveon_decoder (size, code); cur->branch[1] = free_decode; foveon_decoder (size, code+1); } #ifdef LIBRAW_LIBRARY_BUILD #define T imgdata.thumbnail #define ID libraw_internal_data.internal_data void LibRaw::foveon_thumb_loader (void) { unsigned bwide, row, col, bitbuf=0, bit=1, c, i; struct decode *dindex; short pred[3]; if(T.thumb) free(T.thumb); T.thumb = NULL; bwide = get4(); if (bwide > 0) { if (bwide < (unsigned)T.twidth*3) return; T.thumb = (char*)malloc(3*T.twidth * T.theight); merror (T.thumb, "foveon_thumb()"); char *buf = (char*)malloc(bwide); merror (buf, "foveon_thumb()"); for (row=0; row < T.theight; row++) { ID.input->read(buf, 1, bwide); memmove(T.thumb+(row*T.twidth*3),buf,T.twidth*3); } free(buf); T.tlength = 3*T.twidth * T.theight; T.tformat = LIBRAW_THUMBNAIL_BITMAP; return; } else { foveon_decoder (256, 0); T.thumb = (char*)malloc(3*T.twidth * T.theight); char *bufp = T.thumb; merror (T.thumb, "foveon_thumb()"); for (row=0; row < T.theight; row++) { memset (pred, 0, sizeof pred); if (!bit) get4(); for (bit=col=0; col < T.twidth; col++) for(c=0;c<3;c++) { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + ID.input->get_char(); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; (*bufp++)=pred[c]; } } T.tformat = LIBRAW_THUMBNAIL_BITMAP; T.tlength = 3*T.twidth * T.theight; } return; } #endif void CLASS foveon_thumb() { unsigned bwide, row, col, bitbuf=0, bit=1, c, i; char *buf; struct decode *dindex; short pred[3]; bwide = get4(); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); if (bwide > 0) { if (bwide < thumb_width*3) return; buf = (char *) malloc (bwide); merror (buf, "foveon_thumb()"); for (row=0; row < thumb_height; row++) { fread (buf, 1, bwide, ifp); fwrite (buf, 3, thumb_width, ofp); } free (buf); return; } foveon_decoder (256, 0); for (row=0; row < thumb_height; row++) { memset (pred, 0, sizeof pred); if (!bit) get4(); for (bit=col=0; col < thumb_width; col++) FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += dindex->leaf; fputc (pred[c], ofp); } } } void CLASS foveon_sd_load_raw() { struct decode *dindex; short diff[1024]; unsigned bitbuf=0; int pred[3], row, col, bit=-1, c, i; read_shorts ((ushort *) diff, 1024); if (!load_flags) foveon_decoder (1024, 0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (pred, 0, sizeof pred); if (!bit && !load_flags && atoi(model+2) < 14) get4(); for (col=bit=0; col < width; col++) { if (load_flags) { bitbuf = get4(); FORC3 pred[2-c] += diff[bitbuf >> c*10 & 0x3ff]; } else FORC3 { for (dindex=first_decode; dindex->branch[0]; ) { if ((bit = (bit-1) & 31) == 31) for (i=0; i < 4; i++) bitbuf = (bitbuf << 8) + fgetc(ifp); dindex = dindex->branch[bitbuf >> bit & 1]; } pred[c] += diff[dindex->leaf]; if (pred[c] >> 16 && ~pred[c] >> 16) derror(); } FORC3 image[row*width+col][c] = pred[c]; } } } void CLASS foveon_huff (ushort *huff) { int i, j, clen, code; huff[0] = 8; for (i=0; i < 13; i++) { clen = getc(ifp); code = getc(ifp); for (j=0; j < 256 >> clen; ) huff[code+ ++j] = clen << 8 | i; } get2(); } void CLASS foveon_dp_load_raw() { unsigned c, roff[4], row, col, diff; ushort huff[1024], vpred[2][2], hpred[2]; fseek (ifp, 8, SEEK_CUR); foveon_huff (huff); roff[0] = 48; FORC3 roff[c+1] = -(-(roff[c] + get4()) & -16); FORC3 { fseek (ifp, data_offset+roff[c], SEEK_SET); getbits(-1); vpred[0][0] = vpred[0][1] = vpred[1][0] = vpred[1][1] = 512; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; image[row*width+col][c] = hpred[col & 1]; } } } } void CLASS foveon_load_camf() { unsigned type, wide, high, i, j, row, col, diff; ushort huff[1024], vpred[2][2] = {{512,512},{512,512}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); type = get4(); get4(); get4(); wide = get4(); high = get4(); #ifdef LIBRAW_LIBRARY_BUILD if(wide>32767 || high > 32767 || wide*high > 20000000) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif if (type == 2) { fread (meta_data, 1, meta_length, ifp); for (i=0; i < meta_length; i++) { high = (high * 1597 + 51749) % 244944; wide = high * (INT64) 301593171 >> 24; meta_data[i] ^= ((((high << 8) - wide) >> 1) + wide) >> 17; } } else if (type == 4) { free (meta_data); meta_data = (char *) malloc (meta_length = wide*high*3/2); merror (meta_data, "foveon_load_camf()"); foveon_huff (huff); get4(); getbits(-1); for (j=row=0; row < high; row++) { for (col=0; col < wide; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if (col & 1) { meta_data[j++] = hpred[0] >> 4; meta_data[j++] = hpred[0] << 4 | hpred[1] >> 8; meta_data[j++] = hpred[1]; } } } } else fprintf (stderr,_("%s has unknown CAMF type %d.\n"), ifname, type); } const char * CLASS foveon_camf_param (const char *block, const char *param) { unsigned idx, num; char *pos, *cp, *dp; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'P') continue; if (strcmp (block, pos+sget4(pos+12))) continue; cp = pos + sget4(pos+16); num = sget4(cp); dp = pos + sget4(cp+4); while (num--) { cp += 8; if (!strcmp (param, dp+sget4(cp))) return dp+sget4(cp+4); } } return 0; } void * CLASS foveon_camf_matrix (unsigned dim[3], const char *name) { unsigned i, idx, type, ndim, size, *mat; char *pos, *cp, *dp; double dsize; for (idx=0; idx < meta_length; idx += sget4(pos+8)) { pos = meta_data + idx; if (strncmp (pos, "CMb", 3)) break; if (pos[3] != 'M') continue; if (strcmp (name, pos+sget4(pos+12))) continue; dim[0] = dim[1] = dim[2] = 1; cp = pos + sget4(pos+16); type = sget4(cp); if ((ndim = sget4(cp+4)) > 3) break; dp = pos + sget4(cp+8); for (i=ndim; i--; ) { cp += 12; dim[i] = sget4(cp); } if ((dsize = (double) dim[0]*dim[1]*dim[2]) > meta_length/4) break; mat = (unsigned *) malloc ((size = dsize) * 4); merror (mat, "foveon_camf_matrix()"); for (i=0; i < size; i++) if (type && type != 6) mat[i] = sget4(dp + i*4); else mat[i] = sget4(dp + i*2) & 0xffff; return mat; } fprintf (stderr,_("%s: \"%s\" matrix not found!\n"), ifname, name); return 0; } int CLASS foveon_fixed (void *ptr, int size, const char *name) { void *dp; unsigned dim[3]; if (!name) return 0; dp = foveon_camf_matrix (dim, name); if (!dp) return 0; memcpy (ptr, dp, size*4); free (dp); return 1; } float CLASS foveon_avg (short *pix, int range[2], float cfilt) { int i; float val, min=FLT_MAX, max=-FLT_MAX, sum=0; for (i=range[0]; i <= range[1]; i++) { sum += val = pix[i*4] + (pix[i*4]-pix[(i-1)*4]) * cfilt; if (min > val) min = val; if (max < val) max = val; } if (range[1] - range[0] == 1) return sum/2; return (sum - min - max) / (range[1] - range[0] - 1); } short * CLASS foveon_make_curve (double max, double mul, double filt) { short *t_curve; unsigned i, size; double x; if (!filt) filt = 0.8; size = 4*M_PI*max / filt; if (size == UINT_MAX) size--; t_curve = (short *) calloc (size+1, sizeof *t_curve); merror (t_curve, "foveon_make_curve()"); t_curve[0] = size; for (i=0; i < size; i++) { x = i*filt/max/4; t_curve[i+1] = (cos(x)+1)/2 * tanh(i*filt/mul) * mul + 0.5; } return t_curve; } void CLASS foveon_make_curves (short **curvep, float dq[3], float div[3], float filt) { double mul[3], max=0; int c; FORC3 mul[c] = dq[c]/div[c]; FORC3 if (max < mul[c]) max = mul[c]; FORC3 curvep[c] = foveon_make_curve (max, mul[c], filt); } int CLASS foveon_apply_curve (short *t_curve, int i) { if (abs(i) >= t_curve[0]) return 0; return i < 0 ? -t_curve[1-i] : t_curve[1+i]; } #ifdef LIBRAW_LIBRARY_BUILD #ifdef image #undef image #endif #define image ((short(*)[4]) imgdata.image) #else #define image ((short (*)[4]) image) #endif void CLASS foveon_interpolate() { static const short hood[] = { -1,-1, -1,0, -1,1, 0,-1, 0,1, 1,-1, 1,0, 1,1 }; short *pix, prev[3], *t_curve[8], (*t_shrink)[3]; float cfilt=0, ddft[3][3][2], ppm[3][3][3]; float cam_xyz[3][3], correct[3][3], last[3][3], trans[3][3]; float chroma_dq[3], color_dq[3], diag[3][3], div[3]; float (*t_black)[3], (*sgain)[3], (*sgrow)[3]; float fsum[3], val, frow, num; int row, col, c, i, j, diff, sgx, irow, sum, min, max, limit; int dscr[2][2], dstb[4], (*smrow[7])[3], total[4], ipix[3]; int work[3][3], smlast, smred, smred_p=0, dev[3]; int satlev[3], keep[4], active[4]; unsigned dim[3], *badpix; double dsum=0, trsum[3]; char str[128]; const char* cp; if (verbose) fprintf (stderr,_("Foveon interpolation...\n")); foveon_load_camf(); foveon_fixed (dscr, 4, "DarkShieldColRange"); foveon_fixed (ppm[0][0], 27, "PostPolyMatrix"); foveon_fixed (satlev, 3, "SaturationLevel"); foveon_fixed (keep, 4, "KeepImageArea"); foveon_fixed (active, 4, "ActiveImageArea"); foveon_fixed (chroma_dq, 3, "ChromaDQ"); foveon_fixed (color_dq, 3, foveon_camf_param ("IncludeBlocks", "ColorDQ") ? "ColorDQ" : "ColorDQCamRGB"); if (foveon_camf_param ("IncludeBlocks", "ColumnFilter")) foveon_fixed (&cfilt, 1, "ColumnFilter"); memset (ddft, 0, sizeof ddft); if (!foveon_camf_param ("IncludeBlocks", "DarkDrift") || !foveon_fixed (ddft[1][0], 12, "DarkDrift")) for (i=0; i < 2; i++) { foveon_fixed (dstb, 4, i ? "DarkShieldBottom":"DarkShieldTop"); for (row = dstb[1]; row <= dstb[3]; row++) for (col = dstb[0]; col <= dstb[2]; col++) FORC3 ddft[i+1][c][1] += (short) image[row*width+col][c]; FORC3 ddft[i+1][c][1] /= (dstb[3]-dstb[1]+1) * (dstb[2]-dstb[0]+1); } if (!(cp = foveon_camf_param ("WhiteBalanceIlluminants", model2))) { fprintf (stderr,_("%s: Invalid white balance \"%s\"\n"), ifname, model2); return; } foveon_fixed (cam_xyz, 9, cp); foveon_fixed (correct, 9, foveon_camf_param ("WhiteBalanceCorrections", model2)); memset (last, 0, sizeof last); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 last[i][j] += correct[i][c] * cam_xyz[c][j]; #define LAST(x,y) last[(i+x)%3][(c+y)%3] for (i=0; i < 3; i++) FORC3 diag[c][i] = LAST(1,1)*LAST(2,2) - LAST(1,2)*LAST(2,1); #undef LAST FORC3 div[c] = diag[c][0]*0.3127 + diag[c][1]*0.329 + diag[c][2]*0.3583; sprintf (str, "%sRGBNeutral", model2); if (foveon_camf_param ("IncludeBlocks", str)) foveon_fixed (div, 3, str); num = 0; FORC3 if (num < div[c]) num = div[c]; FORC3 div[c] /= num; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += rgb_cam[i][c] * last[c][j] * div[j]; FORC3 trsum[c] = trans[c][0] + trans[c][1] + trans[c][2]; dsum = (6*trsum[0] + 11*trsum[1] + 3*trsum[2]) / 20; for (i=0; i < 3; i++) FORC3 last[i][c] = trans[i][c] * dsum / trsum[i]; memset (trans, 0, sizeof trans); for (i=0; i < 3; i++) for (j=0; j < 3; j++) FORC3 trans[i][j] += (i==c ? 32 : -1) * last[c][j] / 30; foveon_make_curves (t_curve, color_dq, div, cfilt); FORC3 chroma_dq[c] /= 3; foveon_make_curves (t_curve+3, chroma_dq, div, cfilt); FORC3 dsum += chroma_dq[c] / div[c]; t_curve[6] = foveon_make_curve (dsum, dsum, cfilt); t_curve[7] = foveon_make_curve (dsum*2, dsum*2, cfilt); sgain = (float (*)[3]) foveon_camf_matrix (dim, "SpatialGain"); if (!sgain) return; sgrow = (float (*)[3]) calloc (dim[1], sizeof *sgrow); sgx = (width + dim[1]-2) / (dim[1]-1); t_black = (float (*)[3]) calloc (height, sizeof *t_black); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ddft[0][0][i] = ddft[1][0][i] + row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]); FORC3 t_black[row][c] = ( foveon_avg (image[row*width]+c, dscr[0], cfilt) + foveon_avg (image[row*width]+c, dscr[1], cfilt) * 3 - ddft[0][c][0] ) / 4 - ddft[0][c][1]; } memcpy (t_black, t_black+8, sizeof *t_black*8); memcpy (t_black+height-11, t_black+height-22, 11*sizeof *t_black); memcpy (last, t_black, sizeof last); for (row=1; row < height-1; row++) { FORC3 if (last[1][c] > last[0][c]) { if (last[1][c] > last[2][c]) t_black[row][c] = (last[0][c] > last[2][c]) ? last[0][c]:last[2][c]; } else if (last[1][c] < last[2][c]) t_black[row][c] = (last[0][c] < last[2][c]) ? last[0][c]:last[2][c]; memmove (last, last+1, 2*sizeof last[0]); memcpy (last[2], t_black[row+1], sizeof last[2]); } FORC3 t_black[row][c] = (last[0][c] + last[1][c])/2; FORC3 t_black[0][c] = (t_black[1][c] + t_black[3][c])/2; val = 1 - exp(-1/24.0); memcpy (fsum, t_black, sizeof fsum); for (row=1; row < height; row++) FORC3 fsum[c] += t_black[row][c] = (t_black[row][c] - t_black[row-1][c])*val + t_black[row-1][c]; memcpy (last[0], t_black[height-1], sizeof last[0]); FORC3 fsum[c] /= height; for (row = height; row--; ) FORC3 last[0][c] = t_black[row][c] = (t_black[row][c] - fsum[c] - last[0][c])*val + last[0][c]; memset (total, 0, sizeof total); for (row=2; row < height; row+=4) for (col=2; col < width; col+=4) { FORC3 total[c] += (short) image[row*width+col][c]; total[3]++; } for (row=0; row < height; row++) FORC3 t_black[row][c] += fsum[c]/2 + total[c]/(total[3]*100.0); for (row=0; row < height; row++) { for (i=0; i < 6; i++) ddft[0][0][i] = ddft[1][0][i] + row / (height-1.0) * (ddft[2][0][i] - ddft[1][0][i]); pix = image[row*width]; memcpy (prev, pix, sizeof prev); frow = row / (height-1.0) * (dim[2]-1); if ((irow = frow) == dim[2]-1) irow--; frow -= irow; for (i=0; i < dim[1]; i++) FORC3 sgrow[i][c] = sgain[ irow *dim[1]+i][c] * (1-frow) + sgain[(irow+1)*dim[1]+i][c] * frow; for (col=0; col < width; col++) { FORC3 { diff = pix[c] - prev[c]; prev[c] = pix[c]; ipix[c] = pix[c] + floor ((diff + (diff*diff >> 14)) * cfilt - ddft[0][c][1] - ddft[0][c][0] * ((float) col/width - 0.5) - t_black[row][c] ); } FORC3 { work[0][c] = ipix[c] * ipix[c] >> 14; work[2][c] = ipix[c] * work[0][c] >> 14; work[1][2-c] = ipix[(c+1) % 3] * ipix[(c+2) % 3] >> 14; } FORC3 { for (val=i=0; i < 3; i++) for ( j=0; j < 3; j++) val += ppm[c][i][j] * work[i][j]; ipix[c] = floor ((ipix[c] + floor(val)) * ( sgrow[col/sgx ][c] * (sgx - col%sgx) + sgrow[col/sgx+1][c] * (col%sgx) ) / sgx / div[c]); if (ipix[c] > 32000) ipix[c] = 32000; pix[c] = ipix[c]; } pix += 4; } } free (t_black); free (sgrow); free (sgain); if ((badpix = (unsigned int *) foveon_camf_matrix (dim, "BadPixels"))) { for (i=0; i < dim[0]; i++) { col = (badpix[i] >> 8 & 0xfff) - keep[0]; row = (badpix[i] >> 20 ) - keep[1]; if ((unsigned)(row-1) > height-3 || (unsigned)(col-1) > width-3) continue; memset (fsum, 0, sizeof fsum); for (sum=j=0; j < 8; j++) if (badpix[i] & (1 << j)) { FORC3 fsum[c] += (short) image[(row+hood[j*2])*width+col+hood[j*2+1]][c]; sum++; } if (sum) FORC3 image[row*width+col][c] = fsum[c]/sum; } free (badpix); } /* Array for 5x5 Gaussian averaging of red values */ smrow[6] = (int (*)[3]) calloc (width*5, sizeof **smrow); merror (smrow[6], "foveon_interpolate()"); for (i=0; i < 5; i++) smrow[i] = smrow[6] + i*width; /* Sharpen the reds against these Gaussian averages */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { smrow[4][col][0] = (pix[0]*6 + (pix[-4]+pix[4])*4 + pix[-8]+pix[8] + 8) >> 4; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { smred = ( 6 * smrow[2][col][0] + 4 * (smrow[1][col][0] + smrow[3][col][0]) + smrow[0][col][0] + smrow[4][col][0] + 8 ) >> 4; if (col == 2) smred_p = smred; i = pix[0] + ((pix[0] - ((smred*7 + smred_p) >> 3)) >> 3); if (i > 32000) i = 32000; pix[0] = i; smred_p = smred; pix += 4; } } /* Adjust the brighter pixels for better linearity */ min = 0xffff; FORC3 { i = satlev[c] / div[c]; if (min > i) min = i; } limit = min * 9 >> 4; for (pix=image[0]; pix < image[height*width]; pix+=4) { if (pix[0] <= limit || pix[1] <= limit || pix[2] <= limit) continue; min = max = pix[0]; for (c=1; c < 3; c++) { if (min > pix[c]) min = pix[c]; if (max < pix[c]) max = pix[c]; } if (min >= limit*2) { pix[0] = pix[1] = pix[2] = max; } else { i = 0x4000 - ((min - limit) << 14) / limit; i = 0x4000 - (i*i >> 14); i = i*i >> 14; FORC3 pix[c] += (max - pix[c]) * i >> 14; } } /* Because photons that miss one detector often hit another, the sum R+G+B is much less noisy than the individual colors. So smooth the hues without smoothing the total. */ for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-4]+2*pix[c]+pix[c+4]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { FORC3 dev[c] = -foveon_apply_curve (t_curve[7], pix[c] - ((smrow[1][col][c] + 2*smrow[2][col][c] + smrow[3][col][c]) >> 2)); sum = (dev[0] + dev[1] + dev[2]) >> 3; FORC3 pix[c] += dev[c] - sum; pix += 4; } } for (smlast=-1, row=2; row < height-2; row++) { while (smlast < row+2) { for (i=0; i < 6; i++) smrow[(i+5) % 6] = smrow[i]; pix = image[++smlast*width+2]; for (col=2; col < width-2; col++) { FORC3 smrow[4][col][c] = (pix[c-8]+pix[c-4]+pix[c]+pix[c+4]+pix[c+8]+2) >> 2; pix += 4; } } pix = image[row*width+2]; for (col=2; col < width-2; col++) { for (total[3]=375, sum=60, c=0; c < 3; c++) { for (total[c]=i=0; i < 5; i++) total[c] += smrow[i][col][c]; total[3] += total[c]; sum += pix[c]; } if (sum < 0) sum = 0; j = total[3] > 375 ? (sum << 16) / total[3] : sum * 174; FORC3 pix[c] += foveon_apply_curve (t_curve[6], ((j*total[c] + 0x8000) >> 16) - pix[c]); pix += 4; } } /* Transform the image to a different colorspace */ for (pix=image[0]; pix < image[height*width]; pix+=4) { FORC3 pix[c] -= foveon_apply_curve (t_curve[c], pix[c]); sum = (pix[0]+pix[1]+pix[1]+pix[2]) >> 2; FORC3 pix[c] -= foveon_apply_curve (t_curve[c], pix[c]-sum); FORC3 { for (dsum=i=0; i < 3; i++) dsum += trans[c][i] * pix[i]; if (dsum < 0) dsum = 0; if (dsum > 24000) dsum = 24000; ipix[c] = dsum + 0.5; } FORC3 pix[c] = ipix[c]; } /* Smooth the image bottom-to-top and save at 1/4 scale */ t_shrink = (short (*)[3]) calloc ((width/4) * (height/4), sizeof *t_shrink); merror (t_shrink, "foveon_interpolate()"); for (row = height/4; row--; ) for (col=0; col < width/4; col++) { ipix[0] = ipix[1] = ipix[2] = 0; for (i=0; i < 4; i++) for (j=0; j < 4; j++) FORC3 ipix[c] += image[(row*4+i)*width+col*4+j][c]; FORC3 if (row+2 > height/4) t_shrink[row*(width/4)+col][c] = ipix[c] >> 4; else t_shrink[row*(width/4)+col][c] = (t_shrink[(row+1)*(width/4)+col][c]*1840 + ipix[c]*141 + 2048) >> 12; } /* From the 1/4-scale image, smooth right-to-left */ for (row=0; row < (height & ~3); row++) { ipix[0] = ipix[1] = ipix[2] = 0; if ((row & 3) == 0) for (col = width & ~3 ; col--; ) FORC3 smrow[0][col][c] = ipix[c] = (t_shrink[(row/4)*(width/4)+col/4][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Then smooth left-to-right */ ipix[0] = ipix[1] = ipix[2] = 0; for (col=0; col < (width & ~3); col++) FORC3 smrow[1][col][c] = ipix[c] = (smrow[0][col][c]*1485 + ipix[c]*6707 + 4096) >> 13; /* Smooth top-to-bottom */ if (row == 0) memcpy (smrow[2], smrow[1], sizeof **smrow * width); else for (col=0; col < (width & ~3); col++) FORC3 smrow[2][col][c] = (smrow[2][col][c]*6707 + smrow[1][col][c]*1485 + 4096) >> 13; /* Adjust the chroma toward the smooth values */ for (col=0; col < (width & ~3); col++) { for (i=j=30, c=0; c < 3; c++) { i += smrow[2][col][c]; j += image[row*width+col][c]; } j = (j << 16) / i; for (sum=c=0; c < 3; c++) { ipix[c] = foveon_apply_curve (t_curve[c+3], ((smrow[2][col][c] * j + 0x8000) >> 16) - image[row*width+col][c]); sum += ipix[c]; } sum >>= 3; FORC3 { i = image[row*width+col][c] + ipix[c] - sum; if (i < 0) i = 0; image[row*width+col][c] = i; } } } free (t_shrink); free (smrow[6]); for (i=0; i < 8; i++) free (t_curve[i]); /* Trim off the black border */ if (~cropbox[2] && ~cropbox[3]) { // Image already cropped, do nothing int crop[4],c; for(int c=0;c<4;c++) { crop[c] = cropbox[c]; if(crop[c]<0) crop[c]=0; } if(crop[0]>=width-1) crop[0] = width - 2; if(crop[1]>=height-1) crop[1] = height-2; if(crop[0]+crop[2] >= width) crop[2] = width-crop[0]; if(crop[1]+crop[3] >= height) crop[3] = height-crop[1]; active[0] = crop[0]; active[1] = crop[1]; active[2] = crop[0]+crop[2]; active[3] = crop[1]+crop[3]; } else { active[1] -= keep[1]; active[3] -= 2; } i = active[2] - active[0]; for (row=0; row < active[3]-active[1]; row++) memcpy (image[row*i], image[(row+active[1])*width+active[0]], i * sizeof *image); width = i; height = row; } #undef image #ifdef LIBRAW_LIBRARY_BUILD #define image (imgdata.image) #endif /* RESTRICTED code ends here */
./CrossVul/dataset_final_sorted/CWE-190/c/good_3226_0
crossvul-cpp_data_good_3237_0
/* Capstone Disassembly Engine */ /* By Satoshi Tanda <tanda.sat@gmail.com>, 2016 */ #include "winkernel_mm.h" #include <ntddk.h> #include <Ntintsafe.h> // A pool tag for memory allocation static const ULONG CS_WINKERNEL_POOL_TAG = 'kwsC'; // A structure to implement realloc() typedef struct _CS_WINKERNEL_MEMBLOCK { size_t size; // A number of bytes allocated char data[1]; // An address returned to a caller } CS_WINKERNEL_MEMBLOCK; C_ASSERT(sizeof(CS_WINKERNEL_MEMBLOCK) == sizeof(void *) * 2); // free() void CAPSTONE_API cs_winkernel_free(void *ptr) { if (ptr) { ExFreePoolWithTag(CONTAINING_RECORD(ptr, CS_WINKERNEL_MEMBLOCK, data), CS_WINKERNEL_POOL_TAG); } } // malloc() void * CAPSTONE_API cs_winkernel_malloc(size_t size) { // Disallow zero length allocation because they waste pool header space and, // in many cases, indicate a potential validation issue in the calling code. NT_ASSERT(size); // FP; a use of NonPagedPool is required for Windows 7 support #pragma prefast(suppress : 30030) // Allocating executable POOL_TYPE memory size_t number_of_bytes = 0; CS_WINKERNEL_MEMBLOCK *block = NULL; // A specially crafted size value can trigger the overflow. // If the sum in a value that overflows or underflows the capacity of the type, // the function returns NULL. if (!NT_SUCCESS(RtlSizeTAdd(size, sizeof(CS_WINKERNEL_MEMBLOCK), &number_of_bytes))) { return NULL; } block = (CS_WINKERNEL_MEMBLOCK *)ExAllocatePoolWithTag( NonPagedPool, number_of_bytes, CS_WINKERNEL_POOL_TAG); if (!block) { return NULL; } block->size = size; return block->data; } // calloc() void * CAPSTONE_API cs_winkernel_calloc(size_t n, size_t size) { size_t total = n * size; void *new_ptr = cs_winkernel_malloc(total); if (!new_ptr) { return NULL; } return RtlFillMemory(new_ptr, total, 0); } // realloc() void * CAPSTONE_API cs_winkernel_realloc(void *ptr, size_t size) { void *new_ptr = NULL; size_t current_size = 0; size_t smaller_size = 0; if (!ptr) { return cs_winkernel_malloc(size); } new_ptr = cs_winkernel_malloc(size); if (!new_ptr) { return NULL; } current_size = CONTAINING_RECORD(ptr, CS_WINKERNEL_MEMBLOCK, data)->size; smaller_size = (current_size < size) ? current_size : size; RtlCopyMemory(new_ptr, ptr, smaller_size); cs_winkernel_free(ptr); return new_ptr; } // vsnprintf(). _vsnprintf() is available for drivers, but it differs from // vsnprintf() in a return value and when a null-terminator is set. // cs_winkernel_vsnprintf() takes care of those differences. #pragma warning(push) // Banned API Usage : _vsnprintf is a Banned API as listed in dontuse.h for // security purposes. #pragma warning(disable : 28719) int CAPSTONE_API cs_winkernel_vsnprintf(char *buffer, size_t count, const char *format, va_list argptr) { int result = _vsnprintf(buffer, count, format, argptr); // _vsnprintf() returns -1 when a string is truncated, and returns "count" // when an entire string is stored but without '\0' at the end of "buffer". // In both cases, null-terminator needs to be added manually. if (result == -1 || (size_t)result == count) { buffer[count - 1] = '\0'; } if (result == -1) { // In case when -1 is returned, the function has to get and return a number // of characters that would have been written. This attempts so by retrying // the same conversion with temp buffer that is most likely big enough to // complete formatting and get a number of characters that would have been // written. char* tmp = cs_winkernel_malloc(0x1000); if (!tmp) { return result; } result = _vsnprintf(tmp, 0x1000, format, argptr); NT_ASSERT(result != -1); cs_winkernel_free(tmp); } return result; } #pragma warning(pop)
./CrossVul/dataset_final_sorted/CWE-190/c/good_3237_0
crossvul-cpp_data_good_5202_0
/*- * Copyright (c) 2009-2012 Michihiro NAKAJIMA * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``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 AUTHOR(S) 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. */ #include "archive_platform.h" #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_SYS_UTSNAME_H #include <sys/utsname.h> #endif #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include <stdio.h> #include <stdarg.h> #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #include <time.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_ZLIB_H #include <zlib.h> #endif #include "archive.h" #include "archive_endian.h" #include "archive_entry.h" #include "archive_entry_locale.h" #include "archive_private.h" #include "archive_rb.h" #include "archive_write_private.h" #if defined(_WIN32) && !defined(__CYGWIN__) #define getuid() 0 #define getgid() 0 #endif /*#define DEBUG 1*/ #ifdef DEBUG /* To compare to the ISO image file made by mkisofs. */ #define COMPAT_MKISOFS 1 #endif #define LOGICAL_BLOCK_BITS 11 #define LOGICAL_BLOCK_SIZE 2048 #define PATH_TABLE_BLOCK_SIZE 4096 #define SYSTEM_AREA_BLOCK 16 #define PRIMARY_VOLUME_DESCRIPTOR_BLOCK 1 #define SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK 1 #define BOOT_RECORD_DESCRIPTOR_BLOCK 1 #define VOLUME_DESCRIPTOR_SET_TERMINATOR_BLOCK 1 #define NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK 1 #define RRIP_ER_BLOCK 1 #define PADDING_BLOCK 150 #define FD_1_2M_SIZE (1024 * 1200) #define FD_1_44M_SIZE (1024 * 1440) #define FD_2_88M_SIZE (1024 * 2880) #define MULTI_EXTENT_SIZE (ARCHIVE_LITERAL_LL(1) << 32) /* 4Gi bytes. */ #define MAX_DEPTH 8 #define RR_CE_SIZE 28 /* SUSP "CE" extension size */ #define FILE_FLAG_EXISTENCE 0x01 #define FILE_FLAG_DIRECTORY 0x02 #define FILE_FLAG_ASSOCIATED 0x04 #define FILE_FLAG_RECORD 0x08 #define FILE_FLAG_PROTECTION 0x10 #define FILE_FLAG_MULTI_EXTENT 0x80 static const char rrip_identifier[] = "RRIP_1991A"; static const char rrip_descriptor[] = "THE ROCK RIDGE INTERCHANGE PROTOCOL PROVIDES SUPPORT FOR " "POSIX FILE SYSTEM SEMANTICS"; static const char rrip_source[] = "PLEASE CONTACT DISC PUBLISHER FOR SPECIFICATION SOURCE. " "SEE PUBLISHER IDENTIFIER IN PRIMARY VOLUME DESCRIPTOR FOR " "CONTACT INFORMATION."; #define RRIP_ER_ID_SIZE (sizeof(rrip_identifier)-1) #define RRIP_ER_DSC_SIZE (sizeof(rrip_descriptor)-1) #define RRIP_ER_SRC_SIZE (sizeof(rrip_source)-1) #define RRIP_ER_SIZE (8 + RRIP_ER_ID_SIZE + \ RRIP_ER_DSC_SIZE + RRIP_ER_SRC_SIZE) static const unsigned char zisofs_magic[8] = { 0x37, 0xE4, 0x53, 0x96, 0xC9, 0xDB, 0xD6, 0x07 }; #define ZF_HEADER_SIZE 16 /* zisofs header size. */ #define ZF_LOG2_BS 15 /* log2 block size; 32K bytes. */ #define ZF_BLOCK_SIZE (1UL << ZF_LOG2_BS) /* * Manage extra records. */ struct extr_rec { int location; int offset; unsigned char buf[LOGICAL_BLOCK_SIZE]; struct extr_rec *next; }; struct ctl_extr_rec { int use_extr; unsigned char *bp; struct isoent *isoent; unsigned char *ce_ptr; int cur_len; int dr_len; int limit; int extr_off; int extr_loc; }; #define DR_SAFETY RR_CE_SIZE #define DR_LIMIT (254 - DR_SAFETY) /* * The relation of struct isofile and isoent and archive_entry. * * Primary volume tree --> struct isoent * | * v * struct isofile --> archive_entry * ^ * | * Joliet volume tree --> struct isoent * * struct isoent has specific information for volume. */ struct isofile { /* Used for managing struct isofile list. */ struct isofile *allnext; struct isofile *datanext; /* Used for managing a hardlined struct isofile list. */ struct isofile *hlnext; struct isofile *hardlink_target; struct archive_entry *entry; /* * Used for making a directory tree. */ struct archive_string parentdir; struct archive_string basename; struct archive_string basename_utf16; struct archive_string symlink; int dircnt; /* The number of elements of * its parent directory */ /* * Used for a Directory Record. */ struct content { int64_t offset_of_temp; int64_t size; int blocks; uint32_t location; /* * One extent equals one content. * If this entry has multi extent, `next' variable points * next content data. */ struct content *next; /* next content */ } content, *cur_content; int write_content; enum { NO = 0, BOOT_CATALOG, BOOT_IMAGE } boot; /* * Used for a zisofs. */ struct { unsigned char header_size; unsigned char log2_bs; uint32_t uncompressed_size; } zisofs; }; struct isoent { /* Keep `rbnode' at the first member of struct isoent. */ struct archive_rb_node rbnode; struct isofile *file; struct isoent *parent; /* A list of children.(use chnext) */ struct { struct isoent *first; struct isoent **last; int cnt; } children; struct archive_rb_tree rbtree; /* A list of sub directories.(use drnext) */ struct { struct isoent *first; struct isoent **last; int cnt; } subdirs; /* A sorted list of sub directories. */ struct isoent **children_sorted; /* Used for managing struct isoent list. */ struct isoent *chnext; struct isoent *drnext; struct isoent *ptnext; /* * Used for making a Directory Record. */ int dir_number; struct { int vd; int self; int parent; int normal; } dr_len; uint32_t dir_location; int dir_block; /* * Identifier: * on primary, ISO9660 file/directory name. * on joliet, UCS2 file/directory name. * ext_off : offset of identifier extension. * ext_len : length of identifier extension. * id_len : byte size of identifier. * on primary, this is ext_off + ext_len + version length. * on joliet, this is ext_off + ext_len. * mb_len : length of multibyte-character of identifier. * on primary, mb_len and id_len are always the same. * on joliet, mb_len and id_len are different. */ char *identifier; int ext_off; int ext_len; int id_len; int mb_len; /* * Used for making a Rockridge extension. * This is a part of Directory Records. */ struct isoent *rr_parent; struct isoent *rr_child; /* Extra Record.(which we call in this source file) * A maximum size of the Directory Record is 254. * so, if generated RRIP data of a file cannot into a Directory * Record because of its size, that surplus data relocate this * Extra Record. */ struct { struct extr_rec *first; struct extr_rec **last; struct extr_rec *current; } extr_rec_list; int virtual:1; /* If set to one, this file type is a directory. * A convenience flag to be used as * "archive_entry_filetype(isoent->file->entry) == AE_IFDIR". */ int dir:1; }; struct hardlink { struct archive_rb_node rbnode; int nlink; struct { struct isofile *first; struct isofile **last; } file_list; }; /* * ISO writer options */ struct iso_option { /* * Usage : abstract-file=<value> * Type : string, max 37 bytes * Default: Not specified * COMPAT : mkisofs -abstract <value> * * Specifies Abstract Filename. * This file shall be described in the Root Directory * and containing a abstract statement. */ unsigned int abstract_file:1; #define OPT_ABSTRACT_FILE_DEFAULT 0 /* Not specified */ #define ABSTRACT_FILE_SIZE 37 /* * Usage : application-id=<value> * Type : string, max 128 bytes * Default: Not specified * COMPAT : mkisofs -A/-appid <value>. * * Specifies Application Identifier. * If the first byte is set to '_'(5F), the remaining * bytes of this option shall specify an identifier * for a file containing the identification of the * application. * This file shall be described in the Root Directory. */ unsigned int application_id:1; #define OPT_APPLICATION_ID_DEFAULT 0 /* Use default identifier */ #define APPLICATION_IDENTIFIER_SIZE 128 /* * Usage : !allow-vernum * Type : boolean * Default: Enabled * : Violates the ISO9660 standard if disable. * COMPAT: mkisofs -N * * Allow filenames to use version numbers. */ unsigned int allow_vernum:1; #define OPT_ALLOW_VERNUM_DEFAULT 1 /* Enabled */ /* * Usage : biblio-file=<value> * Type : string, max 37 bytes * Default: Not specified * COMPAT : mkisofs -biblio <value> * * Specifies Bibliographic Filename. * This file shall be described in the Root Directory * and containing bibliographic records. */ unsigned int biblio_file:1; #define OPT_BIBLIO_FILE_DEFAULT 0 /* Not specified */ #define BIBLIO_FILE_SIZE 37 /* * Usage : boot=<value> * Type : string * Default: Not specified * COMPAT : mkisofs -b/-eltorito-boot <value> * * Specifies "El Torito" boot image file to make * a bootable CD. */ unsigned int boot:1; #define OPT_BOOT_DEFAULT 0 /* Not specified */ /* * Usage : boot-catalog=<value> * Type : string * Default: "boot.catalog" * COMPAT : mkisofs -c/-eltorito-catalog <value> * * Specifies a fullpath of El Torito boot catalog. */ unsigned int boot_catalog:1; #define OPT_BOOT_CATALOG_DEFAULT 0 /* Not specified */ /* * Usage : boot-info-table * Type : boolean * Default: Disabled * COMPAT : mkisofs -boot-info-table * * Modify the boot image file specified by `boot' * option; ISO writer stores boot file information * into the boot file in ISO image at offset 8 * through offset 64. */ unsigned int boot_info_table:1; #define OPT_BOOT_INFO_TABLE_DEFAULT 0 /* Disabled */ /* * Usage : boot-load-seg=<value> * Type : hexadecimal * Default: Not specified * COMPAT : mkisofs -boot-load-seg <value> * * Specifies a load segment for boot image. * This is used with no-emulation mode. */ unsigned int boot_load_seg:1; #define OPT_BOOT_LOAD_SEG_DEFAULT 0 /* Not specified */ /* * Usage : boot-load-size=<value> * Type : decimal * Default: Not specified * COMPAT : mkisofs -boot-load-size <value> * * Specifies a sector count for boot image. * This is used with no-emulation mode. */ unsigned int boot_load_size:1; #define OPT_BOOT_LOAD_SIZE_DEFAULT 0 /* Not specified */ /* * Usage : boot-type=<boot-media-type> * : 'no-emulation' : 'no emulation' image * : 'fd' : floppy disk image * : 'hard-disk' : hard disk image * Type : string * Default: Auto detect * : We check a size of boot image; * : If ths size is just 1.22M/1.44M/2.88M, * : we assume boot_type is 'fd'; * : otherwise boot_type is 'no-emulation'. * COMPAT : * boot=no-emulation * mkisofs -no-emul-boot * boot=fd * This is a default on the mkisofs. * boot=hard-disk * mkisofs -hard-disk-boot * * Specifies a type of "El Torito" boot image. */ unsigned int boot_type:2; #define OPT_BOOT_TYPE_AUTO 0 /* auto detect */ #define OPT_BOOT_TYPE_NO_EMU 1 /* ``no emulation'' image */ #define OPT_BOOT_TYPE_FD 2 /* floppy disk image */ #define OPT_BOOT_TYPE_HARD_DISK 3 /* hard disk image */ #define OPT_BOOT_TYPE_DEFAULT OPT_BOOT_TYPE_AUTO /* * Usage : compression-level=<value> * Type : decimal * Default: Not specified * COMPAT : NONE * * Specifies compression level for option zisofs=direct. */ unsigned int compression_level:1; #define OPT_COMPRESSION_LEVEL_DEFAULT 0 /* Not specified */ /* * Usage : copyright-file=<value> * Type : string, max 37 bytes * Default: Not specified * COMPAT : mkisofs -copyright <value> * * Specifies Copyright Filename. * This file shall be described in the Root Directory * and containing a copyright statement. */ unsigned int copyright_file:1; #define OPT_COPYRIGHT_FILE_DEFAULT 0 /* Not specified */ #define COPYRIGHT_FILE_SIZE 37 /* * Usage : gid=<value> * Type : decimal * Default: Not specified * COMPAT : mkisofs -gid <value> * * Specifies a group id to rewrite the group id of all files. */ unsigned int gid:1; #define OPT_GID_DEFAULT 0 /* Not specified */ /* * Usage : iso-level=[1234] * Type : decimal * Default: 1 * COMPAT : mkisofs -iso-level <value> * * Specifies ISO9600 Level. * Level 1: [DEFAULT] * - limits each file size less than 4Gi bytes; * - a File Name shall not contain more than eight * d-characters or eight d1-characters; * - a File Name Extension shall not contain more than * three d-characters or three d1-characters; * - a Directory Identifier shall not contain more * than eight d-characters or eight d1-characters. * Level 2: * - limits each file size less than 4Giga bytes; * - a File Name shall not contain more than thirty * d-characters or thirty d1-characters; * - a File Name Extension shall not contain more than * thirty d-characters or thirty d1-characters; * - a Directory Identifier shall not contain more * than thirty-one d-characters or thirty-one * d1-characters. * Level 3: * - no limit of file size; use multi extent. * Level 4: * - this level 4 simulates mkisofs option * '-iso-level 4'; * - crate a enhanced volume as mkisofs doing; * - allow a File Name to have leading dot; * - allow a File Name to have all ASCII letters; * - allow a File Name to have multiple dots; * - allow more then 8 depths of directory trees; * - disable a version number to a File Name; * - disable a forced period to the tail of a File Name; * - the maxinum length of files and directories is raised to 193. * if rockridge option is disabled, raised to 207. */ unsigned int iso_level:3; #define OPT_ISO_LEVEL_DEFAULT 1 /* ISO Level 1 */ /* * Usage : joliet[=long] * : !joliet * : Do not generate Joliet Volume and Records. * : joliet [DEFAULT] * : Generates Joliet Volume and Directory Records. * : [COMPAT: mkisofs -J/-joliet] * : joliet=long * : The joliet filenames are up to 103 Unicode * : characters. * : This option breaks the Joliet specification. * : [COMPAT: mkisofs -J -joliet-long] * Type : boolean/string * Default: Enabled * COMPAT : mkisofs -J / -joliet-long * * Generates Joliet Volume and Directory Records. */ unsigned int joliet:2; #define OPT_JOLIET_DISABLE 0 /* Not generate Joliet Records. */ #define OPT_JOLIET_ENABLE 1 /* Generate Joliet Records. */ #define OPT_JOLIET_LONGNAME 2 /* Use long joliet filenames.*/ #define OPT_JOLIET_DEFAULT OPT_JOLIET_ENABLE /* * Usage : !limit-depth * Type : boolean * Default: Enabled * : Violates the ISO9660 standard if disable. * COMPAT : mkisofs -D/-disable-deep-relocation * * The number of levels in hierarchy cannot exceed eight. */ unsigned int limit_depth:1; #define OPT_LIMIT_DEPTH_DEFAULT 1 /* Enabled */ /* * Usage : !limit-dirs * Type : boolean * Default: Enabled * : Violates the ISO9660 standard if disable. * COMPAT : mkisofs -no-limit-pathtables * * Limits the number of directories less than 65536 due * to the size of the Parent Directory Number of Path * Table. */ unsigned int limit_dirs:1; #define OPT_LIMIT_DIRS_DEFAULT 1 /* Enabled */ /* * Usage : !pad * Type : boolean * Default: Enabled * COMPAT : -pad/-no-pad * * Pads the end of the ISO image by null of 300Ki bytes. */ unsigned int pad:1; #define OPT_PAD_DEFAULT 1 /* Enabled */ /* * Usage : publisher=<value> * Type : string, max 128 bytes * Default: Not specified * COMPAT : mkisofs -publisher <value> * * Specifies Publisher Identifier. * If the first byte is set to '_'(5F), the remaining * bytes of this option shall specify an identifier * for a file containing the identification of the user. * This file shall be described in the Root Directory. */ unsigned int publisher:1; #define OPT_PUBLISHER_DEFAULT 0 /* Not specified */ #define PUBLISHER_IDENTIFIER_SIZE 128 /* * Usage : rockridge * : !rockridge * : disable to generate SUSP and RR records. * : rockridge * : the same as 'rockridge=useful'. * : rockridge=strict * : generate SUSP and RR records. * : [COMPAT: mkisofs -R] * : rockridge=useful [DEFAULT] * : generate SUSP and RR records. * : [COMPAT: mkisofs -r] * : NOTE Our rockridge=useful option does not set a zero * : to uid and gid, you should use application * : option such as --gid,--gname,--uid and --uname * : badtar options instead. * Type : boolean/string * Default: Enabled as rockridge=useful * COMPAT : mkisofs -r / -R * * Generates SUSP and RR records. */ unsigned int rr:2; #define OPT_RR_DISABLED 0 #define OPT_RR_STRICT 1 #define OPT_RR_USEFUL 2 #define OPT_RR_DEFAULT OPT_RR_USEFUL /* * Usage : volume-id=<value> * Type : string, max 32 bytes * Default: Not specified * COMPAT : mkisofs -V <value> * * Specifies Volume Identifier. */ unsigned int volume_id:1; #define OPT_VOLUME_ID_DEFAULT 0 /* Use default identifier */ #define VOLUME_IDENTIFIER_SIZE 32 /* * Usage : !zisofs [DEFAULT] * : Disable to generate RRIP 'ZF' extension. * : zisofs * : Make files zisofs file and generate RRIP 'ZF' * : extension. So you do not need mkzftree utility * : for making zisofs. * : When the file size is less than one Logical Block * : size, that file will not zisofs'ed since it does * : reduece an ISO-image size. * : * : When you specify option 'boot=<boot-image>', that * : 'boot-image' file won't be converted to zisofs file. * Type : boolean * Default: Disabled * * Generates RRIP 'ZF' System Use Entry. */ unsigned int zisofs:1; #define OPT_ZISOFS_DISABLED 0 #define OPT_ZISOFS_DIRECT 1 #define OPT_ZISOFS_DEFAULT OPT_ZISOFS_DISABLED }; struct iso9660 { /* The creation time of ISO image. */ time_t birth_time; /* A file stream of a temporary file, which file contents * save to until ISO iamge can be created. */ int temp_fd; struct isofile *cur_file; struct isoent *cur_dirent; struct archive_string cur_dirstr; uint64_t bytes_remaining; int need_multi_extent; /* Temporary string buffer for Joliet extension. */ struct archive_string utf16be; struct archive_string mbs; struct archive_string_conv *sconv_to_utf16be; struct archive_string_conv *sconv_from_utf16be; /* A list of all of struct isofile entries. */ struct { struct isofile *first; struct isofile **last; } all_file_list; /* A list of struct isofile entries which have its * contents and are not a directory, a hardlined file * and a symlink file. */ struct { struct isofile *first; struct isofile **last; } data_file_list; /* Used for managing to find hardlinking files. */ struct archive_rb_tree hardlink_rbtree; /* Used for making the Path Table Record. */ struct vdd { /* the root of entry tree. */ struct isoent *rootent; enum vdd_type { VDD_PRIMARY, VDD_JOLIET, VDD_ENHANCED } vdd_type; struct path_table { struct isoent *first; struct isoent **last; struct isoent **sorted; int cnt; } *pathtbl; int max_depth; int path_table_block; int path_table_size; int location_type_L_path_table; int location_type_M_path_table; int total_dir_block; } primary, joliet; /* Used for making a Volume Descriptor. */ int volume_space_size; int volume_sequence_number; int total_file_block; struct archive_string volume_identifier; struct archive_string publisher_identifier; struct archive_string data_preparer_identifier; struct archive_string application_identifier; struct archive_string copyright_file_identifier; struct archive_string abstract_file_identifier; struct archive_string bibliographic_file_identifier; /* Used for making rockridge extensions. */ int location_rrip_er; /* Used for making zisofs. */ struct { int detect_magic:1; int making:1; int allzero:1; unsigned char magic_buffer[64]; int magic_cnt; #ifdef HAVE_ZLIB_H /* * Copy a compressed file to iso9660.zisofs.temp_fd * and also copy a uncompressed file(original file) to * iso9660.temp_fd . If the number of logical block * of the compressed file is less than the number of * logical block of the uncompressed file, use it and * remove the copy of the uncompressed file. * but if not, we use uncompressed file and remove * the copy of the compressed file. */ uint32_t *block_pointers; size_t block_pointers_allocated; int block_pointers_cnt; int block_pointers_idx; int64_t total_size; int64_t block_offset; z_stream stream; int stream_valid; int64_t remaining; int compression_level; #endif } zisofs; struct isoent *directories_too_deep; int dircnt_max; /* Write buffer. */ #define wb_buffmax() (LOGICAL_BLOCK_SIZE * 32) #define wb_remaining(a) (((struct iso9660 *)(a)->format_data)->wbuff_remaining) #define wb_offset(a) (((struct iso9660 *)(a)->format_data)->wbuff_offset \ + wb_buffmax() - wb_remaining(a)) unsigned char wbuff[LOGICAL_BLOCK_SIZE * 32]; size_t wbuff_remaining; enum { WB_TO_STREAM, WB_TO_TEMP } wbuff_type; int64_t wbuff_offset; int64_t wbuff_written; int64_t wbuff_tail; /* 'El Torito' boot data. */ struct { /* boot catalog file */ struct archive_string catalog_filename; struct isoent *catalog; /* boot image file */ struct archive_string boot_filename; struct isoent *boot; unsigned char platform_id; #define BOOT_PLATFORM_X86 0 #define BOOT_PLATFORM_PPC 1 #define BOOT_PLATFORM_MAC 2 struct archive_string id; unsigned char media_type; #define BOOT_MEDIA_NO_EMULATION 0 #define BOOT_MEDIA_1_2M_DISKETTE 1 #define BOOT_MEDIA_1_44M_DISKETTE 2 #define BOOT_MEDIA_2_88M_DISKETTE 3 #define BOOT_MEDIA_HARD_DISK 4 unsigned char system_type; uint16_t boot_load_seg; uint16_t boot_load_size; #define BOOT_LOAD_SIZE 4 } el_torito; struct iso_option opt; }; /* * Types of Volume Descriptor */ enum VD_type { VDT_BOOT_RECORD=0, /* Boot Record Volume Descriptor */ VDT_PRIMARY=1, /* Primary Volume Descriptor */ VDT_SUPPLEMENTARY=2, /* Supplementary Volume Descriptor */ VDT_TERMINATOR=255 /* Volume Descriptor Set Terminator */ }; /* * Types of Directory Record */ enum dir_rec_type { DIR_REC_VD, /* Stored in Volume Descriptor. */ DIR_REC_SELF, /* Stored as Current Directory. */ DIR_REC_PARENT, /* Stored as Parent Directory. */ DIR_REC_NORMAL /* Stored as Child. */ }; /* * Kinds of Volume Descriptor Character */ enum vdc { VDC_STD, VDC_LOWERCASE, VDC_UCS2, VDC_UCS2_DIRECT }; /* * IDentifier Resolver. * Used for resolving duplicated filenames. */ struct idr { struct idrent { struct archive_rb_node rbnode; /* Used in wait_list. */ struct idrent *wnext; struct idrent *avail; struct isoent *isoent; int weight; int noff; int rename_num; } *idrent_pool; struct archive_rb_tree rbtree; struct { struct idrent *first; struct idrent **last; } wait_list; int pool_size; int pool_idx; int num_size; int null_size; char char_map[0x80]; }; enum char_type { A_CHAR, D_CHAR }; static int iso9660_options(struct archive_write *, const char *, const char *); static int iso9660_write_header(struct archive_write *, struct archive_entry *); static ssize_t iso9660_write_data(struct archive_write *, const void *, size_t); static int iso9660_finish_entry(struct archive_write *); static int iso9660_close(struct archive_write *); static int iso9660_free(struct archive_write *); static void get_system_identitier(char *, size_t); static void set_str(unsigned char *, const char *, size_t, char, const char *); static inline int joliet_allowed_char(unsigned char, unsigned char); static int set_str_utf16be(struct archive_write *, unsigned char *, const char *, size_t, uint16_t, enum vdc); static int set_str_a_characters_bp(struct archive_write *, unsigned char *, int, int, const char *, enum vdc); static int set_str_d_characters_bp(struct archive_write *, unsigned char *, int, int, const char *, enum vdc); static void set_VD_bp(unsigned char *, enum VD_type, unsigned char); static inline void set_unused_field_bp(unsigned char *, int, int); static unsigned char *extra_open_record(unsigned char *, int, struct isoent *, struct ctl_extr_rec *); static void extra_close_record(struct ctl_extr_rec *, int); static unsigned char * extra_next_record(struct ctl_extr_rec *, int); static unsigned char *extra_get_record(struct isoent *, int *, int *, int *); static void extra_tell_used_size(struct ctl_extr_rec *, int); static int extra_setup_location(struct isoent *, int); static int set_directory_record_rr(unsigned char *, int, struct isoent *, struct iso9660 *, enum dir_rec_type); static int set_directory_record(unsigned char *, size_t, struct isoent *, struct iso9660 *, enum dir_rec_type, enum vdd_type); static inline int get_dir_rec_size(struct iso9660 *, struct isoent *, enum dir_rec_type, enum vdd_type); static inline unsigned char *wb_buffptr(struct archive_write *); static int wb_write_out(struct archive_write *); static int wb_consume(struct archive_write *, size_t); #ifdef HAVE_ZLIB_H static int wb_set_offset(struct archive_write *, int64_t); #endif static int write_null(struct archive_write *, size_t); static int write_VD_terminator(struct archive_write *); static int set_file_identifier(unsigned char *, int, int, enum vdc, struct archive_write *, struct vdd *, struct archive_string *, const char *, int, enum char_type); static int write_VD(struct archive_write *, struct vdd *); static int write_VD_boot_record(struct archive_write *); static int write_information_block(struct archive_write *); static int write_path_table(struct archive_write *, int, struct vdd *); static int write_directory_descriptors(struct archive_write *, struct vdd *); static int write_file_descriptors(struct archive_write *); static int write_rr_ER(struct archive_write *); static void calculate_path_table_size(struct vdd *); static void isofile_init_entry_list(struct iso9660 *); static void isofile_add_entry(struct iso9660 *, struct isofile *); static void isofile_free_all_entries(struct iso9660 *); static void isofile_init_entry_data_file_list(struct iso9660 *); static void isofile_add_data_file(struct iso9660 *, struct isofile *); static struct isofile * isofile_new(struct archive_write *, struct archive_entry *); static void isofile_free(struct isofile *); static int isofile_gen_utility_names(struct archive_write *, struct isofile *); static int isofile_register_hardlink(struct archive_write *, struct isofile *); static void isofile_connect_hardlink_files(struct iso9660 *); static void isofile_init_hardlinks(struct iso9660 *); static void isofile_free_hardlinks(struct iso9660 *); static struct isoent *isoent_new(struct isofile *); static int isoent_clone_tree(struct archive_write *, struct isoent **, struct isoent *); static void _isoent_free(struct isoent *isoent); static void isoent_free_all(struct isoent *); static struct isoent * isoent_create_virtual_dir(struct archive_write *, struct iso9660 *, const char *); static int isoent_cmp_node(const struct archive_rb_node *, const struct archive_rb_node *); static int isoent_cmp_key(const struct archive_rb_node *, const void *); static int isoent_add_child_head(struct isoent *, struct isoent *); static int isoent_add_child_tail(struct isoent *, struct isoent *); static void isoent_remove_child(struct isoent *, struct isoent *); static void isoent_setup_directory_location(struct iso9660 *, int, struct vdd *); static void isoent_setup_file_location(struct iso9660 *, int); static int get_path_component(char *, size_t, const char *); static int isoent_tree(struct archive_write *, struct isoent **); static struct isoent *isoent_find_child(struct isoent *, const char *); static struct isoent *isoent_find_entry(struct isoent *, const char *); static void idr_relaxed_filenames(char *); static void idr_init(struct iso9660 *, struct vdd *, struct idr *); static void idr_cleanup(struct idr *); static int idr_ensure_poolsize(struct archive_write *, struct idr *, int); static int idr_start(struct archive_write *, struct idr *, int, int, int, int, const struct archive_rb_tree_ops *); static void idr_register(struct idr *, struct isoent *, int, int); static void idr_extend_identifier(struct idrent *, int, int); static void idr_resolve(struct idr *, void (*)(unsigned char *, int)); static void idr_set_num(unsigned char *, int); static void idr_set_num_beutf16(unsigned char *, int); static int isoent_gen_iso9660_identifier(struct archive_write *, struct isoent *, struct idr *); static int isoent_gen_joliet_identifier(struct archive_write *, struct isoent *, struct idr *); static int isoent_cmp_iso9660_identifier(const struct isoent *, const struct isoent *); static int isoent_cmp_node_iso9660(const struct archive_rb_node *, const struct archive_rb_node *); static int isoent_cmp_key_iso9660(const struct archive_rb_node *, const void *); static int isoent_cmp_joliet_identifier(const struct isoent *, const struct isoent *); static int isoent_cmp_node_joliet(const struct archive_rb_node *, const struct archive_rb_node *); static int isoent_cmp_key_joliet(const struct archive_rb_node *, const void *); static inline void path_table_add_entry(struct path_table *, struct isoent *); static inline struct isoent * path_table_last_entry(struct path_table *); static int isoent_make_path_table(struct archive_write *); static int isoent_find_out_boot_file(struct archive_write *, struct isoent *); static int isoent_create_boot_catalog(struct archive_write *, struct isoent *); static size_t fd_boot_image_size(int); static int make_boot_catalog(struct archive_write *); static int setup_boot_information(struct archive_write *); static int zisofs_init(struct archive_write *, struct isofile *); static void zisofs_detect_magic(struct archive_write *, const void *, size_t); static int zisofs_write_to_temp(struct archive_write *, const void *, size_t); static int zisofs_finish_entry(struct archive_write *); static int zisofs_rewind_boot_file(struct archive_write *); static int zisofs_free(struct archive_write *); int archive_write_set_format_iso9660(struct archive *_a) { struct archive_write *a = (struct archive_write *)_a; struct iso9660 *iso9660; archive_check_magic(_a, ARCHIVE_WRITE_MAGIC, ARCHIVE_STATE_NEW, "archive_write_set_format_iso9660"); /* If another format was already registered, unregister it. */ if (a->format_free != NULL) (a->format_free)(a); iso9660 = calloc(1, sizeof(*iso9660)); if (iso9660 == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate iso9660 data"); return (ARCHIVE_FATAL); } iso9660->birth_time = 0; iso9660->temp_fd = -1; iso9660->cur_file = NULL; iso9660->primary.max_depth = 0; iso9660->primary.vdd_type = VDD_PRIMARY; iso9660->primary.pathtbl = NULL; iso9660->joliet.rootent = NULL; iso9660->joliet.max_depth = 0; iso9660->joliet.vdd_type = VDD_JOLIET; iso9660->joliet.pathtbl = NULL; isofile_init_entry_list(iso9660); isofile_init_entry_data_file_list(iso9660); isofile_init_hardlinks(iso9660); iso9660->directories_too_deep = NULL; iso9660->dircnt_max = 1; iso9660->wbuff_remaining = wb_buffmax(); iso9660->wbuff_type = WB_TO_TEMP; iso9660->wbuff_offset = 0; iso9660->wbuff_written = 0; iso9660->wbuff_tail = 0; archive_string_init(&(iso9660->utf16be)); archive_string_init(&(iso9660->mbs)); /* * Init Identifiers used for PVD and SVD. */ archive_string_init(&(iso9660->volume_identifier)); archive_strcpy(&(iso9660->volume_identifier), "CDROM"); archive_string_init(&(iso9660->publisher_identifier)); archive_string_init(&(iso9660->data_preparer_identifier)); archive_string_init(&(iso9660->application_identifier)); archive_strcpy(&(iso9660->application_identifier), archive_version_string()); archive_string_init(&(iso9660->copyright_file_identifier)); archive_string_init(&(iso9660->abstract_file_identifier)); archive_string_init(&(iso9660->bibliographic_file_identifier)); /* * Init El Torito bootable CD variables. */ archive_string_init(&(iso9660->el_torito.catalog_filename)); iso9660->el_torito.catalog = NULL; /* Set default file name of boot catalog */ archive_strcpy(&(iso9660->el_torito.catalog_filename), "boot.catalog"); archive_string_init(&(iso9660->el_torito.boot_filename)); iso9660->el_torito.boot = NULL; iso9660->el_torito.platform_id = BOOT_PLATFORM_X86; archive_string_init(&(iso9660->el_torito.id)); iso9660->el_torito.boot_load_seg = 0; iso9660->el_torito.boot_load_size = BOOT_LOAD_SIZE; /* * Init zisofs variables. */ #ifdef HAVE_ZLIB_H iso9660->zisofs.block_pointers = NULL; iso9660->zisofs.block_pointers_allocated = 0; iso9660->zisofs.stream_valid = 0; iso9660->zisofs.compression_level = 9; memset(&(iso9660->zisofs.stream), 0, sizeof(iso9660->zisofs.stream)); #endif /* * Set default value of iso9660 options. */ iso9660->opt.abstract_file = OPT_ABSTRACT_FILE_DEFAULT; iso9660->opt.application_id = OPT_APPLICATION_ID_DEFAULT; iso9660->opt.allow_vernum = OPT_ALLOW_VERNUM_DEFAULT; iso9660->opt.biblio_file = OPT_BIBLIO_FILE_DEFAULT; iso9660->opt.boot = OPT_BOOT_DEFAULT; iso9660->opt.boot_catalog = OPT_BOOT_CATALOG_DEFAULT; iso9660->opt.boot_info_table = OPT_BOOT_INFO_TABLE_DEFAULT; iso9660->opt.boot_load_seg = OPT_BOOT_LOAD_SEG_DEFAULT; iso9660->opt.boot_load_size = OPT_BOOT_LOAD_SIZE_DEFAULT; iso9660->opt.boot_type = OPT_BOOT_TYPE_DEFAULT; iso9660->opt.compression_level = OPT_COMPRESSION_LEVEL_DEFAULT; iso9660->opt.copyright_file = OPT_COPYRIGHT_FILE_DEFAULT; iso9660->opt.iso_level = OPT_ISO_LEVEL_DEFAULT; iso9660->opt.joliet = OPT_JOLIET_DEFAULT; iso9660->opt.limit_depth = OPT_LIMIT_DEPTH_DEFAULT; iso9660->opt.limit_dirs = OPT_LIMIT_DIRS_DEFAULT; iso9660->opt.pad = OPT_PAD_DEFAULT; iso9660->opt.publisher = OPT_PUBLISHER_DEFAULT; iso9660->opt.rr = OPT_RR_DEFAULT; iso9660->opt.volume_id = OPT_VOLUME_ID_DEFAULT; iso9660->opt.zisofs = OPT_ZISOFS_DEFAULT; /* Create the root directory. */ iso9660->primary.rootent = isoent_create_virtual_dir(a, iso9660, ""); if (iso9660->primary.rootent == NULL) { free(iso9660); archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } iso9660->primary.rootent->parent = iso9660->primary.rootent; iso9660->cur_dirent = iso9660->primary.rootent; archive_string_init(&(iso9660->cur_dirstr)); archive_string_ensure(&(iso9660->cur_dirstr), 1); iso9660->cur_dirstr.s[0] = 0; iso9660->sconv_to_utf16be = NULL; iso9660->sconv_from_utf16be = NULL; a->format_data = iso9660; a->format_name = "iso9660"; a->format_options = iso9660_options; a->format_write_header = iso9660_write_header; a->format_write_data = iso9660_write_data; a->format_finish_entry = iso9660_finish_entry; a->format_close = iso9660_close; a->format_free = iso9660_free; a->archive.archive_format = ARCHIVE_FORMAT_ISO9660; a->archive.archive_format_name = "ISO9660"; return (ARCHIVE_OK); } static int get_str_opt(struct archive_write *a, struct archive_string *s, size_t maxsize, const char *key, const char *value) { if (strlen(value) > maxsize) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Value is longer than %zu characters " "for option ``%s''", maxsize, key); return (ARCHIVE_FATAL); } archive_strcpy(s, value); return (ARCHIVE_OK); } static int get_num_opt(struct archive_write *a, int *num, int high, int low, const char *key, const char *value) { const char *p = value; int data = 0; int neg = 0; if (p == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value(empty) for option ``%s''", key); return (ARCHIVE_FATAL); } if (*p == '-') { neg = 1; p++; } while (*p) { if (*p >= '0' && *p <= '9') data = data * 10 + *p - '0'; else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value for option ``%s''", key); return (ARCHIVE_FATAL); } if (data > high) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value(over %d) for " "option ``%s''", high, key); return (ARCHIVE_FATAL); } if (data < low) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value(under %d) for " "option ``%s''", low, key); return (ARCHIVE_FATAL); } p++; } if (neg) data *= -1; *num = data; return (ARCHIVE_OK); } static int iso9660_options(struct archive_write *a, const char *key, const char *value) { struct iso9660 *iso9660 = a->format_data; const char *p; int r; switch (key[0]) { case 'a': if (strcmp(key, "abstract-file") == 0) { r = get_str_opt(a, &(iso9660->abstract_file_identifier), ABSTRACT_FILE_SIZE, key, value); iso9660->opt.abstract_file = r == ARCHIVE_OK; return (r); } if (strcmp(key, "application-id") == 0) { r = get_str_opt(a, &(iso9660->application_identifier), APPLICATION_IDENTIFIER_SIZE, key, value); iso9660->opt.application_id = r == ARCHIVE_OK; return (r); } if (strcmp(key, "allow-vernum") == 0) { iso9660->opt.allow_vernum = value != NULL; return (ARCHIVE_OK); } break; case 'b': if (strcmp(key, "biblio-file") == 0) { r = get_str_opt(a, &(iso9660->bibliographic_file_identifier), BIBLIO_FILE_SIZE, key, value); iso9660->opt.biblio_file = r == ARCHIVE_OK; return (r); } if (strcmp(key, "boot") == 0) { if (value == NULL) iso9660->opt.boot = 0; else { iso9660->opt.boot = 1; archive_strcpy( &(iso9660->el_torito.boot_filename), value); } return (ARCHIVE_OK); } if (strcmp(key, "boot-catalog") == 0) { r = get_str_opt(a, &(iso9660->el_torito.catalog_filename), 1024, key, value); iso9660->opt.boot_catalog = r == ARCHIVE_OK; return (r); } if (strcmp(key, "boot-info-table") == 0) { iso9660->opt.boot_info_table = value != NULL; return (ARCHIVE_OK); } if (strcmp(key, "boot-load-seg") == 0) { uint32_t seg; iso9660->opt.boot_load_seg = 0; if (value == NULL) goto invalid_value; seg = 0; p = value; if (p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) p += 2; while (*p) { if (seg) seg <<= 4; if (*p >= 'A' && *p <= 'F') seg += *p - 'A' + 0x0a; else if (*p >= 'a' && *p <= 'f') seg += *p - 'a' + 0x0a; else if (*p >= '0' && *p <= '9') seg += *p - '0'; else goto invalid_value; if (seg > 0xffff) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value(over 0xffff) for " "option ``%s''", key); return (ARCHIVE_FATAL); } p++; } iso9660->el_torito.boot_load_seg = (uint16_t)seg; iso9660->opt.boot_load_seg = 1; return (ARCHIVE_OK); } if (strcmp(key, "boot-load-size") == 0) { int num = 0; r = get_num_opt(a, &num, 0xffff, 1, key, value); iso9660->opt.boot_load_size = r == ARCHIVE_OK; if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->el_torito.boot_load_size = (uint16_t)num; return (ARCHIVE_OK); } if (strcmp(key, "boot-type") == 0) { if (value == NULL) goto invalid_value; if (strcmp(value, "no-emulation") == 0) iso9660->opt.boot_type = OPT_BOOT_TYPE_NO_EMU; else if (strcmp(value, "fd") == 0) iso9660->opt.boot_type = OPT_BOOT_TYPE_FD; else if (strcmp(value, "hard-disk") == 0) iso9660->opt.boot_type = OPT_BOOT_TYPE_HARD_DISK; else goto invalid_value; return (ARCHIVE_OK); } break; case 'c': if (strcmp(key, "compression-level") == 0) { #ifdef HAVE_ZLIB_H if (value == NULL || !(value[0] >= '0' && value[0] <= '9') || value[1] != '\0') goto invalid_value; iso9660->zisofs.compression_level = value[0] - '0'; iso9660->opt.compression_level = 1; return (ARCHIVE_OK); #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Option ``%s'' " "is not supported on this platform.", key); return (ARCHIVE_FATAL); #endif } if (strcmp(key, "copyright-file") == 0) { r = get_str_opt(a, &(iso9660->copyright_file_identifier), COPYRIGHT_FILE_SIZE, key, value); iso9660->opt.copyright_file = r == ARCHIVE_OK; return (r); } #ifdef DEBUG /* Specifies Volume creation date and time; * year(4),month(2),day(2),hour(2),minute(2),second(2). * e.g. "20090929033757" */ if (strcmp(key, "creation") == 0) { struct tm tm; char buf[5]; p = value; if (p == NULL || strlen(p) < 14) goto invalid_value; memset(&tm, 0, sizeof(tm)); memcpy(buf, p, 4); buf[4] = '\0'; p += 4; tm.tm_year = strtol(buf, NULL, 10) - 1900; memcpy(buf, p, 2); buf[2] = '\0'; p += 2; tm.tm_mon = strtol(buf, NULL, 10) - 1; memcpy(buf, p, 2); buf[2] = '\0'; p += 2; tm.tm_mday = strtol(buf, NULL, 10); memcpy(buf, p, 2); buf[2] = '\0'; p += 2; tm.tm_hour = strtol(buf, NULL, 10); memcpy(buf, p, 2); buf[2] = '\0'; p += 2; tm.tm_min = strtol(buf, NULL, 10); memcpy(buf, p, 2); buf[2] = '\0'; tm.tm_sec = strtol(buf, NULL, 10); iso9660->birth_time = mktime(&tm); return (ARCHIVE_OK); } #endif break; case 'i': if (strcmp(key, "iso-level") == 0) { if (value != NULL && value[1] == '\0' && (value[0] >= '1' && value[0] <= '4')) { iso9660->opt.iso_level = value[0]-'0'; return (ARCHIVE_OK); } goto invalid_value; } break; case 'j': if (strcmp(key, "joliet") == 0) { if (value == NULL) iso9660->opt.joliet = OPT_JOLIET_DISABLE; else if (strcmp(value, "1") == 0) iso9660->opt.joliet = OPT_JOLIET_ENABLE; else if (strcmp(value, "long") == 0) iso9660->opt.joliet = OPT_JOLIET_LONGNAME; else goto invalid_value; return (ARCHIVE_OK); } break; case 'l': if (strcmp(key, "limit-depth") == 0) { iso9660->opt.limit_depth = value != NULL; return (ARCHIVE_OK); } if (strcmp(key, "limit-dirs") == 0) { iso9660->opt.limit_dirs = value != NULL; return (ARCHIVE_OK); } break; case 'p': if (strcmp(key, "pad") == 0) { iso9660->opt.pad = value != NULL; return (ARCHIVE_OK); } if (strcmp(key, "publisher") == 0) { r = get_str_opt(a, &(iso9660->publisher_identifier), PUBLISHER_IDENTIFIER_SIZE, key, value); iso9660->opt.publisher = r == ARCHIVE_OK; return (r); } break; case 'r': if (strcmp(key, "rockridge") == 0 || strcmp(key, "Rockridge") == 0) { if (value == NULL) iso9660->opt.rr = OPT_RR_DISABLED; else if (strcmp(value, "1") == 0) iso9660->opt.rr = OPT_RR_USEFUL; else if (strcmp(value, "strict") == 0) iso9660->opt.rr = OPT_RR_STRICT; else if (strcmp(value, "useful") == 0) iso9660->opt.rr = OPT_RR_USEFUL; else goto invalid_value; return (ARCHIVE_OK); } break; case 'v': if (strcmp(key, "volume-id") == 0) { r = get_str_opt(a, &(iso9660->volume_identifier), VOLUME_IDENTIFIER_SIZE, key, value); iso9660->opt.volume_id = r == ARCHIVE_OK; return (r); } break; case 'z': if (strcmp(key, "zisofs") == 0) { if (value == NULL) iso9660->opt.zisofs = OPT_ZISOFS_DISABLED; else { #ifdef HAVE_ZLIB_H iso9660->opt.zisofs = OPT_ZISOFS_DIRECT; #else archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "``zisofs'' " "is not supported on this platform."); return (ARCHIVE_FATAL); #endif } return (ARCHIVE_OK); } break; } /* Note: The "warn" return is just to inform the options * supervisor that we didn't handle it. It will generate * a suitable error if no one used this option. */ return (ARCHIVE_WARN); invalid_value: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Invalid value for option ``%s''", key); return (ARCHIVE_FAILED); } static int iso9660_write_header(struct archive_write *a, struct archive_entry *entry) { struct iso9660 *iso9660; struct isofile *file; struct isoent *isoent; int r, ret = ARCHIVE_OK; iso9660 = a->format_data; iso9660->cur_file = NULL; iso9660->bytes_remaining = 0; iso9660->need_multi_extent = 0; if (archive_entry_filetype(entry) == AE_IFLNK && iso9660->opt.rr == OPT_RR_DISABLED) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Ignore symlink file."); iso9660->cur_file = NULL; return (ARCHIVE_WARN); } if (archive_entry_filetype(entry) == AE_IFREG && archive_entry_size(entry) >= MULTI_EXTENT_SIZE) { if (iso9660->opt.iso_level < 3) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Ignore over %lld bytes file. " "This file too large.", MULTI_EXTENT_SIZE); iso9660->cur_file = NULL; return (ARCHIVE_WARN); } iso9660->need_multi_extent = 1; } file = isofile_new(a, entry); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate data"); return (ARCHIVE_FATAL); } r = isofile_gen_utility_names(a, file); if (r < ARCHIVE_WARN) { isofile_free(file); return (r); } else if (r < ret) ret = r; /* * Ignore a path which looks like the top of directory name * since we have already made the root directory of an ISO image. */ if (archive_strlen(&(file->parentdir)) == 0 && archive_strlen(&(file->basename)) == 0) { isofile_free(file); return (r); } isofile_add_entry(iso9660, file); isoent = isoent_new(file); if (isoent == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate data"); return (ARCHIVE_FATAL); } if (isoent->file->dircnt > iso9660->dircnt_max) iso9660->dircnt_max = isoent->file->dircnt; /* Add the current file into tree */ r = isoent_tree(a, &isoent); if (r != ARCHIVE_OK) return (r); /* If there is the same file in tree and * the current file is older than the file in tree. * So we don't need the current file data anymore. */ if (isoent->file != file) return (ARCHIVE_OK); /* Non regular files contents are unneeded to be saved to * temporary files. */ if (archive_entry_filetype(file->entry) != AE_IFREG) return (ret); /* * Set the current file to cur_file to read its contents. */ iso9660->cur_file = file; if (archive_entry_nlink(file->entry) > 1) { r = isofile_register_hardlink(a, file); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* * Prepare to save the contents of the file. */ if (iso9660->temp_fd < 0) { iso9660->temp_fd = __archive_mktemp(NULL); if (iso9660->temp_fd < 0) { archive_set_error(&a->archive, errno, "Couldn't create temporary file"); return (ARCHIVE_FATAL); } } /* Save an offset of current file in temporary file. */ file->content.offset_of_temp = wb_offset(a); file->cur_content = &(file->content); r = zisofs_init(a, file); if (r < ret) ret = r; iso9660->bytes_remaining = archive_entry_size(file->entry); return (ret); } static int write_to_temp(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; ssize_t written; const unsigned char *b; b = (const unsigned char *)buff; while (s) { written = write(iso9660->temp_fd, b, s); if (written < 0) { archive_set_error(&a->archive, errno, "Can't write to temporary file"); return (ARCHIVE_FATAL); } s -= written; b += written; } return (ARCHIVE_OK); } static int wb_write_to_temp(struct archive_write *a, const void *buff, size_t s) { const char *xp = buff; size_t xs = s; /* * If a written data size is big enough to use system-call * and there is no waiting data, this calls write_to_temp() in * order to reduce a extra memory copy. */ if (wb_remaining(a) == wb_buffmax() && s > (1024 * 16)) { struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; xs = s % LOGICAL_BLOCK_SIZE; iso9660->wbuff_offset += s - xs; if (write_to_temp(a, buff, s - xs) != ARCHIVE_OK) return (ARCHIVE_FATAL); if (xs == 0) return (ARCHIVE_OK); xp += s - xs; } while (xs) { size_t size = xs; if (size > wb_remaining(a)) size = wb_remaining(a); memcpy(wb_buffptr(a), xp, size); if (wb_consume(a, size) != ARCHIVE_OK) return (ARCHIVE_FATAL); xs -= size; xp += size; } return (ARCHIVE_OK); } static int wb_write_padding_to_temp(struct archive_write *a, int64_t csize) { size_t ns; int ret; ns = (size_t)(csize % LOGICAL_BLOCK_SIZE); if (ns != 0) ret = write_null(a, LOGICAL_BLOCK_SIZE - ns); else ret = ARCHIVE_OK; return (ret); } static ssize_t write_iso9660_data(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; size_t ws; if (iso9660->temp_fd < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Couldn't create temporary file"); return (ARCHIVE_FATAL); } ws = s; if (iso9660->need_multi_extent && (iso9660->cur_file->cur_content->size + ws) >= (MULTI_EXTENT_SIZE - LOGICAL_BLOCK_SIZE)) { struct content *con; size_t ts; ts = (size_t)(MULTI_EXTENT_SIZE - LOGICAL_BLOCK_SIZE - iso9660->cur_file->cur_content->size); if (iso9660->zisofs.detect_magic) zisofs_detect_magic(a, buff, ts); if (iso9660->zisofs.making) { if (zisofs_write_to_temp(a, buff, ts) != ARCHIVE_OK) return (ARCHIVE_FATAL); } else { if (wb_write_to_temp(a, buff, ts) != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->cur_file->cur_content->size += ts; } /* Write padding. */ if (wb_write_padding_to_temp(a, iso9660->cur_file->cur_content->size) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Compute the logical block number. */ iso9660->cur_file->cur_content->blocks = (int) ((iso9660->cur_file->cur_content->size + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); /* * Make next extent. */ ws -= ts; buff = (const void *)(((const unsigned char *)buff) + ts); /* Make a content for next extent. */ con = calloc(1, sizeof(*con)); if (con == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate content data"); return (ARCHIVE_FATAL); } con->offset_of_temp = wb_offset(a); iso9660->cur_file->cur_content->next = con; iso9660->cur_file->cur_content = con; #ifdef HAVE_ZLIB_H iso9660->zisofs.block_offset = 0; #endif } if (iso9660->zisofs.detect_magic) zisofs_detect_magic(a, buff, ws); if (iso9660->zisofs.making) { if (zisofs_write_to_temp(a, buff, ws) != ARCHIVE_OK) return (ARCHIVE_FATAL); } else { if (wb_write_to_temp(a, buff, ws) != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->cur_file->cur_content->size += ws; } return (s); } static ssize_t iso9660_write_data(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; ssize_t r; if (iso9660->cur_file == NULL) return (0); if (archive_entry_filetype(iso9660->cur_file->entry) != AE_IFREG) return (0); if (s > iso9660->bytes_remaining) s = (size_t)iso9660->bytes_remaining; if (s == 0) return (0); r = write_iso9660_data(a, buff, s); if (r > 0) iso9660->bytes_remaining -= r; return (r); } static int iso9660_finish_entry(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; if (iso9660->cur_file == NULL) return (ARCHIVE_OK); if (archive_entry_filetype(iso9660->cur_file->entry) != AE_IFREG) return (ARCHIVE_OK); if (iso9660->cur_file->content.size == 0) return (ARCHIVE_OK); /* If there are unwritten data, write null data instead. */ while (iso9660->bytes_remaining > 0) { size_t s; s = (iso9660->bytes_remaining > a->null_length)? a->null_length: (size_t)iso9660->bytes_remaining; if (write_iso9660_data(a, a->nulls, s) < 0) return (ARCHIVE_FATAL); iso9660->bytes_remaining -= s; } if (iso9660->zisofs.making && zisofs_finish_entry(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write padding. */ if (wb_write_padding_to_temp(a, iso9660->cur_file->cur_content->size) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Compute the logical block number. */ iso9660->cur_file->cur_content->blocks = (int) ((iso9660->cur_file->cur_content->size + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); /* Add the current file to data file list. */ isofile_add_data_file(iso9660, iso9660->cur_file); return (ARCHIVE_OK); } static int iso9660_close(struct archive_write *a) { struct iso9660 *iso9660; int ret, blocks; iso9660 = a->format_data; /* * Write remaining data out to the temporary file. */ if (wb_remaining(a) > 0) { ret = wb_write_out(a); if (ret < 0) return (ret); } /* * Preparations... */ #ifdef DEBUG if (iso9660->birth_time == 0) #endif time(&(iso9660->birth_time)); /* * Prepare a bootable ISO image. */ if (iso9660->opt.boot) { /* Find out the boot file entry. */ ret = isoent_find_out_boot_file(a, iso9660->primary.rootent); if (ret < 0) return (ret); /* Reconvert the boot file from zisofs'ed form to * plain form. */ ret = zisofs_rewind_boot_file(a); if (ret < 0) return (ret); /* Write remaining data out to the temporary file. */ if (wb_remaining(a) > 0) { ret = wb_write_out(a); if (ret < 0) return (ret); } /* Create the boot catalog. */ ret = isoent_create_boot_catalog(a, iso9660->primary.rootent); if (ret < 0) return (ret); } /* * Prepare joliet extensions. */ if (iso9660->opt.joliet) { /* Make a new tree for joliet. */ ret = isoent_clone_tree(a, &(iso9660->joliet.rootent), iso9660->primary.rootent); if (ret < 0) return (ret); /* Make sure we have UTF-16BE convertors. * if there is no file entry, convertors are still * uninitilized. */ if (iso9660->sconv_to_utf16be == NULL) { iso9660->sconv_to_utf16be = archive_string_conversion_to_charset( &(a->archive), "UTF-16BE", 1); if (iso9660->sconv_to_utf16be == NULL) /* Couldn't allocate memory */ return (ARCHIVE_FATAL); iso9660->sconv_from_utf16be = archive_string_conversion_from_charset( &(a->archive), "UTF-16BE", 1); if (iso9660->sconv_from_utf16be == NULL) /* Couldn't allocate memory */ return (ARCHIVE_FATAL); } } /* * Make Path Tables. */ ret = isoent_make_path_table(a); if (ret < 0) return (ret); /* * Calculate a total volume size and setup all locations of * contents of an iso9660 image. */ blocks = SYSTEM_AREA_BLOCK + PRIMARY_VOLUME_DESCRIPTOR_BLOCK + VOLUME_DESCRIPTOR_SET_TERMINATOR_BLOCK + NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK; if (iso9660->opt.boot) blocks += BOOT_RECORD_DESCRIPTOR_BLOCK; if (iso9660->opt.joliet) blocks += SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK; if (iso9660->opt.iso_level == 4) blocks += SUPPLEMENTARY_VOLUME_DESCRIPTOR_BLOCK; /* Setup the locations of Path Table. */ iso9660->primary.location_type_L_path_table = blocks; blocks += iso9660->primary.path_table_block; iso9660->primary.location_type_M_path_table = blocks; blocks += iso9660->primary.path_table_block; if (iso9660->opt.joliet) { iso9660->joliet.location_type_L_path_table = blocks; blocks += iso9660->joliet.path_table_block; iso9660->joliet.location_type_M_path_table = blocks; blocks += iso9660->joliet.path_table_block; } /* Setup the locations of directories. */ isoent_setup_directory_location(iso9660, blocks, &(iso9660->primary)); blocks += iso9660->primary.total_dir_block; if (iso9660->opt.joliet) { isoent_setup_directory_location(iso9660, blocks, &(iso9660->joliet)); blocks += iso9660->joliet.total_dir_block; } if (iso9660->opt.rr) { iso9660->location_rrip_er = blocks; blocks += RRIP_ER_BLOCK; } /* Setup the locations of all file contents. */ isoent_setup_file_location(iso9660, blocks); blocks += iso9660->total_file_block; if (iso9660->opt.boot && iso9660->opt.boot_info_table) { ret = setup_boot_information(a); if (ret < 0) return (ret); } /* Now we have a total volume size. */ iso9660->volume_space_size = blocks; if (iso9660->opt.pad) iso9660->volume_space_size += PADDING_BLOCK; iso9660->volume_sequence_number = 1; /* * Write an ISO 9660 image. */ /* Switc to start using wbuff as file buffer. */ iso9660->wbuff_remaining = wb_buffmax(); iso9660->wbuff_type = WB_TO_STREAM; iso9660->wbuff_offset = 0; iso9660->wbuff_written = 0; iso9660->wbuff_tail = 0; /* Write The System Area */ ret = write_null(a, SYSTEM_AREA_BLOCK * LOGICAL_BLOCK_SIZE); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Primary Volume Descriptor */ ret = write_VD(a, &(iso9660->primary)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->opt.boot) { /* Write Boot Record Volume Descriptor */ ret = write_VD_boot_record(a); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } if (iso9660->opt.iso_level == 4) { /* Write Enhanced Volume Descriptor */ iso9660->primary.vdd_type = VDD_ENHANCED; ret = write_VD(a, &(iso9660->primary)); iso9660->primary.vdd_type = VDD_PRIMARY; if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } if (iso9660->opt.joliet) { ret = write_VD(a, &(iso9660->joliet)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* Write Volume Descriptor Set Terminator */ ret = write_VD_terminator(a); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Non-ISO File System Information */ ret = write_information_block(a); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Type L Path Table */ ret = write_path_table(a, 0, &(iso9660->primary)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Type M Path Table */ ret = write_path_table(a, 1, &(iso9660->primary)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->opt.joliet) { /* Write Type L Path Table */ ret = write_path_table(a, 0, &(iso9660->joliet)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Type M Path Table */ ret = write_path_table(a, 1, &(iso9660->joliet)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* Write Directory Descriptors */ ret = write_directory_descriptors(a, &(iso9660->primary)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); if (iso9660->opt.joliet) { ret = write_directory_descriptors(a, &(iso9660->joliet)); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } if (iso9660->opt.rr) { /* Write Rockridge ER(Extensions Reference) */ ret = write_rr_ER(a); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } /* Write File Descriptors */ ret = write_file_descriptors(a); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Write Padding */ if (iso9660->opt.pad) { ret = write_null(a, PADDING_BLOCK * LOGICAL_BLOCK_SIZE); if (ret != ARCHIVE_OK) return (ARCHIVE_FATAL); } if (iso9660->directories_too_deep != NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "%s: Directories too deep.", archive_entry_pathname( iso9660->directories_too_deep->file->entry)); return (ARCHIVE_WARN); } /* Write remaining data out. */ ret = wb_write_out(a); return (ret); } static int iso9660_free(struct archive_write *a) { struct iso9660 *iso9660; int i, ret; iso9660 = a->format_data; /* Close the temporary file. */ if (iso9660->temp_fd >= 0) close(iso9660->temp_fd); /* Free some stuff for zisofs operations. */ ret = zisofs_free(a); /* Remove directory entries in tree which includes file entries. */ isoent_free_all(iso9660->primary.rootent); for (i = 0; i < iso9660->primary.max_depth; i++) free(iso9660->primary.pathtbl[i].sorted); free(iso9660->primary.pathtbl); if (iso9660->opt.joliet) { isoent_free_all(iso9660->joliet.rootent); for (i = 0; i < iso9660->joliet.max_depth; i++) free(iso9660->joliet.pathtbl[i].sorted); free(iso9660->joliet.pathtbl); } /* Remove isofile entries. */ isofile_free_all_entries(iso9660); isofile_free_hardlinks(iso9660); archive_string_free(&(iso9660->cur_dirstr)); archive_string_free(&(iso9660->volume_identifier)); archive_string_free(&(iso9660->publisher_identifier)); archive_string_free(&(iso9660->data_preparer_identifier)); archive_string_free(&(iso9660->application_identifier)); archive_string_free(&(iso9660->copyright_file_identifier)); archive_string_free(&(iso9660->abstract_file_identifier)); archive_string_free(&(iso9660->bibliographic_file_identifier)); archive_string_free(&(iso9660->el_torito.catalog_filename)); archive_string_free(&(iso9660->el_torito.boot_filename)); archive_string_free(&(iso9660->el_torito.id)); archive_string_free(&(iso9660->utf16be)); archive_string_free(&(iso9660->mbs)); free(iso9660); a->format_data = NULL; return (ret); } /* * Get the System Identifier */ static void get_system_identitier(char *system_id, size_t size) { #if defined(HAVE_SYS_UTSNAME_H) struct utsname u; uname(&u); strncpy(system_id, u.sysname, size-1); system_id[size-1] = '\0'; #elif defined(_WIN32) && !defined(__CYGWIN__) strncpy(system_id, "Windows", size-1); system_id[size-1] = '\0'; #else #error no way to get the system identifier on your platform. #endif } static void set_str(unsigned char *p, const char *s, size_t l, char f, const char *map) { unsigned char c; if (s == NULL) s = ""; while ((c = *s++) != 0 && l > 0) { if (c >= 0x80 || map[c] == 0) { /* illegal character */ if (c >= 'a' && c <= 'z') { /* convert c from a-z to A-Z */ c -= 0x20; } else c = 0x5f; } *p++ = c; l--; } /* If l isn't zero, fill p buffer by the character * which indicated by f. */ if (l > 0) memset(p , f, l); } static inline int joliet_allowed_char(unsigned char high, unsigned char low) { int utf16 = (high << 8) | low; if (utf16 <= 0x001F) return (0); switch (utf16) { case 0x002A: /* '*' */ case 0x002F: /* '/' */ case 0x003A: /* ':' */ case 0x003B: /* ';' */ case 0x003F: /* '?' */ case 0x005C: /* '\' */ return (0);/* Not allowed. */ } return (1); } static int set_str_utf16be(struct archive_write *a, unsigned char *p, const char *s, size_t l, uint16_t uf, enum vdc vdc) { size_t size, i; int onepad; if (s == NULL) s = ""; if (l & 0x01) { onepad = 1; l &= ~1; } else onepad = 0; if (vdc == VDC_UCS2) { struct iso9660 *iso9660 = a->format_data; if (archive_strncpy_l(&iso9660->utf16be, s, strlen(s), iso9660->sconv_to_utf16be) != 0 && errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for UTF-16BE"); return (ARCHIVE_FATAL); } size = iso9660->utf16be.length; if (size > l) size = l; memcpy(p, iso9660->utf16be.s, size); } else { const uint16_t *u16 = (const uint16_t *)s; size = 0; while (*u16++) size += 2; if (size > l) size = l; memcpy(p, s, size); } for (i = 0; i < size; i += 2, p += 2) { if (!joliet_allowed_char(p[0], p[1])) archive_be16enc(p, 0x005F);/* '_' */ } l -= size; while (l > 0) { archive_be16enc(p, uf); p += 2; l -= 2; } if (onepad) *p = 0; return (ARCHIVE_OK); } static const char a_characters_map[0x80] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20-2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30-3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 60-6F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 70-7F */ }; static const char a1_characters_map[0x80] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 20-2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 30-3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60-6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,/* 70-7F */ }; static const char d_characters_map[0x80] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 20-2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,/* 30-3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 60-6F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 70-7F */ }; static const char d1_characters_map[0x80] = { /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 00-0F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 10-1F */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,/* 20-2F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,/* 30-3F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 40-4F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,/* 50-5F */ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,/* 60-6F */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,/* 70-7F */ }; static int set_str_a_characters_bp(struct archive_write *a, unsigned char *bp, int from, int to, const char *s, enum vdc vdc) { int r; switch (vdc) { case VDC_STD: set_str(bp+from, s, to - from + 1, 0x20, a_characters_map); r = ARCHIVE_OK; break; case VDC_LOWERCASE: set_str(bp+from, s, to - from + 1, 0x20, a1_characters_map); r = ARCHIVE_OK; break; case VDC_UCS2: case VDC_UCS2_DIRECT: r = set_str_utf16be(a, bp+from, s, to - from + 1, 0x0020, vdc); break; default: r = ARCHIVE_FATAL; } return (r); } static int set_str_d_characters_bp(struct archive_write *a, unsigned char *bp, int from, int to, const char *s, enum vdc vdc) { int r; switch (vdc) { case VDC_STD: set_str(bp+from, s, to - from + 1, 0x20, d_characters_map); r = ARCHIVE_OK; break; case VDC_LOWERCASE: set_str(bp+from, s, to - from + 1, 0x20, d1_characters_map); r = ARCHIVE_OK; break; case VDC_UCS2: case VDC_UCS2_DIRECT: r = set_str_utf16be(a, bp+from, s, to - from + 1, 0x0020, vdc); break; default: r = ARCHIVE_FATAL; } return (r); } static void set_VD_bp(unsigned char *bp, enum VD_type type, unsigned char ver) { /* Volume Descriptor Type */ bp[1] = (unsigned char)type; /* Standard Identifier */ memcpy(bp + 2, "CD001", 5); /* Volume Descriptor Version */ bp[7] = ver; } static inline void set_unused_field_bp(unsigned char *bp, int from, int to) { memset(bp + from, 0, to - from + 1); } /* * 8-bit unsigned numerical values. * ISO9660 Standard 7.1.1 */ static inline void set_num_711(unsigned char *p, unsigned char value) { *p = value; } /* * 8-bit signed numerical values. * ISO9660 Standard 7.1.2 */ static inline void set_num_712(unsigned char *p, char value) { *((char *)p) = value; } /* * Least significant byte first. * ISO9660 Standard 7.2.1 */ static inline void set_num_721(unsigned char *p, uint16_t value) { archive_le16enc(p, value); } /* * Most significant byte first. * ISO9660 Standard 7.2.2 */ static inline void set_num_722(unsigned char *p, uint16_t value) { archive_be16enc(p, value); } /* * Both-byte orders. * ISO9660 Standard 7.2.3 */ static void set_num_723(unsigned char *p, uint16_t value) { archive_le16enc(p, value); archive_be16enc(p+2, value); } /* * Least significant byte first. * ISO9660 Standard 7.3.1 */ static inline void set_num_731(unsigned char *p, uint32_t value) { archive_le32enc(p, value); } /* * Most significant byte first. * ISO9660 Standard 7.3.2 */ static inline void set_num_732(unsigned char *p, uint32_t value) { archive_be32enc(p, value); } /* * Both-byte orders. * ISO9660 Standard 7.3.3 */ static inline void set_num_733(unsigned char *p, uint32_t value) { archive_le32enc(p, value); archive_be32enc(p+4, value); } static void set_digit(unsigned char *p, size_t s, int value) { while (s--) { p[s] = '0' + (value % 10); value /= 10; } } #if defined(HAVE_STRUCT_TM_TM_GMTOFF) #define get_gmoffset(tm) ((tm)->tm_gmtoff) #elif defined(HAVE_STRUCT_TM___TM_GMTOFF) #define get_gmoffset(tm) ((tm)->__tm_gmtoff) #else static long get_gmoffset(struct tm *tm) { long offset; #if defined(HAVE__GET_TIMEZONE) _get_timezone(&offset); #elif defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__) offset = _timezone; #else offset = timezone; #endif offset *= -1; if (tm->tm_isdst) offset += 3600; return (offset); } #endif static void get_tmfromtime(struct tm *tm, time_t *t) { #if HAVE_LOCALTIME_R tzset(); localtime_r(t, tm); #elif HAVE__LOCALTIME64_S _localtime64_s(tm, t); #else memcpy(tm, localtime(t), sizeof(*tm)); #endif } /* * Date and Time Format. * ISO9660 Standard 8.4.26.1 */ static void set_date_time(unsigned char *p, time_t t) { struct tm tm; get_tmfromtime(&tm, &t); set_digit(p, 4, tm.tm_year + 1900); set_digit(p+4, 2, tm.tm_mon + 1); set_digit(p+6, 2, tm.tm_mday); set_digit(p+8, 2, tm.tm_hour); set_digit(p+10, 2, tm.tm_min); set_digit(p+12, 2, tm.tm_sec); set_digit(p+14, 2, 0); set_num_712(p+16, (char)(get_gmoffset(&tm)/(60*15))); } static void set_date_time_null(unsigned char *p) { memset(p, '0', 16); p[16] = 0; } static void set_time_915(unsigned char *p, time_t t) { struct tm tm; get_tmfromtime(&tm, &t); set_num_711(p+0, tm.tm_year); set_num_711(p+1, tm.tm_mon+1); set_num_711(p+2, tm.tm_mday); set_num_711(p+3, tm.tm_hour); set_num_711(p+4, tm.tm_min); set_num_711(p+5, tm.tm_sec); set_num_712(p+6, (char)(get_gmoffset(&tm)/(60*15))); } /* * Write SUSP "CE" System Use Entry. */ static int set_SUSP_CE(unsigned char *p, int location, int offset, int size) { unsigned char *bp = p -1; /* Extend the System Use Area * "CE" Format: * len ver * +----+----+----+----+-----------+-----------+ * | 'C'| 'E'| 1C | 01 | LOCATION1 | LOCATION2 | * +----+----+----+----+-----------+-----------+ * 0 1 2 3 4 12 20 * +-----------+ * | LOCATION3 | * +-----------+ * 20 28 * LOCATION1 : Location of Continuation of System Use Area. * LOCATION2 : Offset to Start of Continuation. * LOCATION3 : Length of the Continuation. */ bp[1] = 'C'; bp[2] = 'E'; bp[3] = RR_CE_SIZE; /* length */ bp[4] = 1; /* version */ set_num_733(bp+5, location); set_num_733(bp+13, offset); set_num_733(bp+21, size); return (RR_CE_SIZE); } /* * The functions, which names are beginning with extra_, are used to * control extra records. * The maximum size of a Directory Record is 254. When a filename is * very long, all of RRIP data of a file won't stored to the Directory * Record and so remaining RRIP data store to an extra record instead. */ static unsigned char * extra_open_record(unsigned char *bp, int dr_len, struct isoent *isoent, struct ctl_extr_rec *ctl) { ctl->bp = bp; if (bp != NULL) bp += dr_len; ctl->use_extr = 0; ctl->isoent = isoent; ctl->ce_ptr = NULL; ctl->cur_len = ctl->dr_len = dr_len; ctl->limit = DR_LIMIT; return (bp); } static void extra_close_record(struct ctl_extr_rec *ctl, int ce_size) { int padding = 0; if (ce_size > 0) extra_tell_used_size(ctl, ce_size); /* Padding. */ if (ctl->cur_len & 0x01) { ctl->cur_len++; if (ctl->bp != NULL) ctl->bp[ctl->cur_len] = 0; padding = 1; } if (ctl->use_extr) { if (ctl->ce_ptr != NULL) set_SUSP_CE(ctl->ce_ptr, ctl->extr_loc, ctl->extr_off, ctl->cur_len - padding); } else ctl->dr_len = ctl->cur_len; } #define extra_space(ctl) ((ctl)->limit - (ctl)->cur_len) static unsigned char * extra_next_record(struct ctl_extr_rec *ctl, int length) { int cur_len = ctl->cur_len;/* save cur_len */ /* Close the current extra record or Directory Record. */ extra_close_record(ctl, RR_CE_SIZE); /* Get a next extra record. */ ctl->use_extr = 1; if (ctl->bp != NULL) { /* Storing data into an extra record. */ unsigned char *p; /* Save the pointer where a CE extension will be * stored to. */ ctl->ce_ptr = &ctl->bp[cur_len+1]; p = extra_get_record(ctl->isoent, &ctl->limit, &ctl->extr_off, &ctl->extr_loc); ctl->bp = p - 1;/* the base of bp offset is 1. */ } else /* Calculating the size of an extra record. */ (void)extra_get_record(ctl->isoent, &ctl->limit, NULL, NULL); ctl->cur_len = 0; /* Check if an extra record is almost full. * If so, get a next one. */ if (extra_space(ctl) < length) (void)extra_next_record(ctl, length); return (ctl->bp); } static inline struct extr_rec * extra_last_record(struct isoent *isoent) { if (isoent->extr_rec_list.first == NULL) return (NULL); return ((struct extr_rec *)(void *) ((char *)(isoent->extr_rec_list.last) - offsetof(struct extr_rec, next))); } static unsigned char * extra_get_record(struct isoent *isoent, int *space, int *off, int *loc) { struct extr_rec *rec; isoent = isoent->parent; if (off != NULL) { /* Storing data into an extra record. */ rec = isoent->extr_rec_list.current; if (DR_SAFETY > LOGICAL_BLOCK_SIZE - rec->offset) rec = rec->next; } else { /* Calculating the size of an extra record. */ rec = extra_last_record(isoent); if (rec == NULL || DR_SAFETY > LOGICAL_BLOCK_SIZE - rec->offset) { rec = malloc(sizeof(*rec)); if (rec == NULL) return (NULL); rec->location = 0; rec->offset = 0; /* Insert `rec` into the tail of isoent->extr_rec_list */ rec->next = NULL; /* * Note: testing isoent->extr_rec_list.last == NULL * here is really unneeded since it has been already * initialized at isoent_new function but Clang Static * Analyzer claims that it is dereference of null * pointer. */ if (isoent->extr_rec_list.last == NULL) isoent->extr_rec_list.last = &(isoent->extr_rec_list.first); *isoent->extr_rec_list.last = rec; isoent->extr_rec_list.last = &(rec->next); } } *space = LOGICAL_BLOCK_SIZE - rec->offset - DR_SAFETY; if (*space & 0x01) *space -= 1;/* Keep padding space. */ if (off != NULL) *off = rec->offset; if (loc != NULL) *loc = rec->location; isoent->extr_rec_list.current = rec; return (&rec->buf[rec->offset]); } static void extra_tell_used_size(struct ctl_extr_rec *ctl, int size) { struct isoent *isoent; struct extr_rec *rec; if (ctl->use_extr) { isoent = ctl->isoent->parent; rec = isoent->extr_rec_list.current; if (rec != NULL) rec->offset += size; } ctl->cur_len += size; } static int extra_setup_location(struct isoent *isoent, int location) { struct extr_rec *rec; int cnt; cnt = 0; rec = isoent->extr_rec_list.first; isoent->extr_rec_list.current = rec; while (rec) { cnt++; rec->location = location++; rec->offset = 0; rec = rec->next; } return (cnt); } /* * Create the RRIP entries. */ static int set_directory_record_rr(unsigned char *bp, int dr_len, struct isoent *isoent, struct iso9660 *iso9660, enum dir_rec_type t) { /* Flags(BP 5) of the Rockridge "RR" System Use Field */ unsigned char rr_flag; #define RR_USE_PX 0x01 #define RR_USE_PN 0x02 #define RR_USE_SL 0x04 #define RR_USE_NM 0x08 #define RR_USE_CL 0x10 #define RR_USE_PL 0x20 #define RR_USE_RE 0x40 #define RR_USE_TF 0x80 int length; struct ctl_extr_rec ctl; struct isoent *rr_parent, *pxent; struct isofile *file; bp = extra_open_record(bp, dr_len, isoent, &ctl); if (t == DIR_REC_PARENT) { rr_parent = isoent->rr_parent; pxent = isoent->parent; if (rr_parent != NULL) isoent = rr_parent; else isoent = isoent->parent; } else { rr_parent = NULL; pxent = isoent; } file = isoent->file; if (t != DIR_REC_NORMAL) { rr_flag = RR_USE_PX | RR_USE_TF; if (rr_parent != NULL) rr_flag |= RR_USE_PL; } else { rr_flag = RR_USE_PX | RR_USE_NM | RR_USE_TF; if (archive_entry_filetype(file->entry) == AE_IFLNK) rr_flag |= RR_USE_SL; if (isoent->rr_parent != NULL) rr_flag |= RR_USE_RE; if (isoent->rr_child != NULL) rr_flag |= RR_USE_CL; if (archive_entry_filetype(file->entry) == AE_IFCHR || archive_entry_filetype(file->entry) == AE_IFBLK) rr_flag |= RR_USE_PN; #ifdef COMPAT_MKISOFS /* * mkisofs 2.01.01a63 records "RE" extension to * the entry of "rr_moved" directory. * I don't understand this behavior. */ if (isoent->virtual && isoent->parent == iso9660->primary.rootent && strcmp(isoent->file->basename.s, "rr_moved") == 0) rr_flag |= RR_USE_RE; #endif } /* Write "SP" System Use Entry. */ if (t == DIR_REC_SELF && isoent == isoent->parent) { length = 7; if (bp != NULL) { bp[1] = 'S'; bp[2] = 'P'; bp[3] = length; bp[4] = 1; /* version */ bp[5] = 0xBE; /* Check Byte */ bp[6] = 0xEF; /* Check Byte */ bp[7] = 0; bp += length; } extra_tell_used_size(&ctl, length); } /* Write "RR" System Use Entry. */ length = 5; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'R'; bp[2] = 'R'; bp[3] = length; bp[4] = 1; /* version */ bp[5] = rr_flag; bp += length; } extra_tell_used_size(&ctl, length); /* Write "NM" System Use Entry. */ if (rr_flag & RR_USE_NM) { /* * "NM" Format: * e.g. a basename is 'foo' * len ver flg * +----+----+----+----+----+----+----+----+ * | 'N'| 'M'| 08 | 01 | 00 | 'f'| 'o'| 'o'| * +----+----+----+----+----+----+----+----+ * <----------------- len -----------------> */ size_t nmlen = file->basename.length; const char *nm = file->basename.s; size_t nmmax; if (extra_space(&ctl) < 6) bp = extra_next_record(&ctl, 6); if (bp != NULL) { bp[1] = 'N'; bp[2] = 'M'; bp[4] = 1; /* version */ } nmmax = extra_space(&ctl); if (nmmax > 0xff) nmmax = 0xff; while (nmlen + 5 > nmmax) { length = (int)nmmax; if (bp != NULL) { bp[3] = length; bp[5] = 0x01;/* Alternate Name continues * in next "NM" field */ memcpy(bp+6, nm, length - 5); bp += length; } nmlen -= length - 5; nm += length - 5; extra_tell_used_size(&ctl, length); if (extra_space(&ctl) < 6) { bp = extra_next_record(&ctl, 6); nmmax = extra_space(&ctl); if (nmmax > 0xff) nmmax = 0xff; } if (bp != NULL) { bp[1] = 'N'; bp[2] = 'M'; bp[4] = 1; /* version */ } } length = 5 + (int)nmlen; if (bp != NULL) { bp[3] = length; bp[5] = 0; memcpy(bp+6, nm, nmlen); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "PX" System Use Entry. */ if (rr_flag & RR_USE_PX) { /* * "PX" Format: * len ver * +----+----+----+----+-----------+-----------+ * | 'P'| 'X'| 2C | 01 | FILE MODE | LINKS | * +----+----+----+----+-----------+-----------+ * 0 1 2 3 4 12 20 * +-----------+-----------+------------------+ * | USER ID | GROUP ID |FILE SERIAL NUMBER| * +-----------+-----------+------------------+ * 20 28 36 44 */ length = 44; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { mode_t mode; int64_t uid; int64_t gid; mode = archive_entry_mode(file->entry); uid = archive_entry_uid(file->entry); gid = archive_entry_gid(file->entry); if (iso9660->opt.rr == OPT_RR_USEFUL) { /* * This action is simular mkisofs -r option * but our rockridge=useful option does not * set a zero to uid and gid. */ /* set all read bit ON */ mode |= 0444; #if !defined(_WIN32) && !defined(__CYGWIN__) if (mode & 0111) #endif /* set all exec bit ON */ mode |= 0111; /* clear all write bits. */ mode &= ~0222; /* clear setuid,setgid,sticky bits. */ mode &= ~07000; } bp[1] = 'P'; bp[2] = 'X'; bp[3] = length; bp[4] = 1; /* version */ /* file mode */ set_num_733(bp+5, mode); /* file links (stat.st_nlink) */ set_num_733(bp+13, archive_entry_nlink(file->entry)); set_num_733(bp+21, (uint32_t)uid); set_num_733(bp+29, (uint32_t)gid); /* File Serial Number */ if (pxent->dir) set_num_733(bp+37, pxent->dir_location); else if (file->hardlink_target != NULL) set_num_733(bp+37, file->hardlink_target->cur_content->location); else set_num_733(bp+37, file->cur_content->location); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "SL" System Use Entry. */ if (rr_flag & RR_USE_SL) { /* * "SL" Format: * e.g. a symbolic name is 'foo/bar' * len ver flg * +----+----+----+----+----+------------+ * | 'S'| 'L'| 0F | 01 | 00 | components | * +----+----+----+----+----+-----+------+ * 0 1 2 3 4 5 ...|... 15 * <----------------- len --------+------> * components : | * cflg clen | * +----+----+----+----+----+ | * | 00 | 03 | 'f'| 'o'| 'o'| <---+ * +----+----+----+----+----+ | * 5 6 7 8 9 10 | * cflg clen | * +----+----+----+----+----+ | * | 00 | 03 | 'b'| 'a'| 'r'| <---+ * +----+----+----+----+----+ * 10 11 12 13 14 15 * * - cflg : flag of componet * - clen : length of componet */ const char *sl; char sl_last; if (extra_space(&ctl) < 7) bp = extra_next_record(&ctl, 7); sl = file->symlink.s; sl_last = '\0'; if (bp != NULL) { bp[1] = 'S'; bp[2] = 'L'; bp[4] = 1; /* version */ } for (;;) { unsigned char *nc, *cf, *cl, cldmy = 0; int sllen, slmax; slmax = extra_space(&ctl); if (slmax > 0xff) slmax = 0xff; if (bp != NULL) nc = &bp[6]; else nc = NULL; cf = cl = NULL; sllen = 0; while (*sl && sllen + 11 < slmax) { if (sl_last == '\0' && sl[0] == '/') { /* * flg len * +----+----+ * | 08 | 00 | ROOT component. * +----+----+ ("/") * * Root component has to appear * at the first component only. */ if (nc != NULL) { cf = nc++; *cf = 0x08; /* ROOT */ *nc++ = 0; } sllen += 2; sl++; sl_last = '/'; cl = NULL; continue; } if (((sl_last == '\0' || sl_last == '/') && sl[0] == '.' && sl[1] == '.' && (sl[2] == '/' || sl[2] == '\0')) || (sl[0] == '/' && sl[1] == '.' && sl[2] == '.' && (sl[3] == '/' || sl[3] == '\0'))) { /* * flg len * +----+----+ * | 04 | 00 | PARENT component. * +----+----+ ("..") */ if (nc != NULL) { cf = nc++; *cf = 0x04; /* PARENT */ *nc++ = 0; } sllen += 2; if (sl[0] == '/') sl += 3;/* skip "/.." */ else sl += 2;/* skip ".." */ sl_last = '.'; cl = NULL; continue; } if (((sl_last == '\0' || sl_last == '/') && sl[0] == '.' && (sl[1] == '/' || sl[1] == '\0')) || (sl[0] == '/' && sl[1] == '.' && (sl[2] == '/' || sl[2] == '\0'))) { /* * flg len * +----+----+ * | 02 | 00 | CURREENT component. * +----+----+ (".") */ if (nc != NULL) { cf = nc++; *cf = 0x02; /* CURRENT */ *nc++ = 0; } sllen += 2; if (sl[0] == '/') sl += 2;/* skip "/." */ else sl ++; /* skip "." */ sl_last = '.'; cl = NULL; continue; } if (sl[0] == '/' || cl == NULL) { if (nc != NULL) { cf = nc++; *cf = 0; cl = nc++; *cl = 0; } else cl = &cldmy; sllen += 2; if (sl[0] == '/') { sl_last = *sl++; continue; } } sl_last = *sl++; if (nc != NULL) { *nc++ = sl_last; (*cl) ++; } sllen++; } if (*sl) { length = 5 + sllen; if (bp != NULL) { /* * Mark flg as CONTINUE component. */ *cf |= 0x01; /* * len ver flg * +----+----+----+----+----+- * | 'S'| 'L'| XX | 01 | 01 | * +----+----+----+----+----+- * ^ * continues in next "SL" */ bp[3] = length; bp[5] = 0x01;/* This Symbolic Link * continues in next * "SL" field */ bp += length; } extra_tell_used_size(&ctl, length); if (extra_space(&ctl) < 11) bp = extra_next_record(&ctl, 11); if (bp != NULL) { /* Next 'SL' */ bp[1] = 'S'; bp[2] = 'L'; bp[4] = 1; /* version */ } } else { length = 5 + sllen; if (bp != NULL) { bp[3] = length; bp[5] = 0; bp += length; } extra_tell_used_size(&ctl, length); break; } } } /* Write "TF" System Use Entry. */ if (rr_flag & RR_USE_TF) { /* * "TF" Format: * len ver * +----+----+----+----+-----+-------------+ * | 'T'| 'F'| XX | 01 |FLAGS| TIME STAMPS | * +----+----+----+----+-----+-------------+ * 0 1 2 3 4 5 XX * TIME STAMPS : ISO 9660 Standard 9.1.5. * If TF_LONG_FORM FLAGS is set, * use ISO9660 Standard 8.4.26.1. */ #define TF_CREATION 0x01 /* Creation time recorded */ #define TF_MODIFY 0x02 /* Modification time recorded */ #define TF_ACCESS 0x04 /* Last Access time recorded */ #define TF_ATTRIBUTES 0x08 /* Last Attribute Change time recorded */ #define TF_BACKUP 0x10 /* Last Backup time recorded */ #define TF_EXPIRATION 0x20 /* Expiration time recorded */ #define TF_EFFECTIVE 0x40 /* Effective time recorded */ #define TF_LONG_FORM 0x80 /* ISO 9660 17-byte time format used */ unsigned char tf_flags; length = 5; tf_flags = 0; #ifndef COMPAT_MKISOFS if (archive_entry_birthtime_is_set(file->entry) && archive_entry_birthtime(file->entry) <= archive_entry_mtime(file->entry)) { length += 7; tf_flags |= TF_CREATION; } #endif if (archive_entry_mtime_is_set(file->entry)) { length += 7; tf_flags |= TF_MODIFY; } if (archive_entry_atime_is_set(file->entry)) { length += 7; tf_flags |= TF_ACCESS; } if (archive_entry_ctime_is_set(file->entry)) { length += 7; tf_flags |= TF_ATTRIBUTES; } if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'T'; bp[2] = 'F'; bp[3] = length; bp[4] = 1; /* version */ bp[5] = tf_flags; bp += 5; /* Creation time */ if (tf_flags & TF_CREATION) { set_time_915(bp+1, archive_entry_birthtime(file->entry)); bp += 7; } /* Modification time */ if (tf_flags & TF_MODIFY) { set_time_915(bp+1, archive_entry_mtime(file->entry)); bp += 7; } /* Last Access time */ if (tf_flags & TF_ACCESS) { set_time_915(bp+1, archive_entry_atime(file->entry)); bp += 7; } /* Last Attribute Change time */ if (tf_flags & TF_ATTRIBUTES) { set_time_915(bp+1, archive_entry_ctime(file->entry)); bp += 7; } } extra_tell_used_size(&ctl, length); } /* Write "RE" System Use Entry. */ if (rr_flag & RR_USE_RE) { /* * "RE" Format: * len ver * +----+----+----+----+ * | 'R'| 'E'| 04 | 01 | * +----+----+----+----+ * 0 1 2 3 4 */ length = 4; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'R'; bp[2] = 'E'; bp[3] = length; bp[4] = 1; /* version */ bp += length; } extra_tell_used_size(&ctl, length); } /* Write "PL" System Use Entry. */ if (rr_flag & RR_USE_PL) { /* * "PL" Format: * len ver * +----+----+----+----+------------+ * | 'P'| 'L'| 0C | 01 | *LOCATION | * +----+----+----+----+------------+ * 0 1 2 3 4 12 * *LOCATION: location of parent directory */ length = 12; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'P'; bp[2] = 'L'; bp[3] = length; bp[4] = 1; /* version */ set_num_733(bp + 5, rr_parent->dir_location); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "CL" System Use Entry. */ if (rr_flag & RR_USE_CL) { /* * "CL" Format: * len ver * +----+----+----+----+------------+ * | 'C'| 'L'| 0C | 01 | *LOCATION | * +----+----+----+----+------------+ * 0 1 2 3 4 12 * *LOCATION: location of child directory */ length = 12; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'C'; bp[2] = 'L'; bp[3] = length; bp[4] = 1; /* version */ set_num_733(bp + 5, isoent->rr_child->dir_location); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "PN" System Use Entry. */ if (rr_flag & RR_USE_PN) { /* * "PN" Format: * len ver * +----+----+----+----+------------+------------+ * | 'P'| 'N'| 14 | 01 | dev_t high | dev_t low | * +----+----+----+----+------------+------------+ * 0 1 2 3 4 12 20 */ length = 20; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { uint64_t dev; bp[1] = 'P'; bp[2] = 'N'; bp[3] = length; bp[4] = 1; /* version */ dev = (uint64_t)archive_entry_rdev(file->entry); set_num_733(bp + 5, (uint32_t)(dev >> 32)); set_num_733(bp + 13, (uint32_t)(dev & 0xFFFFFFFF)); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "ZF" System Use Entry. */ if (file->zisofs.header_size) { /* * "ZF" Format: * len ver * +----+----+----+----+----+----+-------------+ * | 'Z'| 'F'| 10 | 01 | 'p'| 'z'| Header Size | * +----+----+----+----+----+----+-------------+ * 0 1 2 3 4 5 6 7 * +--------------------+-------------------+ * | Log2 of block Size | Uncompressed Size | * +--------------------+-------------------+ * 7 8 16 */ length = 16; if (extra_space(&ctl) < length) bp = extra_next_record(&ctl, length); if (bp != NULL) { bp[1] = 'Z'; bp[2] = 'F'; bp[3] = length; bp[4] = 1; /* version */ bp[5] = 'p'; bp[6] = 'z'; bp[7] = file->zisofs.header_size; bp[8] = file->zisofs.log2_bs; set_num_733(bp + 9, file->zisofs.uncompressed_size); bp += length; } extra_tell_used_size(&ctl, length); } /* Write "CE" System Use Entry. */ if (t == DIR_REC_SELF && isoent == isoent->parent) { length = RR_CE_SIZE; if (bp != NULL) set_SUSP_CE(bp+1, iso9660->location_rrip_er, 0, RRIP_ER_SIZE); extra_tell_used_size(&ctl, length); } extra_close_record(&ctl, 0); return (ctl.dr_len); } /* * Write data of a Directory Record or calculate writing bytes itself. * If parameter `p' is NULL, calculates the size of writing data, which * a Directory Record needs to write, then it saved and return * the calculated size. * Parameter `n' is a remaining size of buffer. when parameter `p' is * not NULL, check whether that `n' is not less than the saved size. * if that `n' is small, return zero. * * This format of the Directory Record is according to * ISO9660 Standard 9.1 */ static int set_directory_record(unsigned char *p, size_t n, struct isoent *isoent, struct iso9660 *iso9660, enum dir_rec_type t, enum vdd_type vdd_type) { unsigned char *bp; size_t dr_len; size_t fi_len; if (p != NULL) { /* * Check whether a write buffer size is less than the * saved size which is needed to write this Directory * Record. */ switch (t) { case DIR_REC_VD: dr_len = isoent->dr_len.vd; break; case DIR_REC_SELF: dr_len = isoent->dr_len.self; break; case DIR_REC_PARENT: dr_len = isoent->dr_len.parent; break; case DIR_REC_NORMAL: default: dr_len = isoent->dr_len.normal; break; } if (dr_len > n) return (0);/* Needs more buffer size. */ } if (t == DIR_REC_NORMAL && isoent->identifier != NULL) fi_len = isoent->id_len; else fi_len = 1; if (p != NULL) { struct isoent *xisoent; struct isofile *file; unsigned char flag; if (t == DIR_REC_PARENT) xisoent = isoent->parent; else xisoent = isoent; file = isoent->file; if (file->hardlink_target != NULL) file = file->hardlink_target; /* Make a file flag. */ if (xisoent->dir) flag = FILE_FLAG_DIRECTORY; else { if (file->cur_content->next != NULL) flag = FILE_FLAG_MULTI_EXTENT; else flag = 0; } bp = p -1; /* Extended Attribute Record Length */ set_num_711(bp+2, 0); /* Location of Extent */ if (xisoent->dir) set_num_733(bp+3, xisoent->dir_location); else set_num_733(bp+3, file->cur_content->location); /* Data Length */ if (xisoent->dir) set_num_733(bp+11, xisoent->dir_block * LOGICAL_BLOCK_SIZE); else set_num_733(bp+11, (uint32_t)file->cur_content->size); /* Recording Date and Time */ /* NOTE: * If a file type is symbolic link, you are seeing this * field value is different from a value mkisofs makes. * libarchive uses lstat to get this one, but it * seems mkisofs uses stat to get. */ set_time_915(bp+19, archive_entry_mtime(xisoent->file->entry)); /* File Flags */ bp[26] = flag; /* File Unit Size */ set_num_711(bp+27, 0); /* Interleave Gap Size */ set_num_711(bp+28, 0); /* Volume Sequence Number */ set_num_723(bp+29, iso9660->volume_sequence_number); /* Length of File Identifier */ set_num_711(bp+33, (unsigned char)fi_len); /* File Identifier */ switch (t) { case DIR_REC_VD: case DIR_REC_SELF: set_num_711(bp+34, 0); break; case DIR_REC_PARENT: set_num_711(bp+34, 1); break; case DIR_REC_NORMAL: if (isoent->identifier != NULL) memcpy(bp+34, isoent->identifier, fi_len); else set_num_711(bp+34, 0); break; } } else bp = NULL; dr_len = 33 + fi_len; /* Padding Field */ if (dr_len & 0x01) { dr_len ++; if (p != NULL) bp[dr_len] = 0; } /* Volume Descriptor does not record extension. */ if (t == DIR_REC_VD) { if (p != NULL) /* Length of Directory Record */ set_num_711(p, (unsigned char)dr_len); else isoent->dr_len.vd = (int)dr_len; return ((int)dr_len); } /* Rockridge */ if (iso9660->opt.rr && vdd_type != VDD_JOLIET) dr_len = set_directory_record_rr(bp, (int)dr_len, isoent, iso9660, t); if (p != NULL) /* Length of Directory Record */ set_num_711(p, (unsigned char)dr_len); else { /* * Save the size which is needed to write this * Directory Record. */ switch (t) { case DIR_REC_VD: /* This case does not come, but compiler * complains that DIR_REC_VD not handled * in switch .... */ break; case DIR_REC_SELF: isoent->dr_len.self = (int)dr_len; break; case DIR_REC_PARENT: isoent->dr_len.parent = (int)dr_len; break; case DIR_REC_NORMAL: isoent->dr_len.normal = (int)dr_len; break; } } return ((int)dr_len); } /* * Calculate the size of a directory record. */ static inline int get_dir_rec_size(struct iso9660 *iso9660, struct isoent *isoent, enum dir_rec_type t, enum vdd_type vdd_type) { return (set_directory_record(NULL, SIZE_MAX, isoent, iso9660, t, vdd_type)); } /* * Manage to write ISO-image data with wbuff to reduce calling * __archive_write_output() for performance. */ static inline unsigned char * wb_buffptr(struct archive_write *a) { struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; return (&(iso9660->wbuff[sizeof(iso9660->wbuff) - iso9660->wbuff_remaining])); } static int wb_write_out(struct archive_write *a) { struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; size_t wsize, nw; int r; wsize = sizeof(iso9660->wbuff) - iso9660->wbuff_remaining; nw = wsize % LOGICAL_BLOCK_SIZE; if (iso9660->wbuff_type == WB_TO_STREAM) r = __archive_write_output(a, iso9660->wbuff, wsize - nw); else r = write_to_temp(a, iso9660->wbuff, wsize - nw); /* Increase the offset. */ iso9660->wbuff_offset += wsize - nw; if (iso9660->wbuff_offset > iso9660->wbuff_written) iso9660->wbuff_written = iso9660->wbuff_offset; iso9660->wbuff_remaining = sizeof(iso9660->wbuff); if (nw) { iso9660->wbuff_remaining -= nw; memmove(iso9660->wbuff, iso9660->wbuff + wsize - nw, nw); } return (r); } static int wb_consume(struct archive_write *a, size_t size) { struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; if (size > iso9660->wbuff_remaining || iso9660->wbuff_remaining == 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal Programing error: iso9660:wb_consume()" " size=%jd, wbuff_remaining=%jd", (intmax_t)size, (intmax_t)iso9660->wbuff_remaining); return (ARCHIVE_FATAL); } iso9660->wbuff_remaining -= size; if (iso9660->wbuff_remaining < LOGICAL_BLOCK_SIZE) return (wb_write_out(a)); return (ARCHIVE_OK); } #ifdef HAVE_ZLIB_H static int wb_set_offset(struct archive_write *a, int64_t off) { struct iso9660 *iso9660 = (struct iso9660 *)a->format_data; int64_t used, ext_bytes; if (iso9660->wbuff_type != WB_TO_TEMP) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal Programing error: iso9660:wb_set_offset()"); return (ARCHIVE_FATAL); } used = sizeof(iso9660->wbuff) - iso9660->wbuff_remaining; if (iso9660->wbuff_offset + used > iso9660->wbuff_tail) iso9660->wbuff_tail = iso9660->wbuff_offset + used; if (iso9660->wbuff_offset < iso9660->wbuff_written) { if (used > 0 && write_to_temp(a, iso9660->wbuff, (size_t)used) != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->wbuff_offset = iso9660->wbuff_written; lseek(iso9660->temp_fd, iso9660->wbuff_offset, SEEK_SET); iso9660->wbuff_remaining = sizeof(iso9660->wbuff); used = 0; } if (off < iso9660->wbuff_offset) { /* * Write out waiting data. */ if (used > 0) { if (wb_write_out(a) != ARCHIVE_OK) return (ARCHIVE_FATAL); } lseek(iso9660->temp_fd, off, SEEK_SET); iso9660->wbuff_offset = off; iso9660->wbuff_remaining = sizeof(iso9660->wbuff); } else if (off <= iso9660->wbuff_tail) { iso9660->wbuff_remaining = (size_t) (sizeof(iso9660->wbuff) - (off - iso9660->wbuff_offset)); } else { ext_bytes = off - iso9660->wbuff_tail; iso9660->wbuff_remaining = (size_t)(sizeof(iso9660->wbuff) - (iso9660->wbuff_tail - iso9660->wbuff_offset)); while (ext_bytes >= (int64_t)iso9660->wbuff_remaining) { if (write_null(a, (size_t)iso9660->wbuff_remaining) != ARCHIVE_OK) return (ARCHIVE_FATAL); ext_bytes -= iso9660->wbuff_remaining; } if (ext_bytes > 0) { if (write_null(a, (size_t)ext_bytes) != ARCHIVE_OK) return (ARCHIVE_FATAL); } } return (ARCHIVE_OK); } #endif /* HAVE_ZLIB_H */ static int write_null(struct archive_write *a, size_t size) { size_t remaining; unsigned char *p, *old; int r; remaining = wb_remaining(a); p = wb_buffptr(a); if (size <= remaining) { memset(p, 0, size); return (wb_consume(a, size)); } memset(p, 0, remaining); r = wb_consume(a, remaining); if (r != ARCHIVE_OK) return (r); size -= remaining; old = p; p = wb_buffptr(a); memset(p, 0, old - p); remaining = wb_remaining(a); while (size) { size_t wsize = size; if (wsize > remaining) wsize = remaining; r = wb_consume(a, wsize); if (r != ARCHIVE_OK) return (r); size -= wsize; } return (ARCHIVE_OK); } /* * Write Volume Descriptor Set Terminator */ static int write_VD_terminator(struct archive_write *a) { unsigned char *bp; bp = wb_buffptr(a) -1; set_VD_bp(bp, VDT_TERMINATOR, 1); set_unused_field_bp(bp, 8, LOGICAL_BLOCK_SIZE); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } static int set_file_identifier(unsigned char *bp, int from, int to, enum vdc vdc, struct archive_write *a, struct vdd *vdd, struct archive_string *id, const char *label, int leading_under, enum char_type char_type) { char identifier[256]; struct isoent *isoent; const char *ids; size_t len; int r; if (id->length > 0 && leading_under && id->s[0] != '_') { if (char_type == A_CHAR) r = set_str_a_characters_bp(a, bp, from, to, id->s, vdc); else r = set_str_d_characters_bp(a, bp, from, to, id->s, vdc); } else if (id->length > 0) { ids = id->s; if (leading_under) ids++; isoent = isoent_find_entry(vdd->rootent, ids); if (isoent == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Not Found %s `%s'.", label, ids); return (ARCHIVE_FATAL); } len = isoent->ext_off + isoent->ext_len; if (vdd->vdd_type == VDD_JOLIET) { if (len > sizeof(identifier)-2) len = sizeof(identifier)-2; } else { if (len > sizeof(identifier)-1) len = sizeof(identifier)-1; } memcpy(identifier, isoent->identifier, len); identifier[len] = '\0'; if (vdd->vdd_type == VDD_JOLIET) { identifier[len+1] = 0; vdc = VDC_UCS2_DIRECT; } if (char_type == A_CHAR) r = set_str_a_characters_bp(a, bp, from, to, identifier, vdc); else r = set_str_d_characters_bp(a, bp, from, to, identifier, vdc); } else { if (char_type == A_CHAR) r = set_str_a_characters_bp(a, bp, from, to, NULL, vdc); else r = set_str_d_characters_bp(a, bp, from, to, NULL, vdc); } return (r); } /* * Write Primary/Supplementary Volume Descriptor */ static int write_VD(struct archive_write *a, struct vdd *vdd) { struct iso9660 *iso9660; unsigned char *bp; uint16_t volume_set_size = 1; char identifier[256]; enum VD_type vdt; enum vdc vdc; unsigned char vd_ver, fst_ver; int r; iso9660 = a->format_data; switch (vdd->vdd_type) { case VDD_JOLIET: vdt = VDT_SUPPLEMENTARY; vd_ver = fst_ver = 1; vdc = VDC_UCS2; break; case VDD_ENHANCED: vdt = VDT_SUPPLEMENTARY; vd_ver = fst_ver = 2; vdc = VDC_LOWERCASE; break; case VDD_PRIMARY: default: vdt = VDT_PRIMARY; vd_ver = fst_ver = 1; #ifdef COMPAT_MKISOFS vdc = VDC_LOWERCASE; #else vdc = VDC_STD; #endif break; } bp = wb_buffptr(a) -1; /* Volume Descriptor Type */ set_VD_bp(bp, vdt, vd_ver); /* Unused Field */ set_unused_field_bp(bp, 8, 8); /* System Identifier */ get_system_identitier(identifier, sizeof(identifier)); r = set_str_a_characters_bp(a, bp, 9, 40, identifier, vdc); if (r != ARCHIVE_OK) return (r); /* Volume Identifier */ r = set_str_d_characters_bp(a, bp, 41, 72, iso9660->volume_identifier.s, vdc); if (r != ARCHIVE_OK) return (r); /* Unused Field */ set_unused_field_bp(bp, 73, 80); /* Volume Space Size */ set_num_733(bp+81, iso9660->volume_space_size); if (vdd->vdd_type == VDD_JOLIET) { /* Escape Sequences */ bp[89] = 0x25;/* UCS-2 Level 3 */ bp[90] = 0x2F; bp[91] = 0x45; memset(bp + 92, 0, 120 - 92 + 1); } else { /* Unused Field */ set_unused_field_bp(bp, 89, 120); } /* Volume Set Size */ set_num_723(bp+121, volume_set_size); /* Volume Sequence Number */ set_num_723(bp+125, iso9660->volume_sequence_number); /* Logical Block Size */ set_num_723(bp+129, LOGICAL_BLOCK_SIZE); /* Path Table Size */ set_num_733(bp+133, vdd->path_table_size); /* Location of Occurrence of Type L Path Table */ set_num_731(bp+141, vdd->location_type_L_path_table); /* Location of Optional Occurrence of Type L Path Table */ set_num_731(bp+145, 0); /* Location of Occurrence of Type M Path Table */ set_num_732(bp+149, vdd->location_type_M_path_table); /* Location of Optional Occurrence of Type M Path Table */ set_num_732(bp+153, 0); /* Directory Record for Root Directory(BP 157 to 190) */ set_directory_record(bp+157, 190-157+1, vdd->rootent, iso9660, DIR_REC_VD, vdd->vdd_type); /* Volume Set Identifier */ r = set_str_d_characters_bp(a, bp, 191, 318, "", vdc); if (r != ARCHIVE_OK) return (r); /* Publisher Identifier */ r = set_file_identifier(bp, 319, 446, vdc, a, vdd, &(iso9660->publisher_identifier), "Publisher File", 1, A_CHAR); if (r != ARCHIVE_OK) return (r); /* Data Preparer Identifier */ r = set_file_identifier(bp, 447, 574, vdc, a, vdd, &(iso9660->data_preparer_identifier), "Data Preparer File", 1, A_CHAR); if (r != ARCHIVE_OK) return (r); /* Application Identifier */ r = set_file_identifier(bp, 575, 702, vdc, a, vdd, &(iso9660->application_identifier), "Application File", 1, A_CHAR); if (r != ARCHIVE_OK) return (r); /* Copyright File Identifier */ r = set_file_identifier(bp, 703, 739, vdc, a, vdd, &(iso9660->copyright_file_identifier), "Copyright File", 0, D_CHAR); if (r != ARCHIVE_OK) return (r); /* Abstract File Identifier */ r = set_file_identifier(bp, 740, 776, vdc, a, vdd, &(iso9660->abstract_file_identifier), "Abstract File", 0, D_CHAR); if (r != ARCHIVE_OK) return (r); /* Bibliongraphic File Identifier */ r = set_file_identifier(bp, 777, 813, vdc, a, vdd, &(iso9660->bibliographic_file_identifier), "Bibliongraphic File", 0, D_CHAR); if (r != ARCHIVE_OK) return (r); /* Volume Creation Date and Time */ set_date_time(bp+814, iso9660->birth_time); /* Volume Modification Date and Time */ set_date_time(bp+831, iso9660->birth_time); /* Volume Expiration Date and Time(obsolete) */ set_date_time_null(bp+848); /* Volume Effective Date and Time */ set_date_time(bp+865, iso9660->birth_time); /* File Structure Version */ bp[882] = fst_ver; /* Reserved */ bp[883] = 0; /* Application Use */ memset(bp + 884, 0x20, 1395 - 884 + 1); /* Reserved */ set_unused_field_bp(bp, 1396, LOGICAL_BLOCK_SIZE); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } /* * Write Boot Record Volume Descriptor */ static int write_VD_boot_record(struct archive_write *a) { struct iso9660 *iso9660; unsigned char *bp; iso9660 = a->format_data; bp = wb_buffptr(a) -1; /* Volume Descriptor Type */ set_VD_bp(bp, VDT_BOOT_RECORD, 1); /* Boot System Identifier */ memcpy(bp+8, "EL TORITO SPECIFICATION", 23); set_unused_field_bp(bp, 8+23, 39); /* Unused */ set_unused_field_bp(bp, 40, 71); /* Absolute pointer to first sector of Boot Catalog */ set_num_731(bp+72, iso9660->el_torito.catalog->file->content.location); /* Unused */ set_unused_field_bp(bp, 76, LOGICAL_BLOCK_SIZE); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } enum keytype { KEY_FLG, KEY_STR, KEY_INT, KEY_HEX }; static void set_option_info(struct archive_string *info, int *opt, const char *key, enum keytype type, ...) { va_list ap; char prefix; const char *s; int d; prefix = (*opt==0)? ' ':','; va_start(ap, type); switch (type) { case KEY_FLG: d = va_arg(ap, int); archive_string_sprintf(info, "%c%s%s", prefix, (d == 0)?"!":"", key); break; case KEY_STR: s = va_arg(ap, const char *); archive_string_sprintf(info, "%c%s=%s", prefix, key, s); break; case KEY_INT: d = va_arg(ap, int); archive_string_sprintf(info, "%c%s=%d", prefix, key, d); break; case KEY_HEX: d = va_arg(ap, int); archive_string_sprintf(info, "%c%s=%x", prefix, key, d); break; } va_end(ap); *opt = 1; } /* * Make Non-ISO File System Information */ static int write_information_block(struct archive_write *a) { struct iso9660 *iso9660; char buf[128]; const char *v; int opt, r; struct archive_string info; size_t info_size = LOGICAL_BLOCK_SIZE * NON_ISO_FILE_SYSTEM_INFORMATION_BLOCK; iso9660 = (struct iso9660 *)a->format_data; if (info_size > wb_remaining(a)) { r = wb_write_out(a); if (r != ARCHIVE_OK) return (r); } archive_string_init(&info); if (archive_string_ensure(&info, info_size) == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } memset(info.s, 0, info_size); opt = 0; #if defined(HAVE__CTIME64_S) _ctime64_s(buf, sizeof(buf), &(iso9660->birth_time)); #elif defined(HAVE_CTIME_R) ctime_r(&(iso9660->birth_time), buf); #else strncpy(buf, ctime(&(iso9660->birth_time)), sizeof(buf)-1); buf[sizeof(buf)-1] = '\0'; #endif archive_string_sprintf(&info, "INFO %s%s", buf, archive_version_string()); if (iso9660->opt.abstract_file != OPT_ABSTRACT_FILE_DEFAULT) set_option_info(&info, &opt, "abstract-file", KEY_STR, iso9660->abstract_file_identifier.s); if (iso9660->opt.application_id != OPT_APPLICATION_ID_DEFAULT) set_option_info(&info, &opt, "application-id", KEY_STR, iso9660->application_identifier.s); if (iso9660->opt.allow_vernum != OPT_ALLOW_VERNUM_DEFAULT) set_option_info(&info, &opt, "allow-vernum", KEY_FLG, iso9660->opt.allow_vernum); if (iso9660->opt.biblio_file != OPT_BIBLIO_FILE_DEFAULT) set_option_info(&info, &opt, "biblio-file", KEY_STR, iso9660->bibliographic_file_identifier.s); if (iso9660->opt.boot != OPT_BOOT_DEFAULT) set_option_info(&info, &opt, "boot", KEY_STR, iso9660->el_torito.boot_filename.s); if (iso9660->opt.boot_catalog != OPT_BOOT_CATALOG_DEFAULT) set_option_info(&info, &opt, "boot-catalog", KEY_STR, iso9660->el_torito.catalog_filename.s); if (iso9660->opt.boot_info_table != OPT_BOOT_INFO_TABLE_DEFAULT) set_option_info(&info, &opt, "boot-info-table", KEY_FLG, iso9660->opt.boot_info_table); if (iso9660->opt.boot_load_seg != OPT_BOOT_LOAD_SEG_DEFAULT) set_option_info(&info, &opt, "boot-load-seg", KEY_HEX, iso9660->el_torito.boot_load_seg); if (iso9660->opt.boot_load_size != OPT_BOOT_LOAD_SIZE_DEFAULT) set_option_info(&info, &opt, "boot-load-size", KEY_INT, iso9660->el_torito.boot_load_size); if (iso9660->opt.boot_type != OPT_BOOT_TYPE_DEFAULT) { v = "no-emulation"; if (iso9660->opt.boot_type == OPT_BOOT_TYPE_FD) v = "fd"; if (iso9660->opt.boot_type == OPT_BOOT_TYPE_HARD_DISK) v = "hard-disk"; set_option_info(&info, &opt, "boot-type", KEY_STR, v); } #ifdef HAVE_ZLIB_H if (iso9660->opt.compression_level != OPT_COMPRESSION_LEVEL_DEFAULT) set_option_info(&info, &opt, "compression-level", KEY_INT, iso9660->zisofs.compression_level); #endif if (iso9660->opt.copyright_file != OPT_COPYRIGHT_FILE_DEFAULT) set_option_info(&info, &opt, "copyright-file", KEY_STR, iso9660->copyright_file_identifier.s); if (iso9660->opt.iso_level != OPT_ISO_LEVEL_DEFAULT) set_option_info(&info, &opt, "iso-level", KEY_INT, iso9660->opt.iso_level); if (iso9660->opt.joliet != OPT_JOLIET_DEFAULT) { if (iso9660->opt.joliet == OPT_JOLIET_LONGNAME) set_option_info(&info, &opt, "joliet", KEY_STR, "long"); else set_option_info(&info, &opt, "joliet", KEY_FLG, iso9660->opt.joliet); } if (iso9660->opt.limit_depth != OPT_LIMIT_DEPTH_DEFAULT) set_option_info(&info, &opt, "limit-depth", KEY_FLG, iso9660->opt.limit_depth); if (iso9660->opt.limit_dirs != OPT_LIMIT_DIRS_DEFAULT) set_option_info(&info, &opt, "limit-dirs", KEY_FLG, iso9660->opt.limit_dirs); if (iso9660->opt.pad != OPT_PAD_DEFAULT) set_option_info(&info, &opt, "pad", KEY_FLG, iso9660->opt.pad); if (iso9660->opt.publisher != OPT_PUBLISHER_DEFAULT) set_option_info(&info, &opt, "publisher", KEY_STR, iso9660->publisher_identifier.s); if (iso9660->opt.rr != OPT_RR_DEFAULT) { if (iso9660->opt.rr == OPT_RR_DISABLED) set_option_info(&info, &opt, "rockridge", KEY_FLG, iso9660->opt.rr); else if (iso9660->opt.rr == OPT_RR_STRICT) set_option_info(&info, &opt, "rockridge", KEY_STR, "strict"); else if (iso9660->opt.rr == OPT_RR_USEFUL) set_option_info(&info, &opt, "rockridge", KEY_STR, "useful"); } if (iso9660->opt.volume_id != OPT_VOLUME_ID_DEFAULT) set_option_info(&info, &opt, "volume-id", KEY_STR, iso9660->volume_identifier.s); if (iso9660->opt.zisofs != OPT_ZISOFS_DEFAULT) set_option_info(&info, &opt, "zisofs", KEY_FLG, iso9660->opt.zisofs); memcpy(wb_buffptr(a), info.s, info_size); archive_string_free(&info); return (wb_consume(a, info_size)); } static int write_rr_ER(struct archive_write *a) { unsigned char *p; p = wb_buffptr(a); memset(p, 0, LOGICAL_BLOCK_SIZE); p[0] = 'E'; p[1] = 'R'; p[3] = 0x01; p[2] = RRIP_ER_SIZE; p[4] = RRIP_ER_ID_SIZE; p[5] = RRIP_ER_DSC_SIZE; p[6] = RRIP_ER_SRC_SIZE; p[7] = 0x01; memcpy(&p[8], rrip_identifier, p[4]); memcpy(&p[8+p[4]], rrip_descriptor, p[5]); memcpy(&p[8+p[4]+p[5]], rrip_source, p[6]); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } static void calculate_path_table_size(struct vdd *vdd) { int depth, size; struct path_table *pt; pt = vdd->pathtbl; size = 0; for (depth = 0; depth < vdd->max_depth; depth++) { struct isoent **ptbl; int i, cnt; if ((cnt = pt[depth].cnt) == 0) break; ptbl = pt[depth].sorted; for (i = 0; i < cnt; i++) { int len; if (ptbl[i]->identifier == NULL) len = 1; /* root directory */ else len = ptbl[i]->id_len; if (len & 0x01) len++; /* Padding Field */ size += 8 + len; } } vdd->path_table_size = size; vdd->path_table_block = ((size + PATH_TABLE_BLOCK_SIZE -1) / PATH_TABLE_BLOCK_SIZE) * (PATH_TABLE_BLOCK_SIZE / LOGICAL_BLOCK_SIZE); } static int _write_path_table(struct archive_write *a, int type_m, int depth, struct vdd *vdd) { unsigned char *bp, *wb; struct isoent **ptbl; size_t wbremaining; int i, r, wsize; if (vdd->pathtbl[depth].cnt == 0) return (0); wsize = 0; wb = wb_buffptr(a); wbremaining = wb_remaining(a); bp = wb - 1; ptbl = vdd->pathtbl[depth].sorted; for (i = 0; i < vdd->pathtbl[depth].cnt; i++) { struct isoent *np; size_t len; np = ptbl[i]; if (np->identifier == NULL) len = 1; /* root directory */ else len = np->id_len; if (wbremaining - ((bp+1) - wb) < (len + 1 + 8)) { r = wb_consume(a, (bp+1) - wb); if (r < 0) return (r); wb = wb_buffptr(a); wbremaining = wb_remaining(a); bp = wb -1; } /* Length of Directory Identifier */ set_num_711(bp+1, (unsigned char)len); /* Extended Attribute Record Length */ set_num_711(bp+2, 0); /* Location of Extent */ if (type_m) set_num_732(bp+3, np->dir_location); else set_num_731(bp+3, np->dir_location); /* Parent Directory Number */ if (type_m) set_num_722(bp+7, np->parent->dir_number); else set_num_721(bp+7, np->parent->dir_number); /* Directory Identifier */ if (np->identifier == NULL) bp[9] = 0; else memcpy(&bp[9], np->identifier, len); if (len & 0x01) { /* Padding Field */ bp[9+len] = 0; len++; } wsize += 8 + (int)len; bp += 8 + len; } if ((bp + 1) > wb) { r = wb_consume(a, (bp+1)-wb); if (r < 0) return (r); } return (wsize); } static int write_path_table(struct archive_write *a, int type_m, struct vdd *vdd) { int depth, r; size_t path_table_size; r = ARCHIVE_OK; path_table_size = 0; for (depth = 0; depth < vdd->max_depth; depth++) { r = _write_path_table(a, type_m, depth, vdd); if (r < 0) return (r); path_table_size += r; } /* Write padding data. */ path_table_size = path_table_size % PATH_TABLE_BLOCK_SIZE; if (path_table_size > 0) r = write_null(a, PATH_TABLE_BLOCK_SIZE - path_table_size); return (r); } static int calculate_directory_descriptors(struct iso9660 *iso9660, struct vdd *vdd, struct isoent *isoent, int depth) { struct isoent **enttbl; int bs, block, i; block = 1; bs = get_dir_rec_size(iso9660, isoent, DIR_REC_SELF, vdd->vdd_type); bs += get_dir_rec_size(iso9660, isoent, DIR_REC_PARENT, vdd->vdd_type); if (isoent->children.cnt <= 0 || (vdd->vdd_type != VDD_JOLIET && !iso9660->opt.rr && depth + 1 >= vdd->max_depth)) return (block); enttbl = isoent->children_sorted; for (i = 0; i < isoent->children.cnt; i++) { struct isoent *np = enttbl[i]; struct isofile *file; file = np->file; if (file->hardlink_target != NULL) file = file->hardlink_target; file->cur_content = &(file->content); do { int dr_l; dr_l = get_dir_rec_size(iso9660, np, DIR_REC_NORMAL, vdd->vdd_type); if ((bs + dr_l) > LOGICAL_BLOCK_SIZE) { block ++; bs = dr_l; } else bs += dr_l; file->cur_content = file->cur_content->next; } while (file->cur_content != NULL); } return (block); } static int _write_directory_descriptors(struct archive_write *a, struct vdd *vdd, struct isoent *isoent, int depth) { struct iso9660 *iso9660 = a->format_data; struct isoent **enttbl; unsigned char *p, *wb; int i, r; int dr_l; p = wb = wb_buffptr(a); #define WD_REMAINING (LOGICAL_BLOCK_SIZE - (p - wb)) p += set_directory_record(p, WD_REMAINING, isoent, iso9660, DIR_REC_SELF, vdd->vdd_type); p += set_directory_record(p, WD_REMAINING, isoent, iso9660, DIR_REC_PARENT, vdd->vdd_type); if (isoent->children.cnt <= 0 || (vdd->vdd_type != VDD_JOLIET && !iso9660->opt.rr && depth + 1 >= vdd->max_depth)) { memset(p, 0, WD_REMAINING); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } enttbl = isoent->children_sorted; for (i = 0; i < isoent->children.cnt; i++) { struct isoent *np = enttbl[i]; struct isofile *file = np->file; if (file->hardlink_target != NULL) file = file->hardlink_target; file->cur_content = &(file->content); do { dr_l = set_directory_record(p, WD_REMAINING, np, iso9660, DIR_REC_NORMAL, vdd->vdd_type); if (dr_l == 0) { memset(p, 0, WD_REMAINING); r = wb_consume(a, LOGICAL_BLOCK_SIZE); if (r < 0) return (r); p = wb = wb_buffptr(a); dr_l = set_directory_record(p, WD_REMAINING, np, iso9660, DIR_REC_NORMAL, vdd->vdd_type); } p += dr_l; file->cur_content = file->cur_content->next; } while (file->cur_content != NULL); } memset(p, 0, WD_REMAINING); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } static int write_directory_descriptors(struct archive_write *a, struct vdd *vdd) { struct isoent *np; int depth, r; depth = 0; np = vdd->rootent; do { struct extr_rec *extr; r = _write_directory_descriptors(a, vdd, np, depth); if (r < 0) return (r); if (vdd->vdd_type != VDD_JOLIET) { /* * This extract record is used by SUSP,RRIP. * Not for joliet. */ for (extr = np->extr_rec_list.first; extr != NULL; extr = extr->next) { unsigned char *wb; wb = wb_buffptr(a); memcpy(wb, extr->buf, extr->offset); memset(wb + extr->offset, 0, LOGICAL_BLOCK_SIZE - extr->offset); r = wb_consume(a, LOGICAL_BLOCK_SIZE); if (r < 0) return (r); } } if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } while (np != np->parent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != np->parent); return (ARCHIVE_OK); } /* * Read file contents from the temporary file, and write it. */ static int write_file_contents(struct archive_write *a, int64_t offset, int64_t size) { struct iso9660 *iso9660 = a->format_data; int r; lseek(iso9660->temp_fd, offset, SEEK_SET); while (size) { size_t rsize; ssize_t rs; unsigned char *wb; wb = wb_buffptr(a); rsize = wb_remaining(a); if (rsize > (size_t)size) rsize = (size_t)size; rs = read(iso9660->temp_fd, wb, rsize); if (rs <= 0) { archive_set_error(&a->archive, errno, "Can't read temporary file(%jd)", (intmax_t)rs); return (ARCHIVE_FATAL); } size -= rs; r = wb_consume(a, rs); if (r < 0) return (r); } return (ARCHIVE_OK); } static int write_file_descriptors(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; struct isofile *file; int64_t blocks, offset; int r; blocks = 0; offset = 0; /* Make the boot catalog contents, and write it. */ if (iso9660->el_torito.catalog != NULL) { r = make_boot_catalog(a); if (r < 0) return (r); } /* Write the boot file contents. */ if (iso9660->el_torito.boot != NULL) { file = iso9660->el_torito.boot->file; blocks = file->content.blocks; offset = file->content.offset_of_temp; if (offset != 0) { r = write_file_contents(a, offset, blocks << LOGICAL_BLOCK_BITS); if (r < 0) return (r); blocks = 0; offset = 0; } } /* Write out all file contents. */ for (file = iso9660->data_file_list.first; file != NULL; file = file->datanext) { if (!file->write_content) continue; if ((offset + (blocks << LOGICAL_BLOCK_BITS)) < file->content.offset_of_temp) { if (blocks > 0) { r = write_file_contents(a, offset, blocks << LOGICAL_BLOCK_BITS); if (r < 0) return (r); } blocks = 0; offset = file->content.offset_of_temp; } file->cur_content = &(file->content); do { blocks += file->cur_content->blocks; /* Next fragument */ file->cur_content = file->cur_content->next; } while (file->cur_content != NULL); } /* Flush out remaining blocks. */ if (blocks > 0) { r = write_file_contents(a, offset, blocks << LOGICAL_BLOCK_BITS); if (r < 0) return (r); } return (ARCHIVE_OK); } static void isofile_init_entry_list(struct iso9660 *iso9660) { iso9660->all_file_list.first = NULL; iso9660->all_file_list.last = &(iso9660->all_file_list.first); } static void isofile_add_entry(struct iso9660 *iso9660, struct isofile *file) { file->allnext = NULL; *iso9660->all_file_list.last = file; iso9660->all_file_list.last = &(file->allnext); } static void isofile_free_all_entries(struct iso9660 *iso9660) { struct isofile *file, *file_next; file = iso9660->all_file_list.first; while (file != NULL) { file_next = file->allnext; isofile_free(file); file = file_next; } } static void isofile_init_entry_data_file_list(struct iso9660 *iso9660) { iso9660->data_file_list.first = NULL; iso9660->data_file_list.last = &(iso9660->data_file_list.first); } static void isofile_add_data_file(struct iso9660 *iso9660, struct isofile *file) { file->datanext = NULL; *iso9660->data_file_list.last = file; iso9660->data_file_list.last = &(file->datanext); } static struct isofile * isofile_new(struct archive_write *a, struct archive_entry *entry) { struct isofile *file; file = calloc(1, sizeof(*file)); if (file == NULL) return (NULL); if (entry != NULL) file->entry = archive_entry_clone(entry); else file->entry = archive_entry_new2(&a->archive); if (file->entry == NULL) { free(file); return (NULL); } archive_string_init(&(file->parentdir)); archive_string_init(&(file->basename)); archive_string_init(&(file->basename_utf16)); archive_string_init(&(file->symlink)); file->cur_content = &(file->content); return (file); } static void isofile_free(struct isofile *file) { struct content *con, *tmp; con = file->content.next; while (con != NULL) { tmp = con; con = con->next; free(tmp); } archive_entry_free(file->entry); archive_string_free(&(file->parentdir)); archive_string_free(&(file->basename)); archive_string_free(&(file->basename_utf16)); archive_string_free(&(file->symlink)); free(file); } #if defined(_WIN32) || defined(__CYGWIN__) static int cleanup_backslash_1(char *p) { int mb, dos; mb = dos = 0; while (*p) { if (*(unsigned char *)p > 127) mb = 1; if (*p == '\\') { /* If we have not met any multi-byte characters, * we can replace '\' with '/'. */ if (!mb) *p = '/'; dos = 1; } p++; } if (!mb || !dos) return (0); return (-1); } static void cleanup_backslash_2(wchar_t *p) { /* Convert a path-separator from '\' to '/' */ while (*p != L'\0') { if (*p == L'\\') *p = L'/'; p++; } } #endif /* * Generate a parent directory name and a base name from a pathname. */ static int isofile_gen_utility_names(struct archive_write *a, struct isofile *file) { struct iso9660 *iso9660; const char *pathname; char *p, *dirname, *slash; size_t len; int ret = ARCHIVE_OK; iso9660 = a->format_data; archive_string_empty(&(file->parentdir)); archive_string_empty(&(file->basename)); archive_string_empty(&(file->basename_utf16)); archive_string_empty(&(file->symlink)); pathname = archive_entry_pathname(file->entry); if (pathname == NULL || pathname[0] == '\0') {/* virtual root */ file->dircnt = 0; return (ret); } /* * Make a UTF-16BE basename if Joliet extension enabled. */ if (iso9660->opt.joliet) { const char *u16, *ulast; size_t u16len, ulen_last; if (iso9660->sconv_to_utf16be == NULL) { iso9660->sconv_to_utf16be = archive_string_conversion_to_charset( &(a->archive), "UTF-16BE", 1); if (iso9660->sconv_to_utf16be == NULL) /* Couldn't allocate memory */ return (ARCHIVE_FATAL); iso9660->sconv_from_utf16be = archive_string_conversion_from_charset( &(a->archive), "UTF-16BE", 1); if (iso9660->sconv_from_utf16be == NULL) /* Couldn't allocate memory */ return (ARCHIVE_FATAL); } /* * Converte a filename to UTF-16BE. */ if (0 > archive_entry_pathname_l(file->entry, &u16, &u16len, iso9660->sconv_to_utf16be)) { if (errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for UTF-16BE"); return (ARCHIVE_FATAL); } archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "A filename cannot be converted to UTF-16BE;" "You should disable making Joliet extension"); ret = ARCHIVE_WARN; } /* * Make sure a path separator is not in the last; * Remove trailing '/'. */ while (u16len >= 2) { #if defined(_WIN32) || defined(__CYGWIN__) if (u16[u16len-2] == 0 && (u16[u16len-1] == '/' || u16[u16len-1] == '\\')) #else if (u16[u16len-2] == 0 && u16[u16len-1] == '/') #endif { u16len -= 2; } else break; } /* * Find a basename in UTF-16BE. */ ulast = u16; u16len >>= 1; ulen_last = u16len; while (u16len > 0) { #if defined(_WIN32) || defined(__CYGWIN__) if (u16[0] == 0 && (u16[1] == '/' || u16[1] == '\\')) #else if (u16[0] == 0 && u16[1] == '/') #endif { ulast = u16 + 2; ulen_last = u16len -1; } u16 += 2; u16len --; } ulen_last <<= 1; if (archive_string_ensure(&(file->basename_utf16), ulen_last) == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory for UTF-16BE"); return (ARCHIVE_FATAL); } /* * Set UTF-16BE basename. */ memcpy(file->basename_utf16.s, ulast, ulen_last); file->basename_utf16.length = ulen_last; } archive_strcpy(&(file->parentdir), pathname); #if defined(_WIN32) || defined(__CYGWIN__) /* * Convert a path-separator from '\' to '/' */ if (cleanup_backslash_1(file->parentdir.s) != 0) { const wchar_t *wp = archive_entry_pathname_w(file->entry); struct archive_wstring ws; if (wp != NULL) { int r; archive_string_init(&ws); archive_wstrcpy(&ws, wp); cleanup_backslash_2(ws.s); archive_string_empty(&(file->parentdir)); r = archive_string_append_from_wcs(&(file->parentdir), ws.s, ws.length); archive_wstring_free(&ws); if (r < 0 && errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } } } #endif len = file->parentdir.length; p = dirname = file->parentdir.s; /* * Remove leading '/', '../' and './' elements */ while (*p) { if (p[0] == '/') { p++; len--; } else if (p[0] != '.') break; else if (p[1] == '.' && p[2] == '/') { p += 3; len -= 3; } else if (p[1] == '/' || (p[1] == '.' && p[2] == '\0')) { p += 2; len -= 2; } else if (p[1] == '\0') { p++; len--; } else break; } if (p != dirname) { memmove(dirname, p, len+1); p = dirname; } /* * Remove "/","/." and "/.." elements from tail. */ while (len > 0) { size_t ll = len; if (len > 0 && p[len-1] == '/') { p[len-1] = '\0'; len--; } if (len > 1 && p[len-2] == '/' && p[len-1] == '.') { p[len-2] = '\0'; len -= 2; } if (len > 2 && p[len-3] == '/' && p[len-2] == '.' && p[len-1] == '.') { p[len-3] = '\0'; len -= 3; } if (ll == len) break; } while (*p) { if (p[0] == '/') { if (p[1] == '/') /* Convert '//' --> '/' */ strcpy(p, p+1); else if (p[1] == '.' && p[2] == '/') /* Convert '/./' --> '/' */ strcpy(p, p+2); else if (p[1] == '.' && p[2] == '.' && p[3] == '/') { /* Convert 'dir/dir1/../dir2/' * --> 'dir/dir2/' */ char *rp = p -1; while (rp >= dirname) { if (*rp == '/') break; --rp; } if (rp > dirname) { strcpy(rp, p+3); p = rp; } else { strcpy(dirname, p+4); p = dirname; } } else p++; } else p++; } p = dirname; len = strlen(p); if (archive_entry_filetype(file->entry) == AE_IFLNK) { /* Convert symlink name too. */ pathname = archive_entry_symlink(file->entry); archive_strcpy(&(file->symlink), pathname); #if defined(_WIN32) || defined(__CYGWIN__) /* * Convert a path-separator from '\' to '/' */ if (archive_strlen(&(file->symlink)) > 0 && cleanup_backslash_1(file->symlink.s) != 0) { const wchar_t *wp = archive_entry_symlink_w(file->entry); struct archive_wstring ws; if (wp != NULL) { int r; archive_string_init(&ws); archive_wstrcpy(&ws, wp); cleanup_backslash_2(ws.s); archive_string_empty(&(file->symlink)); r = archive_string_append_from_wcs( &(file->symlink), ws.s, ws.length); archive_wstring_free(&ws); if (r < 0 && errno == ENOMEM) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } } } #endif } /* * - Count up directory elements. * - Find out the position which points the last position of * path separator('/'). */ slash = NULL; file->dircnt = 0; for (; *p != '\0'; p++) if (*p == '/') { slash = p; file->dircnt++; } if (slash == NULL) { /* The pathname doesn't have a parent directory. */ file->parentdir.length = len; archive_string_copy(&(file->basename), &(file->parentdir)); archive_string_empty(&(file->parentdir)); *file->parentdir.s = '\0'; return (ret); } /* Make a basename from dirname and slash */ *slash = '\0'; file->parentdir.length = slash - dirname; archive_strcpy(&(file->basename), slash + 1); if (archive_entry_filetype(file->entry) == AE_IFDIR) file->dircnt ++; return (ret); } /* * Register a entry to get a hardlink target. */ static int isofile_register_hardlink(struct archive_write *a, struct isofile *file) { struct iso9660 *iso9660 = a->format_data; struct hardlink *hl; const char *pathname; archive_entry_set_nlink(file->entry, 1); pathname = archive_entry_hardlink(file->entry); if (pathname == NULL) { /* This `file` is a hardlink target. */ hl = malloc(sizeof(*hl)); if (hl == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } hl->nlink = 1; /* A hardlink target must be the first position. */ file->hlnext = NULL; hl->file_list.first = file; hl->file_list.last = &(file->hlnext); __archive_rb_tree_insert_node(&(iso9660->hardlink_rbtree), (struct archive_rb_node *)hl); } else { hl = (struct hardlink *)__archive_rb_tree_find_node( &(iso9660->hardlink_rbtree), pathname); if (hl != NULL) { /* Insert `file` entry into the tail. */ file->hlnext = NULL; *hl->file_list.last = file; hl->file_list.last = &(file->hlnext); hl->nlink++; } archive_entry_unset_size(file->entry); } return (ARCHIVE_OK); } /* * Hardlinked files have to have the same location of extent. * We have to find out hardlink target entries for the entries * which have a hardlink target name. */ static void isofile_connect_hardlink_files(struct iso9660 *iso9660) { struct archive_rb_node *n; struct hardlink *hl; struct isofile *target, *nf; ARCHIVE_RB_TREE_FOREACH(n, &(iso9660->hardlink_rbtree)) { hl = (struct hardlink *)n; /* The first entry must be a hardlink target. */ target = hl->file_list.first; archive_entry_set_nlink(target->entry, hl->nlink); /* Set a hardlink target to reference entries. */ for (nf = target->hlnext; nf != NULL; nf = nf->hlnext) { nf->hardlink_target = target; archive_entry_set_nlink(nf->entry, hl->nlink); } } } static int isofile_hd_cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct hardlink *h1 = (const struct hardlink *)n1; const struct hardlink *h2 = (const struct hardlink *)n2; return (strcmp(archive_entry_pathname(h1->file_list.first->entry), archive_entry_pathname(h2->file_list.first->entry))); } static int isofile_hd_cmp_key(const struct archive_rb_node *n, const void *key) { const struct hardlink *h = (const struct hardlink *)n; return (strcmp(archive_entry_pathname(h->file_list.first->entry), (const char *)key)); } static void isofile_init_hardlinks(struct iso9660 *iso9660) { static const struct archive_rb_tree_ops rb_ops = { isofile_hd_cmp_node, isofile_hd_cmp_key, }; __archive_rb_tree_init(&(iso9660->hardlink_rbtree), &rb_ops); } static void isofile_free_hardlinks(struct iso9660 *iso9660) { struct archive_rb_node *n, *next; for (n = ARCHIVE_RB_TREE_MIN(&(iso9660->hardlink_rbtree)); n;) { next = __archive_rb_tree_iterate(&(iso9660->hardlink_rbtree), n, ARCHIVE_RB_DIR_RIGHT); free(n); n = next; } } static struct isoent * isoent_new(struct isofile *file) { struct isoent *isoent; static const struct archive_rb_tree_ops rb_ops = { isoent_cmp_node, isoent_cmp_key, }; isoent = calloc(1, sizeof(*isoent)); if (isoent == NULL) return (NULL); isoent->file = file; isoent->children.first = NULL; isoent->children.last = &(isoent->children.first); __archive_rb_tree_init(&(isoent->rbtree), &rb_ops); isoent->subdirs.first = NULL; isoent->subdirs.last = &(isoent->subdirs.first); isoent->extr_rec_list.first = NULL; isoent->extr_rec_list.last = &(isoent->extr_rec_list.first); isoent->extr_rec_list.current = NULL; if (archive_entry_filetype(file->entry) == AE_IFDIR) isoent->dir = 1; return (isoent); } static inline struct isoent * isoent_clone(struct isoent *src) { return (isoent_new(src->file)); } static void _isoent_free(struct isoent *isoent) { struct extr_rec *er, *er_next; free(isoent->children_sorted); free(isoent->identifier); er = isoent->extr_rec_list.first; while (er != NULL) { er_next = er->next; free(er); er = er_next; } free(isoent); } static void isoent_free_all(struct isoent *isoent) { struct isoent *np, *np_temp; if (isoent == NULL) return; np = isoent; for (;;) { if (np->dir) { if (np->children.first != NULL) { /* Enter to sub directories. */ np = np->children.first; continue; } } for (;;) { np_temp = np; if (np->chnext == NULL) { /* Return to the parent directory. */ np = np->parent; _isoent_free(np_temp); if (np == np_temp) return; } else { np = np->chnext; _isoent_free(np_temp); break; } } } } static struct isoent * isoent_create_virtual_dir(struct archive_write *a, struct iso9660 *iso9660, const char *pathname) { struct isofile *file; struct isoent *isoent; file = isofile_new(a, NULL); if (file == NULL) return (NULL); archive_entry_set_pathname(file->entry, pathname); archive_entry_unset_mtime(file->entry); archive_entry_unset_atime(file->entry); archive_entry_unset_ctime(file->entry); archive_entry_set_uid(file->entry, getuid()); archive_entry_set_gid(file->entry, getgid()); archive_entry_set_mode(file->entry, 0555 | AE_IFDIR); archive_entry_set_nlink(file->entry, 2); if (isofile_gen_utility_names(a, file) < ARCHIVE_WARN) { isofile_free(file); return (NULL); } isofile_add_entry(iso9660, file); isoent = isoent_new(file); if (isoent == NULL) return (NULL); isoent->dir = 1; isoent->virtual = 1; return (isoent); } static int isoent_cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct isoent *e1 = (const struct isoent *)n1; const struct isoent *e2 = (const struct isoent *)n2; return (strcmp(e1->file->basename.s, e2->file->basename.s)); } static int isoent_cmp_key(const struct archive_rb_node *n, const void *key) { const struct isoent *e = (const struct isoent *)n; return (strcmp(e->file->basename.s, (const char *)key)); } static int isoent_add_child_head(struct isoent *parent, struct isoent *child) { if (!__archive_rb_tree_insert_node( &(parent->rbtree), (struct archive_rb_node *)child)) return (0); if ((child->chnext = parent->children.first) == NULL) parent->children.last = &(child->chnext); parent->children.first = child; parent->children.cnt++; child->parent = parent; /* Add a child to a sub-directory chain */ if (child->dir) { if ((child->drnext = parent->subdirs.first) == NULL) parent->subdirs.last = &(child->drnext); parent->subdirs.first = child; parent->subdirs.cnt++; child->parent = parent; } else child->drnext = NULL; return (1); } static int isoent_add_child_tail(struct isoent *parent, struct isoent *child) { if (!__archive_rb_tree_insert_node( &(parent->rbtree), (struct archive_rb_node *)child)) return (0); child->chnext = NULL; *parent->children.last = child; parent->children.last = &(child->chnext); parent->children.cnt++; child->parent = parent; /* Add a child to a sub-directory chain */ child->drnext = NULL; if (child->dir) { *parent->subdirs.last = child; parent->subdirs.last = &(child->drnext); parent->subdirs.cnt++; child->parent = parent; } return (1); } static void isoent_remove_child(struct isoent *parent, struct isoent *child) { struct isoent *ent; /* Remove a child entry from children chain. */ ent = parent->children.first; while (ent->chnext != child) ent = ent->chnext; if ((ent->chnext = ent->chnext->chnext) == NULL) parent->children.last = &(ent->chnext); parent->children.cnt--; if (child->dir) { /* Remove a child entry from sub-directory chain. */ ent = parent->subdirs.first; while (ent->drnext != child) ent = ent->drnext; if ((ent->drnext = ent->drnext->drnext) == NULL) parent->subdirs.last = &(ent->drnext); parent->subdirs.cnt--; } __archive_rb_tree_remove_node(&(parent->rbtree), (struct archive_rb_node *)child); } static int isoent_clone_tree(struct archive_write *a, struct isoent **nroot, struct isoent *root) { struct isoent *np, *xroot, *newent; np = root; xroot = NULL; do { newent = isoent_clone(np); if (newent == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } if (xroot == NULL) { *nroot = xroot = newent; newent->parent = xroot; } else isoent_add_child_tail(xroot, newent); if (np->dir && np->children.first != NULL) { /* Enter to sub directories. */ np = np->children.first; xroot = newent; continue; } while (np != np->parent) { if (np->chnext == NULL) { /* Return to the parent directory. */ np = np->parent; xroot = xroot->parent; } else { np = np->chnext; break; } } } while (np != np->parent); return (ARCHIVE_OK); } /* * Setup directory locations. */ static void isoent_setup_directory_location(struct iso9660 *iso9660, int location, struct vdd *vdd) { struct isoent *np; int depth; vdd->total_dir_block = 0; depth = 0; np = vdd->rootent; do { int block; np->dir_block = calculate_directory_descriptors( iso9660, vdd, np, depth); vdd->total_dir_block += np->dir_block; np->dir_location = location; location += np->dir_block; block = extra_setup_location(np, location); vdd->total_dir_block += block; location += block; if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } while (np != np->parent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != np->parent); } static void _isoent_file_location(struct iso9660 *iso9660, struct isoent *isoent, int *symlocation) { struct isoent **children; int n; if (isoent->children.cnt == 0) return; children = isoent->children_sorted; for (n = 0; n < isoent->children.cnt; n++) { struct isoent *np; struct isofile *file; np = children[n]; if (np->dir) continue; if (np == iso9660->el_torito.boot) continue; file = np->file; if (file->boot || file->hardlink_target != NULL) continue; if (archive_entry_filetype(file->entry) == AE_IFLNK || file->content.size == 0) { /* * Do not point a valid location. * Make sure entry is not hardlink file. */ file->content.location = (*symlocation)--; continue; } file->write_content = 1; } } /* * Setup file locations. */ static void isoent_setup_file_location(struct iso9660 *iso9660, int location) { struct isoent *isoent; struct isoent *np; struct isofile *file; size_t size; int block; int depth; int joliet; int symlocation; int total_block; iso9660->total_file_block = 0; if ((isoent = iso9660->el_torito.catalog) != NULL) { isoent->file->content.location = location; block = (int)((archive_entry_size(isoent->file->entry) + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS); location += block; iso9660->total_file_block += block; } if ((isoent = iso9660->el_torito.boot) != NULL) { isoent->file->content.location = location; size = fd_boot_image_size(iso9660->el_torito.media_type); if (size == 0) size = (size_t)archive_entry_size(isoent->file->entry); block = ((int)size + LOGICAL_BLOCK_SIZE -1) >> LOGICAL_BLOCK_BITS; location += block; iso9660->total_file_block += block; isoent->file->content.blocks = block; } depth = 0; symlocation = -16; if (!iso9660->opt.rr && iso9660->opt.joliet) { joliet = 1; np = iso9660->joliet.rootent; } else { joliet = 0; np = iso9660->primary.rootent; } do { _isoent_file_location(iso9660, np, &symlocation); if (np->subdirs.first != NULL && (joliet || ((iso9660->opt.rr == OPT_RR_DISABLED && depth + 2 < iso9660->primary.max_depth) || (iso9660->opt.rr && depth + 1 < iso9660->primary.max_depth)))) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } while (np != np->parent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != np->parent); total_block = 0; for (file = iso9660->data_file_list.first; file != NULL; file = file->datanext) { if (!file->write_content) continue; file->cur_content = &(file->content); do { file->cur_content->location = location; location += file->cur_content->blocks; total_block += file->cur_content->blocks; /* Next fragument */ file->cur_content = file->cur_content->next; } while (file->cur_content != NULL); } iso9660->total_file_block += total_block; } static int get_path_component(char *name, size_t n, const char *fn) { char *p; size_t l; p = strchr(fn, '/'); if (p == NULL) { if ((l = strlen(fn)) == 0) return (0); } else l = p - fn; if (l > n -1) return (-1); memcpy(name, fn, l); name[l] = '\0'; return ((int)l); } /* * Add a new entry into the tree. */ static int isoent_tree(struct archive_write *a, struct isoent **isoentpp) { #if defined(_WIN32) && !defined(__CYGWIN__) char name[_MAX_FNAME];/* Included null terminator size. */ #elif defined(NAME_MAX) && NAME_MAX >= 255 char name[NAME_MAX+1]; #else char name[256]; #endif struct iso9660 *iso9660 = a->format_data; struct isoent *dent, *isoent, *np; struct isofile *f1, *f2; const char *fn, *p; int l; isoent = *isoentpp; dent = iso9660->primary.rootent; if (isoent->file->parentdir.length > 0) fn = p = isoent->file->parentdir.s; else fn = p = ""; /* * If the path of the parent directory of `isoent' entry is * the same as the path of `cur_dirent', add isoent to * `cur_dirent'. */ if (archive_strlen(&(iso9660->cur_dirstr)) == archive_strlen(&(isoent->file->parentdir)) && strcmp(iso9660->cur_dirstr.s, fn) == 0) { if (!isoent_add_child_tail(iso9660->cur_dirent, isoent)) { np = (struct isoent *)__archive_rb_tree_find_node( &(iso9660->cur_dirent->rbtree), isoent->file->basename.s); goto same_entry; } return (ARCHIVE_OK); } for (;;) { l = get_path_component(name, sizeof(name), fn); if (l == 0) { np = NULL; break; } if (l < 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "A name buffer is too small"); _isoent_free(isoent); return (ARCHIVE_FATAL); } np = isoent_find_child(dent, name); if (np == NULL || fn[0] == '\0') break; /* Find next subdirectory. */ if (!np->dir) { /* NOT Directory! */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "`%s' is not directory, we cannot insert `%s' ", archive_entry_pathname(np->file->entry), archive_entry_pathname(isoent->file->entry)); _isoent_free(isoent); *isoentpp = NULL; return (ARCHIVE_FAILED); } fn += l; if (fn[0] == '/') fn++; dent = np; } if (np == NULL) { /* * Create virtual parent directories. */ while (fn[0] != '\0') { struct isoent *vp; struct archive_string as; archive_string_init(&as); archive_strncat(&as, p, fn - p + l); if (as.s[as.length-1] == '/') { as.s[as.length-1] = '\0'; as.length--; } vp = isoent_create_virtual_dir(a, iso9660, as.s); if (vp == NULL) { archive_string_free(&as); archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); _isoent_free(isoent); *isoentpp = NULL; return (ARCHIVE_FATAL); } archive_string_free(&as); if (vp->file->dircnt > iso9660->dircnt_max) iso9660->dircnt_max = vp->file->dircnt; isoent_add_child_tail(dent, vp); np = vp; fn += l; if (fn[0] == '/') fn++; l = get_path_component(name, sizeof(name), fn); if (l < 0) { archive_string_free(&as); archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "A name buffer is too small"); _isoent_free(isoent); *isoentpp = NULL; return (ARCHIVE_FATAL); } dent = np; } /* Found out the parent directory where isoent can be * inserted. */ iso9660->cur_dirent = dent; archive_string_empty(&(iso9660->cur_dirstr)); archive_string_ensure(&(iso9660->cur_dirstr), archive_strlen(&(dent->file->parentdir)) + archive_strlen(&(dent->file->basename)) + 2); if (archive_strlen(&(dent->file->parentdir)) + archive_strlen(&(dent->file->basename)) == 0) iso9660->cur_dirstr.s[0] = 0; else { if (archive_strlen(&(dent->file->parentdir)) > 0) { archive_string_copy(&(iso9660->cur_dirstr), &(dent->file->parentdir)); archive_strappend_char(&(iso9660->cur_dirstr), '/'); } archive_string_concat(&(iso9660->cur_dirstr), &(dent->file->basename)); } if (!isoent_add_child_tail(dent, isoent)) { np = (struct isoent *)__archive_rb_tree_find_node( &(dent->rbtree), isoent->file->basename.s); goto same_entry; } return (ARCHIVE_OK); } same_entry: /* * We have already has the entry the filename of which is * the same. */ f1 = np->file; f2 = isoent->file; /* If the file type of entries is different, * we cannot handle it. */ if (archive_entry_filetype(f1->entry) != archive_entry_filetype(f2->entry)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Found duplicate entries `%s' and its file type is " "different", archive_entry_pathname(f1->entry)); _isoent_free(isoent); *isoentpp = NULL; return (ARCHIVE_FAILED); } /* Swap file entries. */ np->file = f2; isoent->file = f1; np->virtual = 0; _isoent_free(isoent); *isoentpp = np; return (ARCHIVE_OK); } /* * Find a entry from `isoent' */ static struct isoent * isoent_find_child(struct isoent *isoent, const char *child_name) { struct isoent *np; np = (struct isoent *)__archive_rb_tree_find_node( &(isoent->rbtree), child_name); return (np); } /* * Find a entry full-path of which is specified by `fn' parameter, * in the tree. */ static struct isoent * isoent_find_entry(struct isoent *rootent, const char *fn) { #if defined(_WIN32) && !defined(__CYGWIN__) char name[_MAX_FNAME];/* Included null terminator size. */ #elif defined(NAME_MAX) && NAME_MAX >= 255 char name[NAME_MAX+1]; #else char name[256]; #endif struct isoent *isoent, *np; int l; isoent = rootent; np = NULL; for (;;) { l = get_path_component(name, sizeof(name), fn); if (l == 0) break; fn += l; if (fn[0] == '/') fn++; np = isoent_find_child(isoent, name); if (np == NULL) break; if (fn[0] == '\0') break;/* We found out the entry */ /* Try sub directory. */ isoent = np; np = NULL; if (!isoent->dir) break;/* Not directory */ } return (np); } /* * Following idr_* functions are used for resolving duplicated filenames * and unreceivable filenames to generate ISO9660/Joliet Identifiers. */ static void idr_relaxed_filenames(char *map) { int i; for (i = 0x21; i <= 0x2F; i++) map[i] = 1; for (i = 0x3A; i <= 0x41; i++) map[i] = 1; for (i = 0x5B; i <= 0x5E; i++) map[i] = 1; map[0x60] = 1; for (i = 0x7B; i <= 0x7E; i++) map[i] = 1; } static void idr_init(struct iso9660 *iso9660, struct vdd *vdd, struct idr *idr) { idr->idrent_pool = NULL; idr->pool_size = 0; if (vdd->vdd_type != VDD_JOLIET) { if (iso9660->opt.iso_level <= 3) { memcpy(idr->char_map, d_characters_map, sizeof(idr->char_map)); } else { memcpy(idr->char_map, d1_characters_map, sizeof(idr->char_map)); idr_relaxed_filenames(idr->char_map); } } } static void idr_cleanup(struct idr *idr) { free(idr->idrent_pool); } static int idr_ensure_poolsize(struct archive_write *a, struct idr *idr, int cnt) { if (idr->pool_size < cnt) { void *p; const int bk = (1 << 7) - 1; int psize; psize = (cnt + bk) & ~bk; p = realloc(idr->idrent_pool, sizeof(struct idrent) * psize); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } idr->idrent_pool = (struct idrent *)p; idr->pool_size = psize; } return (ARCHIVE_OK); } static int idr_start(struct archive_write *a, struct idr *idr, int cnt, int ffmax, int num_size, int null_size, const struct archive_rb_tree_ops *rbt_ops) { int r; (void)ffmax; /* UNUSED */ r = idr_ensure_poolsize(a, idr, cnt); if (r != ARCHIVE_OK) return (r); __archive_rb_tree_init(&(idr->rbtree), rbt_ops); idr->wait_list.first = NULL; idr->wait_list.last = &(idr->wait_list.first); idr->pool_idx = 0; idr->num_size = num_size; idr->null_size = null_size; return (ARCHIVE_OK); } static void idr_register(struct idr *idr, struct isoent *isoent, int weight, int noff) { struct idrent *idrent, *n; idrent = &(idr->idrent_pool[idr->pool_idx++]); idrent->wnext = idrent->avail = NULL; idrent->isoent = isoent; idrent->weight = weight; idrent->noff = noff; idrent->rename_num = 0; if (!__archive_rb_tree_insert_node(&(idr->rbtree), &(idrent->rbnode))) { n = (struct idrent *)__archive_rb_tree_find_node( &(idr->rbtree), idrent->isoent); if (n != NULL) { /* this `idrent' needs to rename. */ idrent->avail = n; *idr->wait_list.last = idrent; idr->wait_list.last = &(idrent->wnext); } } } static void idr_extend_identifier(struct idrent *wnp, int numsize, int nullsize) { unsigned char *p; int wnp_ext_off; wnp_ext_off = wnp->isoent->ext_off; if (wnp->noff + numsize != wnp_ext_off) { p = (unsigned char *)wnp->isoent->identifier; /* Extend the filename; foo.c --> foo___.c */ memmove(p + wnp->noff + numsize, p + wnp_ext_off, wnp->isoent->ext_len + nullsize); wnp->isoent->ext_off = wnp_ext_off = wnp->noff + numsize; wnp->isoent->id_len = wnp_ext_off + wnp->isoent->ext_len; } } static void idr_resolve(struct idr *idr, void (*fsetnum)(unsigned char *p, int num)) { struct idrent *n; unsigned char *p; for (n = idr->wait_list.first; n != NULL; n = n->wnext) { idr_extend_identifier(n, idr->num_size, idr->null_size); p = (unsigned char *)n->isoent->identifier + n->noff; do { fsetnum(p, n->avail->rename_num++); } while (!__archive_rb_tree_insert_node( &(idr->rbtree), &(n->rbnode))); } } static void idr_set_num(unsigned char *p, int num) { static const char xdig[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; num %= sizeof(xdig) * sizeof(xdig) * sizeof(xdig); p[0] = xdig[(num / (sizeof(xdig) * sizeof(xdig)))]; num %= sizeof(xdig) * sizeof(xdig); p[1] = xdig[ (num / sizeof(xdig))]; num %= sizeof(xdig); p[2] = xdig[num]; } static void idr_set_num_beutf16(unsigned char *p, int num) { static const uint16_t xdig[] = { 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, 0x0038, 0x0039, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, 0x0058, 0x0059, 0x005A }; #define XDIG_CNT (sizeof(xdig)/sizeof(xdig[0])) num %= XDIG_CNT * XDIG_CNT * XDIG_CNT; archive_be16enc(p, xdig[(num / (XDIG_CNT * XDIG_CNT))]); num %= XDIG_CNT * XDIG_CNT; archive_be16enc(p+2, xdig[ (num / XDIG_CNT)]); num %= XDIG_CNT; archive_be16enc(p+4, xdig[num]); } /* * Generate ISO9660 Identifier. */ static int isoent_gen_iso9660_identifier(struct archive_write *a, struct isoent *isoent, struct idr *idr) { struct iso9660 *iso9660; struct isoent *np; char *p; int l, r; const char *char_map; char allow_ldots, allow_multidot, allow_period, allow_vernum; int fnmax, ffmax, dnmax; static const struct archive_rb_tree_ops rb_ops = { isoent_cmp_node_iso9660, isoent_cmp_key_iso9660 }; if (isoent->children.cnt == 0) return (0); iso9660 = a->format_data; char_map = idr->char_map; if (iso9660->opt.iso_level <= 3) { allow_ldots = 0; allow_multidot = 0; allow_period = 1; allow_vernum = iso9660->opt.allow_vernum; if (iso9660->opt.iso_level == 1) { fnmax = 8; ffmax = 12;/* fnmax + '.' + 3 */ dnmax = 8; } else { fnmax = 30; ffmax = 31; dnmax = 31; } } else { allow_ldots = allow_multidot = 1; allow_period = allow_vernum = 0; if (iso9660->opt.rr) /* * MDR : The maximum size of Directory Record(254). * DRL : A Directory Record Length(33). * CE : A size of SUSP CE System Use Entry(28). * MDR - DRL - CE = 254 - 33 - 28 = 193. */ fnmax = ffmax = dnmax = 193; else /* * XA : CD-ROM XA System Use Extension * Information(14). * MDR - DRL - XA = 254 - 33 -14 = 207. */ fnmax = ffmax = dnmax = 207; } r = idr_start(a, idr, isoent->children.cnt, ffmax, 3, 1, &rb_ops); if (r < 0) return (r); for (np = isoent->children.first; np != NULL; np = np->chnext) { char *dot, *xdot; int ext_off, noff, weight; l = (int)np->file->basename.length; p = malloc(l+31+2+1); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } memcpy(p, np->file->basename.s, l); p[l] = '\0'; np->identifier = p; dot = xdot = NULL; if (!allow_ldots) { /* * If there is a '.' character at the first byte, * it has to be replaced by '_' character. */ if (*p == '.') *p++ = '_'; } for (;*p; p++) { if (*p & 0x80) { *p = '_'; continue; } if (char_map[(unsigned char)*p]) { /* if iso-level is '4', a character '.' is * allowed by char_map. */ if (*p == '.') { xdot = dot; dot = p; } continue; } if (*p >= 'a' && *p <= 'z') { *p -= 'a' - 'A'; continue; } if (*p == '.') { xdot = dot; dot = p; if (allow_multidot) continue; } *p = '_'; } p = np->identifier; weight = -1; if (dot == NULL) { int nammax; if (np->dir) nammax = dnmax; else nammax = fnmax; if (l > nammax) { p[nammax] = '\0'; weight = nammax; ext_off = nammax; } else ext_off = l; } else { *dot = '.'; ext_off = (int)(dot - p); if (iso9660->opt.iso_level == 1) { if (dot - p <= 8) { if (strlen(dot) > 4) { /* A length of a file extension * must be less than 4 */ dot[4] = '\0'; weight = 0; } } else { p[8] = dot[0]; p[9] = dot[1]; p[10] = dot[2]; p[11] = dot[3]; p[12] = '\0'; weight = 8; ext_off = 8; } } else if (np->dir) { if (l > dnmax) { p[dnmax] = '\0'; weight = dnmax; if (ext_off > dnmax) ext_off = dnmax; } } else if (l > ffmax) { int extlen = (int)strlen(dot); int xdoff; if (xdot != NULL) xdoff = (int)(xdot - p); else xdoff = 0; if (extlen > 1 && xdoff < fnmax-1) { int off; if (extlen > ffmax) extlen = ffmax; off = ffmax - extlen; if (off == 0) { /* A dot('.') character * does't place to the first * byte of identifier. */ off ++; extlen --; } memmove(p+off, dot, extlen); p[ffmax] = '\0'; ext_off = off; weight = off; #ifdef COMPAT_MKISOFS } else if (xdoff >= fnmax-1) { /* Simulate a bug(?) of mkisofs. */ p[fnmax-1] = '\0'; ext_off = fnmax-1; weight = fnmax-1; #endif } else { p[fnmax] = '\0'; ext_off = fnmax; weight = fnmax; } } } /* Save an offset of a file name extension to sort files. */ np->ext_off = ext_off; np->ext_len = (int)strlen(&p[ext_off]); np->id_len = l = ext_off + np->ext_len; /* Make an offset of the number which is used to be set * hexadecimal number to avoid duplicate identififier. */ if (iso9660->opt.iso_level == 1) { if (ext_off >= 5) noff = 5; else noff = ext_off; } else { if (l == ffmax) noff = ext_off - 3; else if (l == ffmax-1) noff = ext_off - 2; else if (l == ffmax-2) noff = ext_off - 1; else noff = ext_off; } /* Register entry to the identifier resolver. */ idr_register(idr, np, weight, noff); } /* Resolve duplicate identifier. */ idr_resolve(idr, idr_set_num); /* Add a period and a version number to identifiers. */ for (np = isoent->children.first; np != NULL; np = np->chnext) { if (!np->dir && np->rr_child == NULL) { p = np->identifier + np->ext_off + np->ext_len; if (np->ext_len == 0 && allow_period) { *p++ = '.'; np->ext_len = 1; } if (np->ext_len == 1 && !allow_period) { *--p = '\0'; np->ext_len = 0; } np->id_len = np->ext_off + np->ext_len; if (allow_vernum) { *p++ = ';'; *p++ = '1'; np->id_len += 2; } *p = '\0'; } else np->id_len = np->ext_off + np->ext_len; np->mb_len = np->id_len; } return (ARCHIVE_OK); } /* * Generate Joliet Identifier. */ static int isoent_gen_joliet_identifier(struct archive_write *a, struct isoent *isoent, struct idr *idr) { struct iso9660 *iso9660; struct isoent *np; unsigned char *p; size_t l; int r; size_t ffmax, parent_len; static const struct archive_rb_tree_ops rb_ops = { isoent_cmp_node_joliet, isoent_cmp_key_joliet }; if (isoent->children.cnt == 0) return (0); iso9660 = a->format_data; if (iso9660->opt.joliet == OPT_JOLIET_LONGNAME) ffmax = 206; else ffmax = 128; r = idr_start(a, idr, isoent->children.cnt, (int)ffmax, 6, 2, &rb_ops); if (r < 0) return (r); parent_len = 1; for (np = isoent; np->parent != np; np = np->parent) parent_len += np->mb_len + 1; for (np = isoent->children.first; np != NULL; np = np->chnext) { unsigned char *dot; int ext_off, noff, weight; size_t lt; if ((l = np->file->basename_utf16.length) > ffmax) l = ffmax; p = malloc((l+1)*2); if (p == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } memcpy(p, np->file->basename_utf16.s, l); p[l] = 0; p[l+1] = 0; np->identifier = (char *)p; lt = l; dot = p + l; weight = 0; while (lt > 0) { if (!joliet_allowed_char(p[0], p[1])) archive_be16enc(p, 0x005F); /* '_' */ else if (p[0] == 0 && p[1] == 0x2E) /* '.' */ dot = p; p += 2; lt -= 2; } ext_off = (int)(dot - (unsigned char *)np->identifier); np->ext_off = ext_off; np->ext_len = (int)l - ext_off; np->id_len = (int)l; /* * Get a length of MBS of a full-pathname. */ if (np->file->basename_utf16.length > ffmax) { if (archive_strncpy_l(&iso9660->mbs, (const char *)np->identifier, l, iso9660->sconv_from_utf16be) != 0 && errno == ENOMEM) { archive_set_error(&a->archive, errno, "No memory"); return (ARCHIVE_FATAL); } np->mb_len = (int)iso9660->mbs.length; if (np->mb_len != (int)np->file->basename.length) weight = np->mb_len; } else np->mb_len = (int)np->file->basename.length; /* If a length of full-pathname is longer than 240 bytes, * it violates Joliet extensions regulation. */ if (parent_len > 240 || np->mb_len > 240 || parent_len + np->mb_len > 240) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "The regulation of Joliet extensions;" " A length of a full-pathname of `%s' is " "longer than 240 bytes, (p=%d, b=%d)", archive_entry_pathname(np->file->entry), (int)parent_len, (int)np->mb_len); return (ARCHIVE_FATAL); } /* Make an offset of the number which is used to be set * hexadecimal number to avoid duplicate identifier. */ if (l == ffmax) noff = ext_off - 6; else if (l == ffmax-2) noff = ext_off - 4; else if (l == ffmax-4) noff = ext_off - 2; else noff = ext_off; /* Register entry to the identifier resolver. */ idr_register(idr, np, weight, noff); } /* Resolve duplicate identifier with Joliet Volume. */ idr_resolve(idr, idr_set_num_beutf16); return (ARCHIVE_OK); } /* * This comparing rule is according to ISO9660 Standard 9.3 */ static int isoent_cmp_iso9660_identifier(const struct isoent *p1, const struct isoent *p2) { const char *s1, *s2; int cmp; int l; s1 = p1->identifier; s2 = p2->identifier; /* Compare File Name */ l = p1->ext_off; if (l > p2->ext_off) l = p2->ext_off; cmp = memcmp(s1, s2, l); if (cmp != 0) return (cmp); if (p1->ext_off < p2->ext_off) { s2 += l; l = p2->ext_off - p1->ext_off; while (l--) if (0x20 != *s2++) return (0x20 - *(const unsigned char *)(s2 - 1)); } else if (p1->ext_off > p2->ext_off) { s1 += l; l = p1->ext_off - p2->ext_off; while (l--) if (0x20 != *s1++) return (*(const unsigned char *)(s1 - 1) - 0x20); } /* Compare File Name Extension */ if (p1->ext_len == 0 && p2->ext_len == 0) return (0); if (p1->ext_len == 1 && p2->ext_len == 1) return (0); if (p1->ext_len <= 1) return (-1); if (p2->ext_len <= 1) return (1); l = p1->ext_len; if (l > p2->ext_len) l = p2->ext_len; s1 = p1->identifier + p1->ext_off; s2 = p2->identifier + p2->ext_off; if (l > 1) { cmp = memcmp(s1, s2, l); if (cmp != 0) return (cmp); } if (p1->ext_len < p2->ext_len) { s2 += l; l = p2->ext_len - p1->ext_len; while (l--) if (0x20 != *s2++) return (0x20 - *(const unsigned char *)(s2 - 1)); } else if (p1->ext_len > p2->ext_len) { s1 += l; l = p1->ext_len - p2->ext_len; while (l--) if (0x20 != *s1++) return (*(const unsigned char *)(s1 - 1) - 0x20); } /* Compare File Version Number */ /* No operation. The File Version Number is always one. */ return (cmp); } static int isoent_cmp_node_iso9660(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct idrent *e1 = (const struct idrent *)n1; const struct idrent *e2 = (const struct idrent *)n2; return (isoent_cmp_iso9660_identifier(e2->isoent, e1->isoent)); } static int isoent_cmp_key_iso9660(const struct archive_rb_node *node, const void *key) { const struct isoent *isoent = (const struct isoent *)key; const struct idrent *idrent = (const struct idrent *)node; return (isoent_cmp_iso9660_identifier(isoent, idrent->isoent)); } static int isoent_cmp_joliet_identifier(const struct isoent *p1, const struct isoent *p2) { const unsigned char *s1, *s2; int cmp; int l; s1 = (const unsigned char *)p1->identifier; s2 = (const unsigned char *)p2->identifier; /* Compare File Name */ l = p1->ext_off; if (l > p2->ext_off) l = p2->ext_off; cmp = memcmp(s1, s2, l); if (cmp != 0) return (cmp); if (p1->ext_off < p2->ext_off) { s2 += l; l = p2->ext_off - p1->ext_off; while (l--) if (0 != *s2++) return (- *(const unsigned char *)(s2 - 1)); } else if (p1->ext_off > p2->ext_off) { s1 += l; l = p1->ext_off - p2->ext_off; while (l--) if (0 != *s1++) return (*(const unsigned char *)(s1 - 1)); } /* Compare File Name Extension */ if (p1->ext_len == 0 && p2->ext_len == 0) return (0); if (p1->ext_len == 2 && p2->ext_len == 2) return (0); if (p1->ext_len <= 2) return (-1); if (p2->ext_len <= 2) return (1); l = p1->ext_len; if (l > p2->ext_len) l = p2->ext_len; s1 = (unsigned char *)(p1->identifier + p1->ext_off); s2 = (unsigned char *)(p2->identifier + p2->ext_off); if (l > 1) { cmp = memcmp(s1, s2, l); if (cmp != 0) return (cmp); } if (p1->ext_len < p2->ext_len) { s2 += l; l = p2->ext_len - p1->ext_len; while (l--) if (0 != *s2++) return (- *(const unsigned char *)(s2 - 1)); } else if (p1->ext_len > p2->ext_len) { s1 += l; l = p1->ext_len - p2->ext_len; while (l--) if (0 != *s1++) return (*(const unsigned char *)(s1 - 1)); } /* Compare File Version Number */ /* No operation. The File Version Number is always one. */ return (cmp); } static int isoent_cmp_node_joliet(const struct archive_rb_node *n1, const struct archive_rb_node *n2) { const struct idrent *e1 = (const struct idrent *)n1; const struct idrent *e2 = (const struct idrent *)n2; return (isoent_cmp_joliet_identifier(e2->isoent, e1->isoent)); } static int isoent_cmp_key_joliet(const struct archive_rb_node *node, const void *key) { const struct isoent *isoent = (const struct isoent *)key; const struct idrent *idrent = (const struct idrent *)node; return (isoent_cmp_joliet_identifier(isoent, idrent->isoent)); } static int isoent_make_sorted_files(struct archive_write *a, struct isoent *isoent, struct idr *idr) { struct archive_rb_node *rn; struct isoent **children; children = malloc(isoent->children.cnt * sizeof(struct isoent *)); if (children == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } isoent->children_sorted = children; ARCHIVE_RB_TREE_FOREACH(rn, &(idr->rbtree)) { struct idrent *idrent = (struct idrent *)rn; *children ++ = idrent->isoent; } return (ARCHIVE_OK); } /* * - Generate ISO9660 and Joliet identifiers from basenames. * - Sort files by each directory. */ static int isoent_traverse_tree(struct archive_write *a, struct vdd* vdd) { struct iso9660 *iso9660 = a->format_data; struct isoent *np; struct idr idr; int depth; int r; int (*genid)(struct archive_write *, struct isoent *, struct idr *); idr_init(iso9660, vdd, &idr); np = vdd->rootent; depth = 0; if (vdd->vdd_type == VDD_JOLIET) genid = isoent_gen_joliet_identifier; else genid = isoent_gen_iso9660_identifier; do { if (np->virtual && !archive_entry_mtime_is_set(np->file->entry)) { /* Set properly times to virtual directory */ archive_entry_set_mtime(np->file->entry, iso9660->birth_time, 0); archive_entry_set_atime(np->file->entry, iso9660->birth_time, 0); archive_entry_set_ctime(np->file->entry, iso9660->birth_time, 0); } if (np->children.first != NULL) { if (vdd->vdd_type != VDD_JOLIET && !iso9660->opt.rr && depth + 1 >= vdd->max_depth) { if (np->children.cnt > 0) iso9660->directories_too_deep = np; } else { /* Generate Identifier */ r = genid(a, np, &idr); if (r < 0) goto exit_traverse_tree; r = isoent_make_sorted_files(a, np, &idr); if (r < 0) goto exit_traverse_tree; if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } } } while (np != np->parent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != np->parent); r = ARCHIVE_OK; exit_traverse_tree: idr_cleanup(&idr); return (r); } /* * Collect directory entries into path_table by a directory depth. */ static int isoent_collect_dirs(struct vdd *vdd, struct isoent *rootent, int depth) { struct isoent *np; if (rootent == NULL) rootent = vdd->rootent; np = rootent; do { /* Register current directory to pathtable. */ path_table_add_entry(&(vdd->pathtbl[depth]), np); if (np->subdirs.first != NULL && depth + 1 < vdd->max_depth) { /* Enter to sub directories. */ np = np->subdirs.first; depth++; continue; } while (np != rootent) { if (np->drnext == NULL) { /* Return to the parent directory. */ np = np->parent; depth--; } else { np = np->drnext; break; } } } while (np != rootent); return (ARCHIVE_OK); } /* * The entry whose number of levels in a directory hierarchy is * large than eight relocate to rr_move directory. */ static int isoent_rr_move_dir(struct archive_write *a, struct isoent **rr_moved, struct isoent *curent, struct isoent **newent) { struct iso9660 *iso9660 = a->format_data; struct isoent *rrmoved, *mvent, *np; if ((rrmoved = *rr_moved) == NULL) { struct isoent *rootent = iso9660->primary.rootent; /* There isn't rr_move entry. * Create rr_move entry and insert it into the root entry. */ rrmoved = isoent_create_virtual_dir(a, iso9660, "rr_moved"); if (rrmoved == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } /* Add "rr_moved" entry to the root entry. */ isoent_add_child_head(rootent, rrmoved); archive_entry_set_nlink(rootent->file->entry, archive_entry_nlink(rootent->file->entry) + 1); /* Register "rr_moved" entry to second level pathtable. */ path_table_add_entry(&(iso9660->primary.pathtbl[1]), rrmoved); /* Save rr_moved. */ *rr_moved = rrmoved; } /* * Make a clone of curent which is going to be relocated * to rr_moved. */ mvent = isoent_clone(curent); if (mvent == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } /* linking.. and use for creating "CL", "PL" and "RE" */ mvent->rr_parent = curent->parent; curent->rr_child = mvent; /* * Move subdirectories from the curent to mvent */ if (curent->children.first != NULL) { *mvent->children.last = curent->children.first; mvent->children.last = curent->children.last; } for (np = mvent->children.first; np != NULL; np = np->chnext) np->parent = mvent; mvent->children.cnt = curent->children.cnt; curent->children.cnt = 0; curent->children.first = NULL; curent->children.last = &curent->children.first; if (curent->subdirs.first != NULL) { *mvent->subdirs.last = curent->subdirs.first; mvent->subdirs.last = curent->subdirs.last; } mvent->subdirs.cnt = curent->subdirs.cnt; curent->subdirs.cnt = 0; curent->subdirs.first = NULL; curent->subdirs.last = &curent->subdirs.first; /* * The mvent becomes a child of the rr_moved entry. */ isoent_add_child_tail(rrmoved, mvent); archive_entry_set_nlink(rrmoved->file->entry, archive_entry_nlink(rrmoved->file->entry) + 1); /* * This entry which relocated to the rr_moved directory * has to set the flag as a file. * See also RRIP 4.1.5.1 Description of the "CL" System Use Entry. */ curent->dir = 0; *newent = mvent; return (ARCHIVE_OK); } static int isoent_rr_move(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; struct path_table *pt; struct isoent *rootent, *rr_moved; struct isoent *np, *last; int r; pt = &(iso9660->primary.pathtbl[MAX_DEPTH-1]); /* Theare aren't level 8 directories reaching a deepr level. */ if (pt->cnt == 0) return (ARCHIVE_OK); rootent = iso9660->primary.rootent; /* If "rr_moved" directory is already existing, * we have to use it. */ rr_moved = isoent_find_child(rootent, "rr_moved"); if (rr_moved != NULL && rr_moved != rootent->children.first) { /* * It's necessary that rr_move is the first entry * of the root. */ /* Remove "rr_moved" entry from children chain. */ isoent_remove_child(rootent, rr_moved); /* Add "rr_moved" entry into the head of children chain. */ isoent_add_child_head(rootent, rr_moved); } /* * Check level 8 path_table. * If find out sub directory entries, that entries move to rr_move. */ np = pt->first; while (np != NULL) { last = path_table_last_entry(pt); for (; np != NULL; np = np->ptnext) { struct isoent *mvent; struct isoent *newent; if (!np->dir) continue; for (mvent = np->subdirs.first; mvent != NULL; mvent = mvent->drnext) { r = isoent_rr_move_dir(a, &rr_moved, mvent, &newent); if (r < 0) return (r); isoent_collect_dirs(&(iso9660->primary), newent, 2); } } /* If new entries are added to level 8 path_talbe, * its sub directory entries move to rr_move too. */ np = last->ptnext; } return (ARCHIVE_OK); } /* * This comparing rule is according to ISO9660 Standard 6.9.1 */ static int _compare_path_table(const void *v1, const void *v2) { const struct isoent *p1, *p2; const char *s1, *s2; int cmp, l; p1 = *((const struct isoent **)(uintptr_t)v1); p2 = *((const struct isoent **)(uintptr_t)v2); /* Compare parent directory number */ cmp = p1->parent->dir_number - p2->parent->dir_number; if (cmp != 0) return (cmp); /* Compare indetifier */ s1 = p1->identifier; s2 = p2->identifier; l = p1->ext_off; if (l > p2->ext_off) l = p2->ext_off; cmp = strncmp(s1, s2, l); if (cmp != 0) return (cmp); if (p1->ext_off < p2->ext_off) { s2 += l; l = p2->ext_off - p1->ext_off; while (l--) if (0x20 != *s2++) return (0x20 - *(const unsigned char *)(s2 - 1)); } else if (p1->ext_off > p2->ext_off) { s1 += l; l = p1->ext_off - p2->ext_off; while (l--) if (0x20 != *s1++) return (*(const unsigned char *)(s1 - 1) - 0x20); } return (0); } static int _compare_path_table_joliet(const void *v1, const void *v2) { const struct isoent *p1, *p2; const unsigned char *s1, *s2; int cmp, l; p1 = *((const struct isoent **)(uintptr_t)v1); p2 = *((const struct isoent **)(uintptr_t)v2); /* Compare parent directory number */ cmp = p1->parent->dir_number - p2->parent->dir_number; if (cmp != 0) return (cmp); /* Compare indetifier */ s1 = (const unsigned char *)p1->identifier; s2 = (const unsigned char *)p2->identifier; l = p1->ext_off; if (l > p2->ext_off) l = p2->ext_off; cmp = memcmp(s1, s2, l); if (cmp != 0) return (cmp); if (p1->ext_off < p2->ext_off) { s2 += l; l = p2->ext_off - p1->ext_off; while (l--) if (0 != *s2++) return (- *(const unsigned char *)(s2 - 1)); } else if (p1->ext_off > p2->ext_off) { s1 += l; l = p1->ext_off - p2->ext_off; while (l--) if (0 != *s1++) return (*(const unsigned char *)(s1 - 1)); } return (0); } static inline void path_table_add_entry(struct path_table *pathtbl, struct isoent *ent) { ent->ptnext = NULL; *pathtbl->last = ent; pathtbl->last = &(ent->ptnext); pathtbl->cnt ++; } static inline struct isoent * path_table_last_entry(struct path_table *pathtbl) { if (pathtbl->first == NULL) return (NULL); return (((struct isoent *)(void *) ((char *)(pathtbl->last) - offsetof(struct isoent, ptnext)))); } /* * Sort directory entries in path_table * and assign directory number to each entries. */ static int isoent_make_path_table_2(struct archive_write *a, struct vdd *vdd, int depth, int *dir_number) { struct isoent *np; struct isoent **enttbl; struct path_table *pt; int i; pt = &vdd->pathtbl[depth]; if (pt->cnt == 0) { pt->sorted = NULL; return (ARCHIVE_OK); } enttbl = malloc(pt->cnt * sizeof(struct isoent *)); if (enttbl == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } pt->sorted = enttbl; for (np = pt->first; np != NULL; np = np->ptnext) *enttbl ++ = np; enttbl = pt->sorted; switch (vdd->vdd_type) { case VDD_PRIMARY: case VDD_ENHANCED: #ifdef __COMPAR_FN_T qsort(enttbl, pt->cnt, sizeof(struct isoent *), (__compar_fn_t)_compare_path_table); #else qsort(enttbl, pt->cnt, sizeof(struct isoent *), _compare_path_table); #endif break; case VDD_JOLIET: #ifdef __COMPAR_FN_T qsort(enttbl, pt->cnt, sizeof(struct isoent *), (__compar_fn_t)_compare_path_table_joliet); #else qsort(enttbl, pt->cnt, sizeof(struct isoent *), _compare_path_table_joliet); #endif break; } for (i = 0; i < pt->cnt; i++) enttbl[i]->dir_number = (*dir_number)++; return (ARCHIVE_OK); } static int isoent_alloc_path_table(struct archive_write *a, struct vdd *vdd, int max_depth) { int i; vdd->max_depth = max_depth; vdd->pathtbl = malloc(sizeof(*vdd->pathtbl) * vdd->max_depth); if (vdd->pathtbl == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } for (i = 0; i < vdd->max_depth; i++) { vdd->pathtbl[i].first = NULL; vdd->pathtbl[i].last = &(vdd->pathtbl[i].first); vdd->pathtbl[i].sorted = NULL; vdd->pathtbl[i].cnt = 0; } return (ARCHIVE_OK); } /* * Make Path Tables */ static int isoent_make_path_table(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; int depth, r; int dir_number; /* * Init Path Table. */ if (iso9660->dircnt_max >= MAX_DEPTH && (!iso9660->opt.limit_depth || iso9660->opt.iso_level == 4)) r = isoent_alloc_path_table(a, &(iso9660->primary), iso9660->dircnt_max + 1); else /* The number of levels in the hierarchy cannot exceed * eight. */ r = isoent_alloc_path_table(a, &(iso9660->primary), MAX_DEPTH); if (r < 0) return (r); if (iso9660->opt.joliet) { r = isoent_alloc_path_table(a, &(iso9660->joliet), iso9660->dircnt_max + 1); if (r < 0) return (r); } /* Step 0. * - Collect directories for primary and joliet. */ isoent_collect_dirs(&(iso9660->primary), NULL, 0); if (iso9660->opt.joliet) isoent_collect_dirs(&(iso9660->joliet), NULL, 0); /* * Rockridge; move deeper depth directories to rr_moved. */ if (iso9660->opt.rr) { r = isoent_rr_move(a); if (r < 0) return (r); } /* Update nlink. */ isofile_connect_hardlink_files(iso9660); /* Step 1. * - Renew a value of the depth of that directories. * - Resolve hardlinks. * - Convert pathnames to ISO9660 name or UCS2(joliet). * - Sort files by each directory. */ r = isoent_traverse_tree(a, &(iso9660->primary)); if (r < 0) return (r); if (iso9660->opt.joliet) { r = isoent_traverse_tree(a, &(iso9660->joliet)); if (r < 0) return (r); } /* Step 2. * - Sort directories. * - Assign all directory number. */ dir_number = 1; for (depth = 0; depth < iso9660->primary.max_depth; depth++) { r = isoent_make_path_table_2(a, &(iso9660->primary), depth, &dir_number); if (r < 0) return (r); } if (iso9660->opt.joliet) { dir_number = 1; for (depth = 0; depth < iso9660->joliet.max_depth; depth++) { r = isoent_make_path_table_2(a, &(iso9660->joliet), depth, &dir_number); if (r < 0) return (r); } } if (iso9660->opt.limit_dirs && dir_number > 0xffff) { /* * Maximum number of directories is 65535(0xffff) * doe to size(16bit) of Parent Directory Number of * the Path Table. * See also ISO9660 Standard 9.4. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Too many directories(%d) over 65535.", dir_number); return (ARCHIVE_FATAL); } /* Get the size of the Path Table. */ calculate_path_table_size(&(iso9660->primary)); if (iso9660->opt.joliet) calculate_path_table_size(&(iso9660->joliet)); return (ARCHIVE_OK); } static int isoent_find_out_boot_file(struct archive_write *a, struct isoent *rootent) { struct iso9660 *iso9660 = a->format_data; /* Find a isoent of the boot file. */ iso9660->el_torito.boot = isoent_find_entry(rootent, iso9660->el_torito.boot_filename.s); if (iso9660->el_torito.boot == NULL) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Can't find the boot image file ``%s''", iso9660->el_torito.boot_filename.s); return (ARCHIVE_FATAL); } iso9660->el_torito.boot->file->boot = BOOT_IMAGE; return (ARCHIVE_OK); } static int isoent_create_boot_catalog(struct archive_write *a, struct isoent *rootent) { struct iso9660 *iso9660 = a->format_data; struct isofile *file; struct isoent *isoent; struct archive_entry *entry; (void)rootent; /* UNUSED */ /* * Create the entry which is the "boot.catalog" file. */ file = isofile_new(a, NULL); if (file == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } archive_entry_set_pathname(file->entry, iso9660->el_torito.catalog_filename.s); archive_entry_set_size(file->entry, LOGICAL_BLOCK_SIZE); archive_entry_set_mtime(file->entry, iso9660->birth_time, 0); archive_entry_set_atime(file->entry, iso9660->birth_time, 0); archive_entry_set_ctime(file->entry, iso9660->birth_time, 0); archive_entry_set_uid(file->entry, getuid()); archive_entry_set_gid(file->entry, getgid()); archive_entry_set_mode(file->entry, AE_IFREG | 0444); archive_entry_set_nlink(file->entry, 1); if (isofile_gen_utility_names(a, file) < ARCHIVE_WARN) { isofile_free(file); return (ARCHIVE_FATAL); } file->boot = BOOT_CATALOG; file->content.size = LOGICAL_BLOCK_SIZE; isofile_add_entry(iso9660, file); isoent = isoent_new(file); if (isoent == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } isoent->virtual = 1; /* Add the "boot.catalog" entry into tree */ if (isoent_tree(a, &isoent) != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->el_torito.catalog = isoent; /* * Get a boot medai type. */ switch (iso9660->opt.boot_type) { default: case OPT_BOOT_TYPE_AUTO: /* Try detecting a media type of the boot image. */ entry = iso9660->el_torito.boot->file->entry; if (archive_entry_size(entry) == FD_1_2M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_1_2M_DISKETTE; else if (archive_entry_size(entry) == FD_1_44M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_1_44M_DISKETTE; else if (archive_entry_size(entry) == FD_2_88M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_2_88M_DISKETTE; else /* We cannot decide whether the boot image is * hard-disk. */ iso9660->el_torito.media_type = BOOT_MEDIA_NO_EMULATION; break; case OPT_BOOT_TYPE_NO_EMU: iso9660->el_torito.media_type = BOOT_MEDIA_NO_EMULATION; break; case OPT_BOOT_TYPE_HARD_DISK: iso9660->el_torito.media_type = BOOT_MEDIA_HARD_DISK; break; case OPT_BOOT_TYPE_FD: entry = iso9660->el_torito.boot->file->entry; if (archive_entry_size(entry) <= FD_1_2M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_1_2M_DISKETTE; else if (archive_entry_size(entry) <= FD_1_44M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_1_44M_DISKETTE; else if (archive_entry_size(entry) <= FD_2_88M_SIZE) iso9660->el_torito.media_type = BOOT_MEDIA_2_88M_DISKETTE; else { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Boot image file(``%s'') size is too big " "for fd type.", iso9660->el_torito.boot_filename.s); return (ARCHIVE_FATAL); } break; } /* * Get a system type. * TODO: `El Torito' specification says "A copy of byte 5 from the * Partition Table found in the boot image". */ iso9660->el_torito.system_type = 0; /* * Get an ID. */ if (iso9660->opt.publisher) archive_string_copy(&(iso9660->el_torito.id), &(iso9660->publisher_identifier)); return (ARCHIVE_OK); } /* * If a media type is floppy, return its image size. * otherwise return 0. */ static size_t fd_boot_image_size(int media_type) { switch (media_type) { case BOOT_MEDIA_1_2M_DISKETTE: return (FD_1_2M_SIZE); case BOOT_MEDIA_1_44M_DISKETTE: return (FD_1_44M_SIZE); case BOOT_MEDIA_2_88M_DISKETTE: return (FD_2_88M_SIZE); default: return (0); } } /* * Make a boot catalog image data. */ static int make_boot_catalog(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; unsigned char *block; unsigned char *p; uint16_t sum, *wp; block = wb_buffptr(a); memset(block, 0, LOGICAL_BLOCK_SIZE); p = block; /* * Validation Entry */ /* Header ID */ p[0] = 1; /* Platform ID */ p[1] = iso9660->el_torito.platform_id; /* Reserved */ p[2] = p[3] = 0; /* ID */ if (archive_strlen(&(iso9660->el_torito.id)) > 0) strncpy((char *)p+4, iso9660->el_torito.id.s, 23); p[27] = 0; /* Checksum */ p[28] = p[29] = 0; /* Key */ p[30] = 0x55; p[31] = 0xAA; sum = 0; wp = (uint16_t *)block; while (wp < (uint16_t *)&block[32]) sum += archive_le16dec(wp++); set_num_721(&block[28], (~sum) + 1); /* * Initial/Default Entry */ p = &block[32]; /* Boot Indicator */ p[0] = 0x88; /* Boot media type */ p[1] = iso9660->el_torito.media_type; /* Load Segment */ if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) set_num_721(&p[2], iso9660->el_torito.boot_load_seg); else set_num_721(&p[2], 0); /* System Type */ p[4] = iso9660->el_torito.system_type; /* Unused */ p[5] = 0; /* Sector Count */ if (iso9660->el_torito.media_type == BOOT_MEDIA_NO_EMULATION) set_num_721(&p[6], iso9660->el_torito.boot_load_size); else set_num_721(&p[6], 1); /* Load RBA */ set_num_731(&p[8], iso9660->el_torito.boot->file->content.location); /* Unused */ memset(&p[12], 0, 20); return (wb_consume(a, LOGICAL_BLOCK_SIZE)); } static int setup_boot_information(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; struct isoent *np; int64_t size; uint32_t sum; unsigned char buff[4096]; np = iso9660->el_torito.boot; lseek(iso9660->temp_fd, np->file->content.offset_of_temp + 64, SEEK_SET); size = archive_entry_size(np->file->entry) - 64; if (size <= 0) { archive_set_error(&a->archive, errno, "Boot file(%jd) is too small", (intmax_t)size + 64); return (ARCHIVE_FATAL); } sum = 0; while (size > 0) { size_t rsize; ssize_t i, rs; if (size > (int64_t)sizeof(buff)) rsize = sizeof(buff); else rsize = (size_t)size; rs = read(iso9660->temp_fd, buff, rsize); if (rs <= 0) { archive_set_error(&a->archive, errno, "Can't read temporary file(%jd)", (intmax_t)rs); return (ARCHIVE_FATAL); } for (i = 0; i < rs; i += 4) sum += archive_le32dec(buff + i); size -= rs; } /* Set the location of Primary Volume Descriptor. */ set_num_731(buff, SYSTEM_AREA_BLOCK); /* Set the location of the boot file. */ set_num_731(buff+4, np->file->content.location); /* Set the size of the boot file. */ size = fd_boot_image_size(iso9660->el_torito.media_type); if (size == 0) size = archive_entry_size(np->file->entry); set_num_731(buff+8, (uint32_t)size); /* Set the sum of the boot file. */ set_num_731(buff+12, sum); /* Clear reserved bytes. */ memset(buff+16, 0, 40); /* Overwrite the boot file. */ lseek(iso9660->temp_fd, np->file->content.offset_of_temp + 8, SEEK_SET); return (write_to_temp(a, buff, 56)); } #ifdef HAVE_ZLIB_H static int zisofs_init_zstream(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; int r; iso9660->zisofs.stream.next_in = NULL; iso9660->zisofs.stream.avail_in = 0; iso9660->zisofs.stream.total_in = 0; iso9660->zisofs.stream.total_out = 0; if (iso9660->zisofs.stream_valid) r = deflateReset(&(iso9660->zisofs.stream)); else { r = deflateInit(&(iso9660->zisofs.stream), iso9660->zisofs.compression_level); iso9660->zisofs.stream_valid = 1; } switch (r) { case Z_OK: break; default: case Z_STREAM_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "compression library: invalid setup parameter"); return (ARCHIVE_FATAL); case Z_MEM_ERROR: archive_set_error(&a->archive, ENOMEM, "Internal error initializing " "compression library"); return (ARCHIVE_FATAL); case Z_VERSION_ERROR: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Internal error initializing " "compression library: invalid library version"); return (ARCHIVE_FATAL); } return (ARCHIVE_OK); } #endif /* HAVE_ZLIB_H */ static int zisofs_init(struct archive_write *a, struct isofile *file) { struct iso9660 *iso9660 = a->format_data; #ifdef HAVE_ZLIB_H uint64_t tsize; size_t _ceil, bpsize; int r; #endif iso9660->zisofs.detect_magic = 0; iso9660->zisofs.making = 0; if (!iso9660->opt.rr || !iso9660->opt.zisofs) return (ARCHIVE_OK); if (archive_entry_size(file->entry) >= 24 && archive_entry_size(file->entry) < MULTI_EXTENT_SIZE) { /* Acceptable file size for zisofs. */ iso9660->zisofs.detect_magic = 1; iso9660->zisofs.magic_cnt = 0; } if (!iso9660->zisofs.detect_magic) return (ARCHIVE_OK); #ifdef HAVE_ZLIB_H /* The number of Logical Blocks which uncompressed data * will use in iso-image file is the same as the number of * Logical Blocks which zisofs(compressed) data will use * in ISO-image file. It won't reduce iso-image file size. */ if (archive_entry_size(file->entry) <= LOGICAL_BLOCK_SIZE) return (ARCHIVE_OK); /* Initialize compression library */ r = zisofs_init_zstream(a); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Mark file->zisofs to create RRIP 'ZF' Use Entry. */ file->zisofs.header_size = ZF_HEADER_SIZE >> 2; file->zisofs.log2_bs = ZF_LOG2_BS; file->zisofs.uncompressed_size = (uint32_t)archive_entry_size(file->entry); /* Calculate a size of Block Pointers of zisofs. */ _ceil = (file->zisofs.uncompressed_size + ZF_BLOCK_SIZE -1) >> file->zisofs.log2_bs; iso9660->zisofs.block_pointers_cnt = (int)_ceil + 1; iso9660->zisofs.block_pointers_idx = 0; /* Ensure a buffer size used for Block Pointers */ bpsize = iso9660->zisofs.block_pointers_cnt * sizeof(iso9660->zisofs.block_pointers[0]); if (iso9660->zisofs.block_pointers_allocated < bpsize) { free(iso9660->zisofs.block_pointers); iso9660->zisofs.block_pointers = malloc(bpsize); if (iso9660->zisofs.block_pointers == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate data"); return (ARCHIVE_FATAL); } iso9660->zisofs.block_pointers_allocated = bpsize; } /* * Skip zisofs header and Block Pointers, which we will write * after all compressed data of a file written to the temporary * file. */ tsize = ZF_HEADER_SIZE + bpsize; if (write_null(a, (size_t)tsize) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* * Initialize some variables to make zisofs. */ archive_le32enc(&(iso9660->zisofs.block_pointers[0]), (uint32_t)tsize); iso9660->zisofs.remaining = file->zisofs.uncompressed_size; iso9660->zisofs.making = 1; iso9660->zisofs.allzero = 1; iso9660->zisofs.block_offset = tsize; iso9660->zisofs.total_size = tsize; iso9660->cur_file->cur_content->size = tsize; #endif return (ARCHIVE_OK); } static void zisofs_detect_magic(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; struct isofile *file = iso9660->cur_file; const unsigned char *p, *endp; const unsigned char *magic_buff; uint32_t uncompressed_size; unsigned char header_size; unsigned char log2_bs; size_t _ceil, doff; uint32_t bst, bed; int magic_max; int64_t entry_size; entry_size = archive_entry_size(file->entry); if ((int64_t)sizeof(iso9660->zisofs.magic_buffer) > entry_size) magic_max = (int)entry_size; else magic_max = sizeof(iso9660->zisofs.magic_buffer); if (iso9660->zisofs.magic_cnt == 0 && s >= (size_t)magic_max) /* It's unnecessary we copy buffer. */ magic_buff = buff; else { if (iso9660->zisofs.magic_cnt < magic_max) { size_t l; l = sizeof(iso9660->zisofs.magic_buffer) - iso9660->zisofs.magic_cnt; if (l > s) l = s; memcpy(iso9660->zisofs.magic_buffer + iso9660->zisofs.magic_cnt, buff, l); iso9660->zisofs.magic_cnt += (int)l; if (iso9660->zisofs.magic_cnt < magic_max) return; } magic_buff = iso9660->zisofs.magic_buffer; } iso9660->zisofs.detect_magic = 0; p = magic_buff; /* Check the magic code of zisofs. */ if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) /* This is not zisofs file which made by mkzftree. */ return; p += sizeof(zisofs_magic); /* Read a zisofs header. */ uncompressed_size = archive_le32dec(p); header_size = p[4]; log2_bs = p[5]; if (uncompressed_size < 24 || header_size != 4 || log2_bs > 30 || log2_bs < 7) return;/* Invalid or not supported header. */ /* Calculate a size of Block Pointers of zisofs. */ _ceil = (uncompressed_size + (ARCHIVE_LITERAL_LL(1) << log2_bs) -1) >> log2_bs; doff = (_ceil + 1) * 4 + 16; if (entry_size < (int64_t)doff) return;/* Invalid data. */ /* Check every Block Pointer has valid value. */ p = magic_buff + 16; endp = magic_buff + magic_max; while (_ceil && p + 8 <= endp) { bst = archive_le32dec(p); if (bst != doff) return;/* Invalid data. */ p += 4; bed = archive_le32dec(p); if (bed < bst || bed > entry_size) return;/* Invalid data. */ doff += bed - bst; _ceil--; } file->zisofs.uncompressed_size = uncompressed_size; file->zisofs.header_size = header_size; file->zisofs.log2_bs = log2_bs; /* Disable making a zisofs image. */ iso9660->zisofs.making = 0; } #ifdef HAVE_ZLIB_H /* * Compress data and write it to a temporary file. */ static int zisofs_write_to_temp(struct archive_write *a, const void *buff, size_t s) { struct iso9660 *iso9660 = a->format_data; struct isofile *file = iso9660->cur_file; const unsigned char *b; z_stream *zstrm; size_t avail, csize; int flush, r; zstrm = &(iso9660->zisofs.stream); zstrm->next_out = wb_buffptr(a); zstrm->avail_out = (uInt)wb_remaining(a); b = (const unsigned char *)buff; do { avail = ZF_BLOCK_SIZE - zstrm->total_in; if (s < avail) { avail = s; flush = Z_NO_FLUSH; } else flush = Z_FINISH; iso9660->zisofs.remaining -= avail; if (iso9660->zisofs.remaining <= 0) flush = Z_FINISH; zstrm->next_in = (Bytef *)(uintptr_t)(const void *)b; zstrm->avail_in = (uInt)avail; /* * Check if current data block are all zero. */ if (iso9660->zisofs.allzero) { const unsigned char *nonzero = b; const unsigned char *nonzeroend = b + avail; while (nonzero < nonzeroend) if (*nonzero++) { iso9660->zisofs.allzero = 0; break; } } b += avail; s -= avail; /* * If current data block are all zero, we do not use * compressed data. */ if (flush == Z_FINISH && iso9660->zisofs.allzero && avail + zstrm->total_in == ZF_BLOCK_SIZE) { if (iso9660->zisofs.block_offset != file->cur_content->size) { int64_t diff; r = wb_set_offset(a, file->cur_content->offset_of_temp + iso9660->zisofs.block_offset); if (r != ARCHIVE_OK) return (r); diff = file->cur_content->size - iso9660->zisofs.block_offset; file->cur_content->size -= diff; iso9660->zisofs.total_size -= diff; } zstrm->avail_in = 0; } /* * Compress file data. */ while (zstrm->avail_in > 0) { csize = zstrm->total_out; r = deflate(zstrm, flush); switch (r) { case Z_OK: case Z_STREAM_END: csize = zstrm->total_out - csize; if (wb_consume(a, csize) != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->zisofs.total_size += csize; iso9660->cur_file->cur_content->size += csize; zstrm->next_out = wb_buffptr(a); zstrm->avail_out = (uInt)wb_remaining(a); break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Compression failed:" " deflate() call returned status %d", r); return (ARCHIVE_FATAL); } } if (flush == Z_FINISH) { /* * Save the information of one zisofs block. */ iso9660->zisofs.block_pointers_idx ++; archive_le32enc(&(iso9660->zisofs.block_pointers[ iso9660->zisofs.block_pointers_idx]), (uint32_t)iso9660->zisofs.total_size); r = zisofs_init_zstream(a); if (r != ARCHIVE_OK) return (ARCHIVE_FATAL); iso9660->zisofs.allzero = 1; iso9660->zisofs.block_offset = file->cur_content->size; } } while (s); return (ARCHIVE_OK); } static int zisofs_finish_entry(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; struct isofile *file = iso9660->cur_file; unsigned char buff[16]; size_t s; int64_t tail; /* Direct temp file stream to zisofs temp file stream. */ archive_entry_set_size(file->entry, iso9660->zisofs.total_size); /* * Save a file pointer which points the end of current zisofs data. */ tail = wb_offset(a); /* * Make a header. * * +-----------------+----------------+-----------------+ * | Header 16 bytes | Block Pointers | Compressed data | * +-----------------+----------------+-----------------+ * 0 16 +X * Block Pointers : * 4 * (((Uncompressed file size + block_size -1) / block_size) + 1) * * Write zisofs header. * Magic number * +----+----+----+----+----+----+----+----+ * | 37 | E4 | 53 | 96 | C9 | DB | D6 | 07 | * +----+----+----+----+----+----+----+----+ * 0 1 2 3 4 5 6 7 8 * * +------------------------+------------------+ * | Uncompressed file size | header_size >> 2 | * +------------------------+------------------+ * 8 12 13 * * +-----------------+----------------+ * | log2 block_size | Reserved(0000) | * +-----------------+----------------+ * 13 14 16 */ memcpy(buff, zisofs_magic, 8); set_num_731(buff+8, file->zisofs.uncompressed_size); buff[12] = file->zisofs.header_size; buff[13] = file->zisofs.log2_bs; buff[14] = buff[15] = 0;/* Reserved */ /* Move to the right position to write the header. */ wb_set_offset(a, file->content.offset_of_temp); /* Write the header. */ if (wb_write_to_temp(a, buff, 16) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* * Write zisofs Block Pointers. */ s = iso9660->zisofs.block_pointers_cnt * sizeof(iso9660->zisofs.block_pointers[0]); if (wb_write_to_temp(a, iso9660->zisofs.block_pointers, s) != ARCHIVE_OK) return (ARCHIVE_FATAL); /* Set a file pointer back to the end of the temporary file. */ wb_set_offset(a, tail); return (ARCHIVE_OK); } static int zisofs_free(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; int ret = ARCHIVE_OK; free(iso9660->zisofs.block_pointers); if (iso9660->zisofs.stream_valid && deflateEnd(&(iso9660->zisofs.stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up compressor"); ret = ARCHIVE_FATAL; } iso9660->zisofs.block_pointers = NULL; iso9660->zisofs.stream_valid = 0; return (ret); } struct zisofs_extract { int pz_log2_bs; /* Log2 of block size */ uint64_t pz_uncompressed_size; size_t uncompressed_buffer_size; int initialized:1; int header_passed:1; uint32_t pz_offset; unsigned char *block_pointers; size_t block_pointers_size; size_t block_pointers_avail; size_t block_off; uint32_t block_avail; z_stream stream; int stream_valid; }; static ssize_t zisofs_extract_init(struct archive_write *a, struct zisofs_extract *zisofs, const unsigned char *p, size_t bytes) { size_t avail = bytes; size_t _ceil, xsize; /* Allocate block pointers buffer. */ _ceil = (size_t)((zisofs->pz_uncompressed_size + (((int64_t)1) << zisofs->pz_log2_bs) - 1) >> zisofs->pz_log2_bs); xsize = (_ceil + 1) * 4; if (zisofs->block_pointers == NULL) { size_t alloc = ((xsize >> 10) + 1) << 10; zisofs->block_pointers = malloc(alloc); if (zisofs->block_pointers == NULL) { archive_set_error(&a->archive, ENOMEM, "No memory for zisofs decompression"); return (ARCHIVE_FATAL); } } zisofs->block_pointers_size = xsize; /* Allocate uncompressed data buffer. */ zisofs->uncompressed_buffer_size = (size_t)1UL << zisofs->pz_log2_bs; /* * Read the file header, and check the magic code of zisofs. */ if (!zisofs->header_passed) { int err = 0; if (avail < 16) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs file body"); return (ARCHIVE_FATAL); } if (memcmp(p, zisofs_magic, sizeof(zisofs_magic)) != 0) err = 1; else if (archive_le32dec(p + 8) != zisofs->pz_uncompressed_size) err = 1; else if (p[12] != 4 || p[13] != zisofs->pz_log2_bs) err = 1; if (err) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs file body"); return (ARCHIVE_FATAL); } avail -= 16; p += 16; zisofs->header_passed = 1; } /* * Read block pointers. */ if (zisofs->header_passed && zisofs->block_pointers_avail < zisofs->block_pointers_size) { xsize = zisofs->block_pointers_size - zisofs->block_pointers_avail; if (avail < xsize) xsize = avail; memcpy(zisofs->block_pointers + zisofs->block_pointers_avail, p, xsize); zisofs->block_pointers_avail += xsize; avail -= xsize; if (zisofs->block_pointers_avail == zisofs->block_pointers_size) { /* We've got all block pointers and initialize * related variables. */ zisofs->block_off = 0; zisofs->block_avail = 0; /* Complete a initialization */ zisofs->initialized = 1; } } return ((ssize_t)avail); } static ssize_t zisofs_extract(struct archive_write *a, struct zisofs_extract *zisofs, const unsigned char *p, size_t bytes) { size_t avail; int r; if (!zisofs->initialized) { ssize_t rs = zisofs_extract_init(a, zisofs, p, bytes); if (rs < 0) return (rs); if (!zisofs->initialized) { /* We need more data. */ zisofs->pz_offset += (uint32_t)bytes; return (bytes); } avail = rs; p += bytes - avail; } else avail = bytes; /* * Get block offsets from block pointers. */ if (zisofs->block_avail == 0) { uint32_t bst, bed; if (zisofs->block_off + 4 >= zisofs->block_pointers_size) { /* There isn't a pair of offsets. */ archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers"); return (ARCHIVE_FATAL); } bst = archive_le32dec( zisofs->block_pointers + zisofs->block_off); if (bst != zisofs->pz_offset + (bytes - avail)) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers(cannot seek)"); return (ARCHIVE_FATAL); } bed = archive_le32dec( zisofs->block_pointers + zisofs->block_off + 4); if (bed < bst) { archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Illegal zisofs block pointers"); return (ARCHIVE_FATAL); } zisofs->block_avail = bed - bst; zisofs->block_off += 4; /* Initialize compression library for new block. */ if (zisofs->stream_valid) r = inflateReset(&zisofs->stream); else r = inflateInit(&zisofs->stream); if (r != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Can't initialize zisofs decompression."); return (ARCHIVE_FATAL); } zisofs->stream_valid = 1; zisofs->stream.total_in = 0; zisofs->stream.total_out = 0; } /* * Make uncompressed data. */ if (zisofs->block_avail == 0) { /* * It's basically 32K bytes NUL data. */ unsigned char *wb; size_t size, wsize; size = zisofs->uncompressed_buffer_size; while (size) { wb = wb_buffptr(a); if (size > wb_remaining(a)) wsize = wb_remaining(a); else wsize = size; memset(wb, 0, wsize); r = wb_consume(a, wsize); if (r < 0) return (r); size -= wsize; } } else { zisofs->stream.next_in = (Bytef *)(uintptr_t)(const void *)p; if (avail > zisofs->block_avail) zisofs->stream.avail_in = zisofs->block_avail; else zisofs->stream.avail_in = (uInt)avail; zisofs->stream.next_out = wb_buffptr(a); zisofs->stream.avail_out = (uInt)wb_remaining(a); r = inflate(&zisofs->stream, 0); switch (r) { case Z_OK: /* Decompressor made some progress.*/ case Z_STREAM_END: /* Found end of stream. */ break; default: archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "zisofs decompression failed (%d)", r); return (ARCHIVE_FATAL); } avail -= zisofs->stream.next_in - p; zisofs->block_avail -= (uint32_t)(zisofs->stream.next_in - p); r = wb_consume(a, wb_remaining(a) - zisofs->stream.avail_out); if (r < 0) return (r); } zisofs->pz_offset += (uint32_t)bytes; return (bytes - avail); } static int zisofs_rewind_boot_file(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; struct isofile *file; unsigned char *rbuff; ssize_t r; size_t remaining, rbuff_size; struct zisofs_extract zext; int64_t read_offset, write_offset, new_offset; int fd, ret = ARCHIVE_OK; file = iso9660->el_torito.boot->file; /* * There is nothing to do if this boot file does not have * zisofs header. */ if (file->zisofs.header_size == 0) return (ARCHIVE_OK); /* * Uncompress the zisofs'ed file contents. */ memset(&zext, 0, sizeof(zext)); zext.pz_uncompressed_size = file->zisofs.uncompressed_size; zext.pz_log2_bs = file->zisofs.log2_bs; fd = iso9660->temp_fd; new_offset = wb_offset(a); read_offset = file->content.offset_of_temp; remaining = (size_t)file->content.size; if (remaining > 1024 * 32) rbuff_size = 1024 * 32; else rbuff_size = remaining; rbuff = malloc(rbuff_size); if (rbuff == NULL) { archive_set_error(&a->archive, ENOMEM, "Can't allocate memory"); return (ARCHIVE_FATAL); } while (remaining) { size_t rsize; ssize_t rs; /* Get the current file pointer. */ write_offset = lseek(fd, 0, SEEK_CUR); /* Change the file pointer to read. */ lseek(fd, read_offset, SEEK_SET); rsize = rbuff_size; if (rsize > remaining) rsize = remaining; rs = read(iso9660->temp_fd, rbuff, rsize); if (rs <= 0) { archive_set_error(&a->archive, errno, "Can't read temporary file(%jd)", (intmax_t)rs); ret = ARCHIVE_FATAL; break; } remaining -= rs; read_offset += rs; /* Put the file pointer back to write. */ lseek(fd, write_offset, SEEK_SET); r = zisofs_extract(a, &zext, rbuff, rs); if (r < 0) { ret = (int)r; break; } } if (ret == ARCHIVE_OK) { /* * Change the boot file content from zisofs'ed data * to plain data. */ file->content.offset_of_temp = new_offset; file->content.size = file->zisofs.uncompressed_size; archive_entry_set_size(file->entry, file->content.size); /* Set to be no zisofs. */ file->zisofs.header_size = 0; file->zisofs.log2_bs = 0; file->zisofs.uncompressed_size = 0; r = wb_write_padding_to_temp(a, file->content.size); if (r < 0) ret = ARCHIVE_FATAL; } /* * Free the resource we used in this function only. */ free(rbuff); free(zext.block_pointers); if (zext.stream_valid && inflateEnd(&(zext.stream)) != Z_OK) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Failed to clean up compressor"); ret = ARCHIVE_FATAL; } return (ret); } #else static int zisofs_write_to_temp(struct archive_write *a, const void *buff, size_t s) { (void)buff; /* UNUSED */ (void)s; /* UNUSED */ archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "Programing error"); return (ARCHIVE_FATAL); } static int zisofs_rewind_boot_file(struct archive_write *a) { struct iso9660 *iso9660 = a->format_data; if (iso9660->el_torito.boot->file->zisofs.header_size != 0) { archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, "We cannot extract the zisofs imaged boot file;" " this may not boot in being zisofs imaged"); return (ARCHIVE_FAILED); } return (ARCHIVE_OK); } static int zisofs_finish_entry(struct archive_write *a) { (void)a; /* UNUSED */ return (ARCHIVE_OK); } static int zisofs_free(struct archive_write *a) { (void)a; /* UNUSED */ return (ARCHIVE_OK); } #endif /* HAVE_ZLIB_H */
./CrossVul/dataset_final_sorted/CWE-190/c/good_5202_0
crossvul-cpp_data_bad_4425_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/accelerate-private.h" #include "magick/animate.h" #include "magick/animate.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/cache-private.h" #include "magick/cache-view.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/compress.h" #include "magick/constitute.h" #include "magick/deprecate.h" #include "magick/display.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/list.h" #include "magick/image-private.h" #include "magick/magic.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/paint.h" #include "magick/pixel-private.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantize.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/semaphore.h" #include "magick/signature-private.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/timer.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImageChannel method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImageChannel(Image *image, % const ChannelType channel,const MagickEvaluateOperator op, % const double value,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ static MagickPixelPacket **DestroyPixelThreadSet(const Image *images, MagickPixelPacket **pixels) { register ssize_t i; size_t rows; assert(pixels != (MagickPixelPacket **) NULL); rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); for (i=0; i < (ssize_t) rows; i++) if (pixels[i] != (MagickPixelPacket *) NULL) pixels[i]=(MagickPixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(MagickPixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static MagickPixelPacket **AcquirePixelThreadSet(const Image *images) { const Image *next; MagickPixelPacket **pixels; register ssize_t i, j; size_t columns, rows; rows=MagickMax(GetImageListLength(images), (size_t) GetMagickResourceLimit(ThreadResource)); pixels=(MagickPixelPacket **) AcquireQuantumMemory(rows,sizeof(*pixels)); if (pixels == (MagickPixelPacket **) NULL) return((MagickPixelPacket **) NULL); (void) memset(pixels,0,rows*sizeof(*pixels)); columns=GetImageListLength(images); for (next=images; next != (Image *) NULL; next=next->next) columns=MagickMax(next->columns,columns); for (i=0; i < (ssize_t) rows; i++) { pixels[i]=(MagickPixelPacket *) AcquireQuantumMemory(columns, sizeof(**pixels)); if (pixels[i] == (MagickPixelPacket *) NULL) return(DestroyPixelThreadSet(images,pixels)); for (j=0; j < (ssize_t) columns; j++) GetMagickPixelPacket(images,&pixels[i][j]); } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const MagickPixelPacket *color_1, *color_2; int intensity; color_1=(const MagickPixelPacket *) x; color_2=(const MagickPixelPacket *) y; intensity=(int) MagickPixelIntensity(color_2)-(int) MagickPixelIntensity(color_1); return(intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickRealType ApplyEvaluateOperator(RandomInfo *random_info, const Quantum pixel,const MagickEvaluateOperator op, const MagickRealType value) { MagickRealType result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(MagickRealType) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() which returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(MagickRealType) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(MagickRealType) (QuantumRange*exp((double) (value*QuantumScale* pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, ImpulseNoise,value); break; } case LaplacianNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(MagickRealType) (QuantumRange*log((double) (QuantumScale*value* pixel+1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(MagickRealType) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MedianEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case MinEvaluateOperator: { result=(MagickRealType) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(MagickRealType) (value*pixel); break; } case OrEvaluateOperator: { result=(MagickRealType) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, PoissonNoise,value); break; } case PowEvaluateOperator: { result=(MagickRealType) (QuantumRange*pow((double) (QuantumScale*pixel), (double) value)); break; } case RightShiftEvaluateOperator: { result=(MagickRealType) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(MagickRealType) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(MagickRealType) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(MagickRealType) (pixel-value); break; } case SumEvaluateOperator: { result=(MagickRealType) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(MagickRealType) (((MagickRealType) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(MagickRealType) GenerateDifferentialNoise(random_info,pixel, UniformNoise,value); break; } case XorEvaluateOperator: { result=(MagickRealType) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } static Image *AcquireImageCanvas(const Image *images,ExceptionInfo *exception) { const Image *p, *q; size_t columns, number_channels, rows; q=images; columns=images->columns; rows=images->rows; number_channels=0; for (p=images; p != (Image *) NULL; p=p->next) { size_t channels; channels=3; if (p->matte != MagickFalse) channels+=1; if (p->colorspace == CMYKColorspace) channels+=1; if (channels > number_channels) { number_channels=channels; q=p; } if (p->columns > columns) columns=p->columns; if (p->rows > rows) rows=p->rows; } return(CloneImage(q,columns,rows,MagickTrue,exception)); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { MagickBooleanType status; status=EvaluateImageChannel(image,CompositeChannels,op,value,exception); return(status); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict evaluate_pixels, zero; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; number_images=GetImageListLength(images); GetMagickPixelPacket(images,&zero); random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) number_images; i++) evaluate_pixel[i]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); evaluate_pixel[i].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),op,evaluate_pixel[i].red); evaluate_pixel[i].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),op,evaluate_pixel[i].green); evaluate_pixel[i].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),op,evaluate_pixel[i].blue); evaluate_pixel[i].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),op,evaluate_pixel[i].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[i].index=ApplyEvaluateOperator(random_info[id], *indexes,op,evaluate_pixel[i].index); image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); SetPixelRed(q,ClampToQuantum(evaluate_pixel[i/2].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[i/2].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[i/2].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[i/2].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+i,ClampToQuantum( evaluate_pixel[i/2].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(images,EvaluateImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict evaluate_indexes; register ssize_t i, x; register MagickPixelPacket *evaluate_pixel; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } evaluate_indexes=GetCacheViewAuthenticIndexQueue(evaluate_view); evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) evaluate_pixel[x]=zero; next=images; for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=ApplyEvaluateOperator(random_info[id], GetPixelRed(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].red); evaluate_pixel[x].green=ApplyEvaluateOperator(random_info[id], GetPixelGreen(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].green); evaluate_pixel[x].blue=ApplyEvaluateOperator(random_info[id], GetPixelBlue(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].blue); evaluate_pixel[x].opacity=ApplyEvaluateOperator(random_info[id], GetPixelAlpha(p),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].opacity); if (image->colorspace == CMYKColorspace) evaluate_pixel[x].index=ApplyEvaluateOperator(random_info[id], GetPixelIndex(indexes+x),i == 0 ? AddEvaluateOperator : op, evaluate_pixel[x].index); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } if (op == MeanEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red/=number_images; evaluate_pixel[x].green/=number_images; evaluate_pixel[x].blue/=number_images; evaluate_pixel[x].opacity/=number_images; evaluate_pixel[x].index/=number_images; } if (op == RootMeanSquareEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { evaluate_pixel[x].red=sqrt((double) evaluate_pixel[x].red/ number_images); evaluate_pixel[x].green=sqrt((double) evaluate_pixel[x].green/ number_images); evaluate_pixel[x].blue=sqrt((double) evaluate_pixel[x].blue/ number_images); evaluate_pixel[x].opacity=sqrt((double) evaluate_pixel[x].opacity/ number_images); evaluate_pixel[x].index=sqrt((double) evaluate_pixel[x].index/ number_images); } if (op == MultiplyEvaluateOperator) for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) { evaluate_pixel[x].red*=(MagickRealType) QuantumScale; evaluate_pixel[x].green*=(MagickRealType) QuantumScale; evaluate_pixel[x].blue*=(MagickRealType) QuantumScale; evaluate_pixel[x].opacity*=(MagickRealType) QuantumScale; evaluate_pixel[x].index*=(MagickRealType) QuantumScale; } } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(evaluate_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(evaluate_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(evaluate_pixel[x].blue)); SetPixelAlpha(q,ClampToQuantum(evaluate_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(evaluate_indexes+x,ClampToQuantum( evaluate_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(images,evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImageChannel(Image *image, const ChannelType channel,const MagickEvaluateOperator op,const double value, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType result; if ((channel & RedChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelRed(q),op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelRed(q,ClampToQuantum(result)); } if ((channel & GreenChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelGreen(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelGreen(q,ClampToQuantum(result)); } if ((channel & BlueChannel) != 0) { result=ApplyEvaluateOperator(random_info[id],GetPixelBlue(q),op, value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelBlue(q,ClampToQuantum(result)); } if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) { result=ApplyEvaluateOperator(random_info[id],GetPixelOpacity(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelOpacity(q,ClampToQuantum(result)); } else { result=ApplyEvaluateOperator(random_info[id],GetPixelAlpha(q), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelAlpha(q,ClampToQuantum(result)); } } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) { result=ApplyEvaluateOperator(random_info[id],GetPixelIndex(indexes+x), op,value); if (op == MeanEvaluateOperator) result/=2.0; SetPixelIndex(indexes+x,ClampToQuantum(result)); } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImageChannel method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % MagickBooleanType FunctionImageChannel(Image *image, % const ChannelType channel,const MagickFunction function, % const ssize_t number_parameters,const double *argument, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { MagickRealType result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* * Polynomial * Parameters: polynomial constants, highest to lowest order * For example: c0*x^3 + c1*x^2 + c2*x + c3 */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel + parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { /* Sinusoid Function * Parameters: Freq, Phase, Ampl, bias */ double freq,phase,ampl,bias; freq = ( number_parameters >= 1 ) ? parameters[0] : 1.0; phase = ( number_parameters >= 2 ) ? parameters[1] : 0.0; ampl = ( number_parameters >= 3 ) ? parameters[2] : 0.5; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (QuantumRange*(ampl*sin((double) (2.0*MagickPI* (freq*QuantumScale*pixel + phase/360.0) )) + bias ) ); break; } case ArcsinFunction: { /* Arcsin Function (peged at range limits for invalid results) * Parameters: Width, Center, Range, Bias */ double width,range,center,bias; width = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result = 2.0/width*(QuantumScale*pixel - center); if ( result <= -1.0 ) result = bias - range/2.0; else if ( result >= 1.0 ) result = bias + range/2.0; else result=(MagickRealType) (range/MagickPI*asin((double) result)+bias); result *= QuantumRange; break; } case ArctanFunction: { /* Arctan Function * Parameters: Slope, Center, Range, Bias */ double slope,range,center,bias; slope = ( number_parameters >= 1 ) ? parameters[0] : 1.0; center = ( number_parameters >= 2 ) ? parameters[1] : 0.5; range = ( number_parameters >= 3 ) ? parameters[2] : 1.0; bias = ( number_parameters >= 4 ) ? parameters[3] : 0.5; result=(MagickRealType) (MagickPI*slope*(QuantumScale*pixel-center)); result=(MagickRealType) (QuantumRange*(range/MagickPI*atan((double) result) + bias ) ); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { MagickBooleanType status; status=FunctionImageChannel(image,CompositeChannels,function, number_parameters,parameters,exception); return(status); } MagickExport MagickBooleanType FunctionImageChannel(Image *image, const ChannelType channel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } #if defined(MAGICKCORE_OPENCL_SUPPORT) status=AccelerateFunctionImage(image,channel,function,number_parameters, parameters,exception); if (status != MagickFalse) return(status); #endif status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) SetPixelRed(q,ApplyFunction(GetPixelRed(q),function, number_parameters,parameters,exception)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ApplyFunction(GetPixelGreen(q),function, number_parameters,parameters,exception)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ApplyFunction(GetPixelBlue(q),function, number_parameters,parameters,exception)); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) SetPixelOpacity(q,ApplyFunction(GetPixelOpacity(q),function, number_parameters,parameters,exception)); else SetPixelAlpha(q,ApplyFunction((Quantum) GetPixelAlpha(q),function, number_parameters,parameters,exception)); } if (((channel & IndexChannel) != 0) && (indexes != (IndexPacket *) NULL)) SetPixelIndex(indexes+x,ApplyFunction(GetPixelIndex(indexes+x),function, number_parameters,parameters,exception)); q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelEntropy() returns the entropy of one or more image channels. % % The format of the GetImageChannelEntropy method is: % % MagickBooleanType GetImageChannelEntropy(const Image *image, % const ChannelType channel,double *entropy,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelEntropy(image,CompositeChannels,entropy,exception); return(status); } MagickExport MagickBooleanType GetImageChannelEntropy(const Image *image, const ChannelType channel,double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].entropy=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[RedChannel].entropy; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[GreenChannel].entropy; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlueChannel].entropy; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[OpacityChannel].entropy; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].entropy+= channel_statistics[BlackChannel].entropy; channels++; } channel_statistics[CompositeChannels].entropy/=channels; *entropy=channel_statistics[CompositeChannels].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelExtrema() returns the extrema of one or more image channels. % % The format of the GetImageChannelExtrema method is: % % MagickBooleanType GetImageChannelExtrema(const Image *image, % const ChannelType channel,size_t *minima,size_t *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelExtrema(image,CompositeChannels,minima,maxima, exception); return(status); } MagickExport MagickBooleanType GetImageChannelExtrema(const Image *image, const ChannelType channel,size_t *minima,size_t *maxima, ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageChannelRange(image,channel,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelKurtosis() returns the kurtosis and skewness of one or more % image channels. % % The format of the GetImageChannelKurtosis method is: % % MagickBooleanType GetImageChannelKurtosis(const Image *image, % const ChannelType channel,double *kurtosis,double *skewness, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelKurtosis(image,CompositeChannels,kurtosis,skewness, exception); return(status); } MagickExport MagickBooleanType GetImageChannelKurtosis(const Image *image, const ChannelType channel,double *kurtosis,double *skewness, ExceptionInfo *exception) { double area, mean, standard_deviation, sum_squares, sum_cubes, sum_fourth_power; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *kurtosis=0.0; *skewness=0.0; area=0.0; mean=0.0; standard_deviation=0.0; sum_squares=0.0; sum_cubes=0.0; sum_fourth_power=0.0; for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) { mean+=GetPixelRed(p); sum_squares+=(double) GetPixelRed(p)*GetPixelRed(p); sum_cubes+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)* GetPixelRed(p)*GetPixelRed(p); area++; } if ((channel & GreenChannel) != 0) { mean+=GetPixelGreen(p); sum_squares+=(double) GetPixelGreen(p)*GetPixelGreen(p); sum_cubes+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p); sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); area++; } if ((channel & BlueChannel) != 0) { mean+=GetPixelBlue(p); sum_squares+=(double) GetPixelBlue(p)*GetPixelBlue(p); sum_cubes+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); area++; } if ((channel & OpacityChannel) != 0) { mean+=GetPixelAlpha(p); sum_squares+=(double) GetPixelOpacity(p)*GetPixelAlpha(p); sum_cubes+=(double) GetPixelOpacity(p)*GetPixelAlpha(p)* GetPixelAlpha(p); sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)* GetPixelAlpha(p)*GetPixelAlpha(p); area++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { double index; index=(double) GetPixelIndex(indexes+x); mean+=index; sum_squares+=index*index; sum_cubes+=index*index*index; sum_fourth_power+=index*index*index*index; area++; } p++; } } if (y < (ssize_t) image->rows) return(MagickFalse); if (area != 0.0) { mean/=area; sum_squares/=area; sum_cubes/=area; sum_fourth_power/=area; } standard_deviation=sqrt(sum_squares-(mean*mean)); if (standard_deviation != 0.0) { *kurtosis=sum_fourth_power-4.0*mean*sum_cubes+6.0*mean*mean*sum_squares- 3.0*mean*mean*mean*mean; *kurtosis/=standard_deviation*standard_deviation*standard_deviation* standard_deviation; *kurtosis-=3.0; *skewness=sum_cubes-3.0*mean*sum_squares+2.0*mean*mean*mean; *skewness/=standard_deviation*standard_deviation*standard_deviation; } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMean() returns the mean and standard deviation of one or more % image channels. % % The format of the GetImageChannelMean method is: % % MagickBooleanType GetImageChannelMean(const Image *image, % const ChannelType channel,double *mean,double *standard_deviation, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { MagickBooleanType status; status=GetImageChannelMean(image,CompositeChannels,mean,standard_deviation, exception); return(status); } MagickExport MagickBooleanType GetImageChannelMean(const Image *image, const ChannelType channel,double *mean,double *standard_deviation, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; size_t channels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageChannelStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); channels=0; channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; if ((channel & RedChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[RedChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[RedChannel].standard_deviation; channels++; } if ((channel & GreenChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[GreenChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[GreenChannel].standard_deviation; channels++; } if ((channel & BlueChannel) != 0) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlueChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[BlueChannel].standard_deviation; channels++; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { channel_statistics[CompositeChannels].mean+= (QuantumRange-channel_statistics[OpacityChannel].mean); channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[OpacityChannel].standard_deviation; channels++; } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { channel_statistics[CompositeChannels].mean+= channel_statistics[BlackChannel].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[CompositeChannels].standard_deviation; channels++; } channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].standard_deviation/=channels; *mean=channel_statistics[CompositeChannels].mean; *standard_deviation=channel_statistics[CompositeChannels].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageChannelMoments method is: % % ChannelMoments *GetImageChannelMoments(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelMoments *GetImageChannelMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 ChannelMoments *channel_moments; double M00[CompositeChannels+1], M01[CompositeChannels+1], M02[CompositeChannels+1], M03[CompositeChannels+1], M10[CompositeChannels+1], M11[CompositeChannels+1], M12[CompositeChannels+1], M20[CompositeChannels+1], M21[CompositeChannels+1], M22[CompositeChannels+1], M30[CompositeChannels+1]; MagickPixelPacket pixel; PointInfo centroid[CompositeChannels+1]; ssize_t channel, channels, y; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_moments=(ChannelMoments *) AcquireQuantumMemory(length, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) memset(channel_moments,0,length*sizeof(*channel_moments)); (void) memset(centroid,0,sizeof(centroid)); (void) memset(M00,0,sizeof(M00)); (void) memset(M01,0,sizeof(M01)); (void) memset(M02,0,sizeof(M02)); (void) memset(M03,0,sizeof(M03)); (void) memset(M10,0,sizeof(M10)); (void) memset(M11,0,sizeof(M11)); (void) memset(M12,0,sizeof(M12)); (void) memset(M20,0,sizeof(M20)); (void) memset(M21,0,sizeof(M21)); (void) memset(M22,0,sizeof(M22)); (void) memset(M30,0,sizeof(M30)); GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M00[RedChannel]+=QuantumScale*pixel.red; M10[RedChannel]+=x*QuantumScale*pixel.red; M01[RedChannel]+=y*QuantumScale*pixel.red; M00[GreenChannel]+=QuantumScale*pixel.green; M10[GreenChannel]+=x*QuantumScale*pixel.green; M01[GreenChannel]+=y*QuantumScale*pixel.green; M00[BlueChannel]+=QuantumScale*pixel.blue; M10[BlueChannel]+=x*QuantumScale*pixel.blue; M01[BlueChannel]+=y*QuantumScale*pixel.blue; if (image->matte != MagickFalse) { M00[OpacityChannel]+=QuantumScale*pixel.opacity; M10[OpacityChannel]+=x*QuantumScale*pixel.opacity; M01[OpacityChannel]+=y*QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M00[IndexChannel]+=QuantumScale*pixel.index; M10[IndexChannel]+=x*QuantumScale*pixel.index; M01[IndexChannel]+=y*QuantumScale*pixel.index; } p++; } } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute the image moments. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); M11[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M20[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*QuantumScale*pixel.red; M02[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M21[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M12[RedChannel]+=(x-centroid[RedChannel].x)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M22[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*QuantumScale*pixel.red; M30[RedChannel]+=(x-centroid[RedChannel].x)*(x- centroid[RedChannel].x)*(x-centroid[RedChannel].x)*QuantumScale* pixel.red; M03[RedChannel]+=(y-centroid[RedChannel].y)*(y- centroid[RedChannel].y)*(y-centroid[RedChannel].y)*QuantumScale* pixel.red; M11[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M20[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*QuantumScale*pixel.green; M02[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M21[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M12[GreenChannel]+=(x-centroid[GreenChannel].x)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M22[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*QuantumScale*pixel.green; M30[GreenChannel]+=(x-centroid[GreenChannel].x)*(x- centroid[GreenChannel].x)*(x-centroid[GreenChannel].x)*QuantumScale* pixel.green; M03[GreenChannel]+=(y-centroid[GreenChannel].y)*(y- centroid[GreenChannel].y)*(y-centroid[GreenChannel].y)*QuantumScale* pixel.green; M11[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M20[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*QuantumScale*pixel.blue; M02[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M21[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M12[BlueChannel]+=(x-centroid[BlueChannel].x)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; M22[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*QuantumScale*pixel.blue; M30[BlueChannel]+=(x-centroid[BlueChannel].x)*(x- centroid[BlueChannel].x)*(x-centroid[BlueChannel].x)*QuantumScale* pixel.blue; M03[BlueChannel]+=(y-centroid[BlueChannel].y)*(y- centroid[BlueChannel].y)*(y-centroid[BlueChannel].y)*QuantumScale* pixel.blue; if (image->matte != MagickFalse) { M11[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M20[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*QuantumScale*pixel.opacity; M02[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M21[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M12[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; M22[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*QuantumScale*pixel.opacity; M30[OpacityChannel]+=(x-centroid[OpacityChannel].x)*(x- centroid[OpacityChannel].x)*(x-centroid[OpacityChannel].x)* QuantumScale*pixel.opacity; M03[OpacityChannel]+=(y-centroid[OpacityChannel].y)*(y- centroid[OpacityChannel].y)*(y-centroid[OpacityChannel].y)* QuantumScale*pixel.opacity; } if (image->colorspace == CMYKColorspace) { M11[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M20[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*QuantumScale*pixel.index; M02[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M21[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M12[IndexChannel]+=(x-centroid[IndexChannel].x)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; M22[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*QuantumScale*pixel.index; M30[IndexChannel]+=(x-centroid[IndexChannel].x)*(x- centroid[IndexChannel].x)*(x-centroid[IndexChannel].x)* QuantumScale*pixel.index; M03[IndexChannel]+=(y-centroid[IndexChannel].y)*(y- centroid[IndexChannel].y)*(y-centroid[IndexChannel].y)* QuantumScale*pixel.index; } p++; } } channels=3; M00[CompositeChannels]+=(M00[RedChannel]+M00[GreenChannel]+M00[BlueChannel]); M01[CompositeChannels]+=(M01[RedChannel]+M01[GreenChannel]+M01[BlueChannel]); M02[CompositeChannels]+=(M02[RedChannel]+M02[GreenChannel]+M02[BlueChannel]); M03[CompositeChannels]+=(M03[RedChannel]+M03[GreenChannel]+M03[BlueChannel]); M10[CompositeChannels]+=(M10[RedChannel]+M10[GreenChannel]+M10[BlueChannel]); M11[CompositeChannels]+=(M11[RedChannel]+M11[GreenChannel]+M11[BlueChannel]); M12[CompositeChannels]+=(M12[RedChannel]+M12[GreenChannel]+M12[BlueChannel]); M20[CompositeChannels]+=(M20[RedChannel]+M20[GreenChannel]+M20[BlueChannel]); M21[CompositeChannels]+=(M21[RedChannel]+M21[GreenChannel]+M21[BlueChannel]); M22[CompositeChannels]+=(M22[RedChannel]+M22[GreenChannel]+M22[BlueChannel]); M30[CompositeChannels]+=(M30[RedChannel]+M30[GreenChannel]+M30[BlueChannel]); if (image->matte != MagickFalse) { channels+=1; M00[CompositeChannels]+=M00[OpacityChannel]; M01[CompositeChannels]+=M01[OpacityChannel]; M02[CompositeChannels]+=M02[OpacityChannel]; M03[CompositeChannels]+=M03[OpacityChannel]; M10[CompositeChannels]+=M10[OpacityChannel]; M11[CompositeChannels]+=M11[OpacityChannel]; M12[CompositeChannels]+=M12[OpacityChannel]; M20[CompositeChannels]+=M20[OpacityChannel]; M21[CompositeChannels]+=M21[OpacityChannel]; M22[CompositeChannels]+=M22[OpacityChannel]; M30[CompositeChannels]+=M30[OpacityChannel]; } if (image->colorspace == CMYKColorspace) { channels+=1; M00[CompositeChannels]+=M00[IndexChannel]; M01[CompositeChannels]+=M01[IndexChannel]; M02[CompositeChannels]+=M02[IndexChannel]; M03[CompositeChannels]+=M03[IndexChannel]; M10[CompositeChannels]+=M10[IndexChannel]; M11[CompositeChannels]+=M11[IndexChannel]; M12[CompositeChannels]+=M12[IndexChannel]; M20[CompositeChannels]+=M20[IndexChannel]; M21[CompositeChannels]+=M21[IndexChannel]; M22[CompositeChannels]+=M22[IndexChannel]; M30[CompositeChannels]+=M30[IndexChannel]; } M00[CompositeChannels]/=(double) channels; M01[CompositeChannels]/=(double) channels; M02[CompositeChannels]/=(double) channels; M03[CompositeChannels]/=(double) channels; M10[CompositeChannels]/=(double) channels; M11[CompositeChannels]/=(double) channels; M12[CompositeChannels]/=(double) channels; M20[CompositeChannels]/=(double) channels; M21[CompositeChannels]/=(double) channels; M22[CompositeChannels]/=(double) channels; M30[CompositeChannels]/=(double) channels; for (channel=0; channel <= CompositeChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= CompositeChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } for (channel=0; channel <= CompositeChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].I[0]=M20[channel]+M02[channel]; channel_moments[channel].I[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].I[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].I[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].I[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].I[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].I[7]=M11[channel]*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelPerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImageChannelPerceptualHash method is: % % ChannelPerceptualHash *GetImageChannelPerceptualHash(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImageChannelPerceptualHash( const Image *image,ExceptionInfo *exception) { ChannelMoments *moments; ChannelPerceptualHash *perceptual_hash; Image *hash_image; MagickBooleanType status; register ssize_t i; ssize_t channel; /* Blur then transform to sRGB colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) return((ChannelPerceptualHash *) NULL); hash_image->depth=8; status=TransformImageColorspace(hash_image,sRGBColorspace); if (status == MagickFalse) return((ChannelPerceptualHash *) NULL); moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) return((ChannelPerceptualHash *) NULL); perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( CompositeChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].P[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); /* Blur then transform to HCLp colorspace. */ hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } hash_image->depth=8; status=TransformImageColorspace(hash_image,HCLpColorspace); if (status == MagickFalse) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } moments=GetImageChannelMoments(hash_image,exception); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) { perceptual_hash=(ChannelPerceptualHash *) RelinquishMagickMemory( perceptual_hash); return((ChannelPerceptualHash *) NULL); } for (channel=0; channel <= CompositeChannels; channel++) for (i=0; i < MaximumNumberOfImageMoments; i++) perceptual_hash[channel].Q[i]=(-MagickLog10(moments[channel].I[i])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelRange() returns the range of one or more image channels. % % The format of the GetImageChannelRange method is: % % MagickBooleanType GetImageChannelRange(const Image *image, % const ChannelType channel,double *minima,double *maxima, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image, double *minima,double *maxima,ExceptionInfo *exception) { return(GetImageChannelRange(image,CompositeChannels,minima,maxima,exception)); } MagickExport MagickBooleanType GetImageChannelRange(const Image *image, const ChannelType channel,double *minima,double *maxima, ExceptionInfo *exception) { MagickPixelPacket pixel; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); *maxima=(-MagickMaximumValue); *minima=MagickMaximumValue; GetMagickPixelPacket(image,&pixel); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { SetMagickPixelPacket(image,p,indexes+x,&pixel); if ((channel & RedChannel) != 0) { if (pixel.red < *minima) *minima=(double) pixel.red; if (pixel.red > *maxima) *maxima=(double) pixel.red; } if ((channel & GreenChannel) != 0) { if (pixel.green < *minima) *minima=(double) pixel.green; if (pixel.green > *maxima) *maxima=(double) pixel.green; } if ((channel & BlueChannel) != 0) { if (pixel.blue < *minima) *minima=(double) pixel.blue; if (pixel.blue > *maxima) *maxima=(double) pixel.blue; } if (((channel & OpacityChannel) != 0) && (image->matte != MagickFalse)) { if ((QuantumRange-pixel.opacity) < *minima) *minima=(double) (QuantumRange-pixel.opacity); if ((QuantumRange-pixel.opacity) > *maxima) *maxima=(double) (QuantumRange-pixel.opacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((double) pixel.index < *minima) *minima=(double) pixel.index; if ((double) pixel.index > *maxima) *maxima=(double) pixel.index; } p++; } } return(y == (ssize_t) image->rows ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageChannelStatistics() returns statistics for each channel in the % image. The statistics include the channel depth, its minima, maxima, mean, % standard deviation, kurtosis and skewness. You can access the red channel % mean, for example, like this: % % channel_statistics=GetImageChannelStatistics(image,exception); % red_mean=channel_statistics[RedChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageChannelStatistics method is: % % ChannelStatistics *GetImageChannelStatistics(const Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport ChannelStatistics *GetImageChannelStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, standard_deviation; MagickPixelPacket number_bins, *histogram; QuantumAny range; register ssize_t i; size_t channels, depth, length; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=CompositeChannels+1UL; channel_statistics=(ChannelStatistics *) AcquireQuantumMemory(length, sizeof(*channel_statistics)); histogram=(MagickPixelPacket *) AcquireQuantumMemory(MaxMap+1U, sizeof(*histogram)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (MagickPixelPacket *) NULL)) { if (histogram != (MagickPixelPacket *) NULL) histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) memset(channel_statistics,0,length* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) CompositeChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) memset(histogram,0,(MaxMap+1U)*sizeof(*histogram)); (void) memset(&number_bins,0,sizeof(number_bins)); for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; ) { if (channel_statistics[RedChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[RedChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelRed(p),range) == MagickFalse) { channel_statistics[RedChannel].depth++; continue; } } if (channel_statistics[GreenChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[GreenChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelGreen(p),range) == MagickFalse) { channel_statistics[GreenChannel].depth++; continue; } } if (channel_statistics[BlueChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlueChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelBlue(p),range) == MagickFalse) { channel_statistics[BlueChannel].depth++; continue; } } if (image->matte != MagickFalse) { if (channel_statistics[OpacityChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[OpacityChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelAlpha(p),range) == MagickFalse) { channel_statistics[OpacityChannel].depth++; continue; } } } if (image->colorspace == CMYKColorspace) { if (channel_statistics[BlackChannel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[BlackChannel].depth; range=GetQuantumRange(depth); if (IsPixelAtDepth(GetPixelIndex(indexes+x),range) == MagickFalse) { channel_statistics[BlackChannel].depth++; continue; } } } if ((double) GetPixelRed(p) < channel_statistics[RedChannel].minima) channel_statistics[RedChannel].minima=(double) GetPixelRed(p); if ((double) GetPixelRed(p) > channel_statistics[RedChannel].maxima) channel_statistics[RedChannel].maxima=(double) GetPixelRed(p); channel_statistics[RedChannel].sum+=GetPixelRed(p); channel_statistics[RedChannel].sum_squared+=(double) GetPixelRed(p)* GetPixelRed(p); channel_statistics[RedChannel].sum_cubed+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); channel_statistics[RedChannel].sum_fourth_power+=(double) GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p)*GetPixelRed(p); if ((double) GetPixelGreen(p) < channel_statistics[GreenChannel].minima) channel_statistics[GreenChannel].minima=(double) GetPixelGreen(p); if ((double) GetPixelGreen(p) > channel_statistics[GreenChannel].maxima) channel_statistics[GreenChannel].maxima=(double) GetPixelGreen(p); channel_statistics[GreenChannel].sum+=GetPixelGreen(p); channel_statistics[GreenChannel].sum_squared+=(double) GetPixelGreen(p)* GetPixelGreen(p); channel_statistics[GreenChannel].sum_cubed+=(double) GetPixelGreen(p)* GetPixelGreen(p)*GetPixelGreen(p); channel_statistics[GreenChannel].sum_fourth_power+=(double) GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p)*GetPixelGreen(p); if ((double) GetPixelBlue(p) < channel_statistics[BlueChannel].minima) channel_statistics[BlueChannel].minima=(double) GetPixelBlue(p); if ((double) GetPixelBlue(p) > channel_statistics[BlueChannel].maxima) channel_statistics[BlueChannel].maxima=(double) GetPixelBlue(p); channel_statistics[BlueChannel].sum+=GetPixelBlue(p); channel_statistics[BlueChannel].sum_squared+=(double) GetPixelBlue(p)* GetPixelBlue(p); channel_statistics[BlueChannel].sum_cubed+=(double) GetPixelBlue(p)* GetPixelBlue(p)*GetPixelBlue(p); channel_statistics[BlueChannel].sum_fourth_power+=(double) GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p)*GetPixelBlue(p); histogram[ScaleQuantumToMap(GetPixelRed(p))].red++; histogram[ScaleQuantumToMap(GetPixelGreen(p))].green++; histogram[ScaleQuantumToMap(GetPixelBlue(p))].blue++; if (image->matte != MagickFalse) { if ((double) GetPixelAlpha(p) < channel_statistics[OpacityChannel].minima) channel_statistics[OpacityChannel].minima=(double) GetPixelAlpha(p); if ((double) GetPixelAlpha(p) > channel_statistics[OpacityChannel].maxima) channel_statistics[OpacityChannel].maxima=(double) GetPixelAlpha(p); channel_statistics[OpacityChannel].sum+=GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_squared+=(double) GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_cubed+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); channel_statistics[OpacityChannel].sum_fourth_power+=(double) GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p)*GetPixelAlpha(p); histogram[ScaleQuantumToMap(GetPixelAlpha(p))].opacity++; } if (image->colorspace == CMYKColorspace) { if ((double) GetPixelIndex(indexes+x) < channel_statistics[BlackChannel].minima) channel_statistics[BlackChannel].minima=(double) GetPixelIndex(indexes+x); if ((double) GetPixelIndex(indexes+x) > channel_statistics[BlackChannel].maxima) channel_statistics[BlackChannel].maxima=(double) GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum+=GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_squared+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_cubed+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x); channel_statistics[BlackChannel].sum_fourth_power+=(double) GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x)* GetPixelIndex(indexes+x)*GetPixelIndex(indexes+x); histogram[ScaleQuantumToMap(GetPixelIndex(indexes+x))].index++; } x++; p++; } } for (i=0; i < (ssize_t) CompositeChannels; i++) { double area, mean, standard_deviation; /* Normalize pixel statistics. */ area=PerceptibleReciprocal((double) image->columns*image->rows); mean=channel_statistics[i].sum*area; channel_statistics[i].sum=mean; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=mean; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance-(mean*mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) (MaxMap+1U); i++) { if (histogram[i].red > 0.0) number_bins.red++; if (histogram[i].green > 0.0) number_bins.green++; if (histogram[i].blue > 0.0) number_bins.blue++; if ((image->matte != MagickFalse) && (histogram[i].opacity > 0.0)) number_bins.opacity++; if ((image->colorspace == CMYKColorspace) && (histogram[i].index > 0.0)) number_bins.index++; } area=PerceptibleReciprocal((double) image->columns*image->rows); for (i=0; i < (ssize_t) (MaxMap+1U); i++) { /* Compute pixel entropy. */ histogram[i].red*=area; channel_statistics[RedChannel].entropy+=-histogram[i].red* MagickLog10(histogram[i].red)* PerceptibleReciprocal(MagickLog10((double) number_bins.red)); histogram[i].green*=area; channel_statistics[GreenChannel].entropy+=-histogram[i].green* MagickLog10(histogram[i].green)* PerceptibleReciprocal(MagickLog10((double) number_bins.green)); histogram[i].blue*=area; channel_statistics[BlueChannel].entropy+=-histogram[i].blue* MagickLog10(histogram[i].blue)* PerceptibleReciprocal(MagickLog10((double) number_bins.blue)); if (image->matte != MagickFalse) { histogram[i].opacity*=area; channel_statistics[OpacityChannel].entropy+=-histogram[i].opacity* MagickLog10(histogram[i].opacity)* PerceptibleReciprocal(MagickLog10((double) number_bins.opacity)); } if (image->colorspace == CMYKColorspace) { histogram[i].index*=area; channel_statistics[IndexChannel].entropy+=-histogram[i].index* MagickLog10(histogram[i].index)* PerceptibleReciprocal(MagickLog10((double) number_bins.index)); } } /* Compute overall statistics. */ for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].depth=(size_t) EvaluateMax((double) channel_statistics[CompositeChannels].depth,(double) channel_statistics[i].depth); channel_statistics[CompositeChannels].minima=MagickMin( channel_statistics[CompositeChannels].minima, channel_statistics[i].minima); channel_statistics[CompositeChannels].maxima=EvaluateMax( channel_statistics[CompositeChannels].maxima, channel_statistics[i].maxima); channel_statistics[CompositeChannels].sum+=channel_statistics[i].sum; channel_statistics[CompositeChannels].sum_squared+= channel_statistics[i].sum_squared; channel_statistics[CompositeChannels].sum_cubed+= channel_statistics[i].sum_cubed; channel_statistics[CompositeChannels].sum_fourth_power+= channel_statistics[i].sum_fourth_power; channel_statistics[CompositeChannels].mean+=channel_statistics[i].mean; channel_statistics[CompositeChannels].variance+= channel_statistics[i].variance-channel_statistics[i].mean* channel_statistics[i].mean; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); area=PerceptibleReciprocal((double) image->columns*image->rows-1.0)* ((double) image->columns*image->rows); standard_deviation=sqrt(area*standard_deviation*standard_deviation); channel_statistics[CompositeChannels].standard_deviation=standard_deviation; channel_statistics[CompositeChannels].entropy+= channel_statistics[i].entropy; } channels=3; if (image->matte != MagickFalse) channels++; if (image->colorspace == CMYKColorspace) channels++; channel_statistics[CompositeChannels].sum/=channels; channel_statistics[CompositeChannels].sum_squared/=channels; channel_statistics[CompositeChannels].sum_cubed/=channels; channel_statistics[CompositeChannels].sum_fourth_power/=channels; channel_statistics[CompositeChannels].mean/=channels; channel_statistics[CompositeChannels].kurtosis/=channels; channel_statistics[CompositeChannels].skewness/=channels; channel_statistics[CompositeChannels].entropy/=channels; i=CompositeChannels; area=PerceptibleReciprocal((double) channels*image->columns*image->rows); channel_statistics[i].variance=channel_statistics[i].sum_squared; channel_statistics[i].mean=channel_statistics[i].sum; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal((double) channels* image->columns*image->rows-1.0)*channels*image->columns*image->rows* standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; for (i=0; i <= (ssize_t) CompositeChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } channel_statistics[CompositeChannels].mean=0.0; channel_statistics[CompositeChannels].standard_deviation=0.0; for (i=0; i < (ssize_t) CompositeChannels; i++) { channel_statistics[CompositeChannels].mean+= channel_statistics[i].mean; channel_statistics[CompositeChannels].standard_deviation+= channel_statistics[i].standard_deviation; } channel_statistics[CompositeChannels].mean/=(double) channels; channel_statistics[CompositeChannels].standard_deviation/=(double) channels; histogram=(MagickPixelPacket *) RelinquishMagickMemory(histogram); if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % Image *PolynomialImageChannel(const Image *images, % const size_t number_terms,const ChannelType channel, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o channel: the channel. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { Image *polynomial_image; polynomial_image=PolynomialImageChannel(images,DefaultChannels,number_terms, terms,exception); return(polynomial_image); } MagickExport Image *PolynomialImageChannel(const Image *images, const ChannelType channel,const size_t number_terms,const double *terms, ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket **magick_restrict polynomial_pixels, zero; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImageCanvas(images,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImage(image); return((Image *) NULL); } polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (MagickPixelPacket **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; GetMagickPixelPacket(images,&zero); polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict polynomial_indexes; register MagickPixelPacket *polynomial_pixel; register PixelPacket *magick_restrict q; register ssize_t i, x; size_t number_images; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } polynomial_indexes=GetCacheViewAuthenticIndexQueue(polynomial_view); polynomial_pixel=polynomial_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) polynomial_pixel[x]=zero; next=images; number_images=GetImageListLength(images); for (i=0; i < (ssize_t) number_images; i++) { register const IndexPacket *indexes; register const PixelPacket *p; if (i >= (ssize_t) number_terms) break; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { image_view=DestroyCacheView(image_view); break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { double coefficient, degree; coefficient=terms[i << 1]; degree=terms[(i << 1)+1]; if ((channel & RedChannel) != 0) polynomial_pixel[x].red+=coefficient*pow(QuantumScale*p->red,degree); if ((channel & GreenChannel) != 0) polynomial_pixel[x].green+=coefficient*pow(QuantumScale*p->green, degree); if ((channel & BlueChannel) != 0) polynomial_pixel[x].blue+=coefficient*pow(QuantumScale*p->blue, degree); if ((channel & OpacityChannel) != 0) polynomial_pixel[x].opacity+=coefficient*pow(QuantumScale* (QuantumRange-p->opacity),degree); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) polynomial_pixel[x].index+=coefficient*pow(QuantumScale*indexes[x], degree); p++; } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].red)); SetPixelGreen(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].green)); SetPixelBlue(q,ClampToQuantum(QuantumRange*polynomial_pixel[x].blue)); if (image->matte == MagickFalse) SetPixelOpacity(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); else SetPixelAlpha(q,ClampToQuantum(QuantumRange-QuantumRange* polynomial_pixel[x].opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(polynomial_indexes+x,ClampToQuantum(QuantumRange* polynomial_pixel[x].index)); q++; } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(images,polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % Image *StatisticImageChannel(const Image *image, % const ChannelType channel,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the image channel. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ #define ListChannels 5 typedef struct _ListNode { size_t next[9], count, signature; } ListNode; typedef struct _SkipList { ssize_t level; ListNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed, signature; SkipList lists[ListChannels]; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { register ssize_t i; if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); for (i=0; i < ListChannels; i++) if (pixel_list->lists[i].nodes != (ListNode *) NULL) pixel_list->lists[i].nodes=(ListNode *) RelinquishAlignedMemory( pixel_list->lists[i].nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; register ssize_t i; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) memset((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; for (i=0; i < ListChannels; i++) { pixel_list->lists[i].nodes=(ListNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->lists[i].nodes)); if (pixel_list->lists[i].nodes == (ListNode *) NULL) return(DestroyPixelList(pixel_list)); (void) memset(pixel_list->lists[i].nodes,0,65537UL* sizeof(*pixel_list->lists[i].nodes)); } pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) memset(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const ssize_t channel, const size_t color) { register SkipList *list; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ list=pixel_list->lists+channel; list->nodes[color].signature=pixel_list->signature; list->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=list->level; level >= 0; level--) { while (list->nodes[search].next[level] < color) search=list->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (list->level+2)) level=list->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > list->level) { list->level++; update[list->level]=65536UL; } /* Link the node into the skip-list. */ do { list->nodes[color].next[level]=list->nodes[update[level]].next[level]; list->nodes[update[level]].next[level]=color; } while (level-- > 0); } static void GetMaximumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, maximum; ssize_t count; unsigned short channels[ListChannels]; /* Find the maximum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; maximum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color > maximum) maximum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) maximum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMeanPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the mean value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMedianPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the median value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; do { color=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); channels[channel]=(unsigned short) color; } GetMagickPixelPacket((const Image *) NULL,pixel); pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetMinimumPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, minimum; ssize_t count; unsigned short channels[ListChannels]; /* Find the minimum value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; count=0; color=65536UL; minimum=list->nodes[color].next[0]; do { color=list->nodes[color].next[0]; if (color < minimum) minimum=color; count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) minimum; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetModePixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, max_count, mode; ssize_t count; unsigned short channels[5]; /* Make each pixel the 'predominant color' of the specified neighborhood. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; mode=color; max_count=list->nodes[mode].count; count=0; do { color=list->nodes[color].next[0]; if (list->nodes[color].count > max_count) { mode=color; max_count=list->nodes[mode].count; } count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); channels[channel]=(unsigned short) mode; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetNonpeakPixelList(PixelList *pixel_list,MagickPixelPacket *pixel) { register SkipList *list; register ssize_t channel; size_t color, next, previous; ssize_t count; unsigned short channels[5]; /* Finds the non peak value for each of the colors. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; next=list->nodes[color].next[0]; count=0; do { previous=color; color=next; next=list->nodes[color].next[0]; count+=list->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; channels[channel]=(unsigned short) color; } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetRootMeanSquarePixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the root mean square value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; do { color=list->nodes[color].next[0]; sum+=(MagickRealType) (list->nodes[color].count*color*color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static void GetStandardDeviationPixelList(PixelList *pixel_list, MagickPixelPacket *pixel) { MagickRealType sum, sum_squared; register SkipList *list; register ssize_t channel; size_t color; ssize_t count; unsigned short channels[ListChannels]; /* Find the standard-deviation value for each of the color. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=list->nodes[color].next[0]; sum+=(MagickRealType) list->nodes[color].count*color; for (i=0; i < (ssize_t) list->nodes[color].count; i++) sum_squared+=((MagickRealType) color)*((MagickRealType) color); count+=list->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; channels[channel]=(unsigned short) sqrt(sum_squared-(sum*sum)); } pixel->red=(MagickRealType) ScaleShortToQuantum(channels[0]); pixel->green=(MagickRealType) ScaleShortToQuantum(channels[1]); pixel->blue=(MagickRealType) ScaleShortToQuantum(channels[2]); pixel->opacity=(MagickRealType) ScaleShortToQuantum(channels[3]); pixel->index=(MagickRealType) ScaleShortToQuantum(channels[4]); } static inline void InsertPixelList(const Image *image,const PixelPacket *pixel, const IndexPacket *indexes,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(GetPixelRed(pixel)); signature=pixel_list->lists[0].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[0].nodes[index].count++; else AddNodePixelList(pixel_list,0,index); index=ScaleQuantumToShort(GetPixelGreen(pixel)); signature=pixel_list->lists[1].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[1].nodes[index].count++; else AddNodePixelList(pixel_list,1,index); index=ScaleQuantumToShort(GetPixelBlue(pixel)); signature=pixel_list->lists[2].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[2].nodes[index].count++; else AddNodePixelList(pixel_list,2,index); index=ScaleQuantumToShort(GetPixelOpacity(pixel)); signature=pixel_list->lists[3].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[3].nodes[index].count++; else AddNodePixelList(pixel_list,3,index); if (image->colorspace == CMYKColorspace) index=ScaleQuantumToShort(GetPixelIndex(indexes)); signature=pixel_list->lists[4].nodes[index].signature; if (signature == pixel_list->signature) pixel_list->lists[4].nodes[index].count++; else AddNodePixelList(pixel_list,4,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register ListNode *root; register SkipList *list; register ssize_t channel; /* Reset the skip-list. */ for (channel=0; channel < 5; channel++) { list=pixel_list->lists+channel; root=list->nodes+65536UL; list->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; } pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { Image *statistic_image; statistic_image=StatisticImageChannel(image,DefaultChannels,type,width, height,exception); return(statistic_image); } MagickExport Image *StatisticImageChannel(const Image *image, const ChannelType channel,const StatisticType type,const size_t width, const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; size_t neighbor_height, neighbor_width; ssize_t y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,0,0,MagickTrue,exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(statistic_image,DirectClass) == MagickFalse) { InheritException(exception,&statistic_image->exception); statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } neighbor_width=width == 0 ? GetOptimalKernelWidth2D((double) width,0.5) : width; neighbor_height=height == 0 ? GetOptimalKernelWidth2D((double) height,0.5) : height; pixel_list=AcquirePixelListThreadSet(neighbor_width,neighbor_height); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_image->rows; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict statistic_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) neighbor_width/2L),y- (ssize_t) (neighbor_height/2L),image->columns+neighbor_width, neighbor_height,exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); statistic_indexes=GetCacheViewAuthenticIndexQueue(statistic_view); for (x=0; x < (ssize_t) statistic_image->columns; x++) { MagickPixelPacket pixel; register const IndexPacket *magick_restrict s; register const PixelPacket *magick_restrict r; register ssize_t u, v; r=p; s=indexes+x; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) neighbor_height; v++) { for (u=0; u < (ssize_t) neighbor_width; u++) InsertPixelList(image,r+u,s+u,pixel_list[id]); r+=image->columns+neighbor_width; s+=image->columns+neighbor_width; } GetMagickPixelPacket(image,&pixel); SetMagickPixelPacket(image,p+neighbor_width*neighbor_height/2,indexes+x+ neighbor_width*neighbor_height/2,&pixel); switch (type) { case GradientStatistic: { MagickPixelPacket maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=pixel; pixel.red=MagickAbsoluteValue(maximum.red-minimum.red); pixel.green=MagickAbsoluteValue(maximum.green-minimum.green); pixel.blue=MagickAbsoluteValue(maximum.blue-minimum.blue); pixel.opacity=MagickAbsoluteValue(maximum.opacity-minimum.opacity); if (image->colorspace == CMYKColorspace) pixel.index=MagickAbsoluteValue(maximum.index-minimum.index); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } if ((channel & RedChannel) != 0) SetPixelRed(q,ClampToQuantum(pixel.red)); if ((channel & GreenChannel) != 0) SetPixelGreen(q,ClampToQuantum(pixel.green)); if ((channel & BlueChannel) != 0) SetPixelBlue(q,ClampToQuantum(pixel.blue)); if ((channel & OpacityChannel) != 0) SetPixelOpacity(q,ClampToQuantum(pixel.opacity)); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) SetPixelIndex(statistic_indexes+x,ClampToQuantum(pixel.index)); p++; q++; } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
./CrossVul/dataset_final_sorted/CWE-190/c/bad_4425_0
crossvul-cpp_data_good_3178_0
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * undo.c: multi level undo facility * * The saved lines are stored in a list of lists (one for each buffer): * * b_u_oldhead------------------------------------------------+ * | * V * +--------------+ +--------------+ +--------------+ * b_u_newhead--->| u_header | | u_header | | u_header | * | uh_next------>| uh_next------>| uh_next---->NULL * NULL<--------uh_prev |<---------uh_prev |<---------uh_prev | * | uh_entry | | uh_entry | | uh_entry | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ +--------------+ +--------------+ * | u_entry | | u_entry | | u_entry | * | ue_next | | ue_next | | ue_next | * +--------|-----+ +--------|-----+ +--------|-----+ * | | | * V V V * +--------------+ NULL NULL * | u_entry | * | ue_next | * +--------|-----+ * | * V * etc. * * Each u_entry list contains the information for one undo or redo. * curbuf->b_u_curhead points to the header of the last undo (the next redo), * or is NULL if nothing has been undone (end of the branch). * * For keeping alternate undo/redo branches the uh_alt field is used. Thus at * each point in the list a branch may appear for an alternate to redo. The * uh_seq field is numbered sequentially to be able to find a newer or older * branch. * * +---------------+ +---------------+ * b_u_oldhead --->| u_header | | u_header | * | uh_alt_next ---->| uh_alt_next ----> NULL * NULL <----- uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next | | uh_alt_next | * b_u_newhead --->| uh_alt_prev | | uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * V V * NULL +---------------+ +---------------+ * | u_header | | u_header | * | uh_alt_next ---->| uh_alt_next | * | uh_alt_prev |<------ uh_alt_prev | * | uh_prev | | uh_prev | * +-----|---------+ +-----|---------+ * | | * etc. etc. * * * All data is allocated and will all be freed when the buffer is unloaded. */ /* Uncomment the next line for including the u_check() function. This warns * for errors in the debug information. */ /* #define U_DEBUG 1 */ #define UH_MAGIC 0x18dade /* value for uh_magic when in use */ #define UE_MAGIC 0xabc123 /* value for ue_magic when in use */ /* Size of buffer used for encryption. */ #define CRYPT_BUF_SIZE 8192 #include "vim.h" /* Structure passed around between functions. * Avoids passing cryptstate_T when encryption not available. */ typedef struct { buf_T *bi_buf; FILE *bi_fp; #ifdef FEAT_CRYPT cryptstate_T *bi_state; char_u *bi_buffer; /* CRYPT_BUF_SIZE, NULL when not buffering */ size_t bi_used; /* bytes written to/read from bi_buffer */ size_t bi_avail; /* bytes available in bi_buffer */ #endif } bufinfo_T; static long get_undolevel(void); static void u_unch_branch(u_header_T *uhp); static u_entry_T *u_get_headentry(void); static void u_getbot(void); static void u_doit(int count); static void u_undoredo(int undo); static void u_undo_end(int did_undo, int absolute); static void u_add_time(char_u *buf, size_t buflen, time_t tt); static void u_freeheader(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freebranch(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentries(buf_T *buf, u_header_T *uhp, u_header_T **uhpp); static void u_freeentry(u_entry_T *, long); #ifdef FEAT_PERSISTENT_UNDO static void corruption_error(char *mesg, char_u *file_name); static void u_free_uhp(u_header_T *uhp); static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len); # ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi); # endif static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len); static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len); static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp); static int undo_read_4c(bufinfo_T *bi); static int undo_read_2c(bufinfo_T *bi); static int undo_read_byte(bufinfo_T *bi); static time_t undo_read_time(bufinfo_T *bi); static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size); static char_u *read_string_decrypt(bufinfo_T *bi, int len); static int serialize_header(bufinfo_T *bi, char_u *hash); static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp); static u_header_T *unserialize_uhp(bufinfo_T *bi, char_u *file_name); static int serialize_uep(bufinfo_T *bi, u_entry_T *uep); static u_entry_T *unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name); static void serialize_pos(bufinfo_T *bi, pos_T pos); static void unserialize_pos(bufinfo_T *bi, pos_T *pos); static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info); #endif #define U_ALLOC_LINE(size) lalloc((long_u)(size), FALSE) static char_u *u_save_line(linenr_T); /* used in undo_end() to report number of added and deleted lines */ static long u_newcount, u_oldcount; /* * When 'u' flag included in 'cpoptions', we behave like vi. Need to remember * the action that "u" should do. */ static int undo_undoes = FALSE; static int lastmark = 0; #if defined(U_DEBUG) || defined(PROTO) /* * Check the undo structures for being valid. Print a warning when something * looks wrong. */ static int seen_b_u_curhead; static int seen_b_u_newhead; static int header_count; static void u_check_tree(u_header_T *uhp, u_header_T *exp_uh_next, u_header_T *exp_uh_alt_prev) { u_entry_T *uep; if (uhp == NULL) return; ++header_count; if (uhp == curbuf->b_u_curhead && ++seen_b_u_curhead > 1) { EMSG("b_u_curhead found twice (looping?)"); return; } if (uhp == curbuf->b_u_newhead && ++seen_b_u_newhead > 1) { EMSG("b_u_newhead found twice (looping?)"); return; } if (uhp->uh_magic != UH_MAGIC) EMSG("uh_magic wrong (may be using freed memory)"); else { /* Check pointers back are correct. */ if (uhp->uh_next.ptr != exp_uh_next) { EMSG("uh_next wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_next, uhp->uh_next.ptr); } if (uhp->uh_alt_prev.ptr != exp_uh_alt_prev) { EMSG("uh_alt_prev wrong"); smsg((char_u *)"expected: 0x%x, actual: 0x%x", exp_uh_alt_prev, uhp->uh_alt_prev.ptr); } /* Check the undo tree at this header. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { if (uep->ue_magic != UE_MAGIC) { EMSG("ue_magic wrong (may be using freed memory)"); break; } } /* Check the next alt tree. */ u_check_tree(uhp->uh_alt_next.ptr, uhp->uh_next.ptr, uhp); /* Check the next header in this branch. */ u_check_tree(uhp->uh_prev.ptr, uhp, NULL); } } static void u_check(int newhead_may_be_NULL) { seen_b_u_newhead = 0; seen_b_u_curhead = 0; header_count = 0; u_check_tree(curbuf->b_u_oldhead, NULL, NULL); if (seen_b_u_newhead == 0 && curbuf->b_u_oldhead != NULL && !(newhead_may_be_NULL && curbuf->b_u_newhead == NULL)) EMSGN("b_u_newhead invalid: 0x%x", curbuf->b_u_newhead); if (curbuf->b_u_curhead != NULL && seen_b_u_curhead == 0) EMSGN("b_u_curhead invalid: 0x%x", curbuf->b_u_curhead); if (header_count != curbuf->b_u_numhead) { EMSG("b_u_numhead invalid"); smsg((char_u *)"expected: %ld, actual: %ld", (long)header_count, (long)curbuf->b_u_numhead); } } #endif /* * Save the current line for both the "u" and "U" command. * Careful: may trigger autocommands that reload the buffer. * Returns OK or FAIL. */ int u_save_cursor(void) { return (u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + 1))); } /* * Save the lines between "top" and "bot" for both the "u" and "U" command. * "top" may be 0 and bot may be curbuf->b_ml.ml_line_count + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_save(linenr_T top, linenr_T bot) { if (undo_off) return OK; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) return FALSE; /* rely on caller to do error messages */ if (top + 2 == bot) u_saveline((linenr_T)(top + 1)); return (u_savecommon(top, bot, (linenr_T)0, FALSE)); } /* * Save the line "lnum" (used by ":s" and "~" command). * The line is replaced, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savesub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + 1, lnum + 1, FALSE)); } /* * A new line is inserted before line "lnum" (used by :s command). * The line is inserted, so the new bottom line is lnum + 1. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_inssub(linenr_T lnum) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum, lnum + 1, FALSE)); } /* * Save the lines "lnum" - "lnum" + nlines (used by delete command). * The lines are deleted, so the new bottom line is lnum, unless the buffer * becomes empty. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savedel(linenr_T lnum, long nlines) { if (undo_off) return OK; return (u_savecommon(lnum - 1, lnum + nlines, nlines == curbuf->b_ml.ml_line_count ? 2 : lnum, FALSE)); } /* * Return TRUE when undo is allowed. Otherwise give an error message and * return FALSE. */ int undo_allowed(void) { /* Don't allow changes when 'modifiable' is off. */ if (!curbuf->b_p_ma) { EMSG(_(e_modifiable)); return FALSE; } #ifdef HAVE_SANDBOX /* In the sandbox it's not allowed to change the text. */ if (sandbox != 0) { EMSG(_(e_sandbox)); return FALSE; } #endif /* Don't allow changes in the buffer while editing the cmdline. The * caller of getcmdline() may get confused. */ if (textlock != 0) { EMSG(_(e_secure)); return FALSE; } return TRUE; } /* * Get the undolevle value for the current buffer. */ static long get_undolevel(void) { if (curbuf->b_p_ul == NO_LOCAL_UNDOLEVEL) return p_ul; return curbuf->b_p_ul; } /* * Common code for various ways to save text before a change. * "top" is the line above the first changed line. * "bot" is the line below the last changed line. * "newbot" is the new bottom line. Use zero when not known. * "reload" is TRUE when saving for a buffer reload. * Careful: may trigger autocommands that reload the buffer. * Returns FAIL when lines could not be saved, OK otherwise. */ int u_savecommon( linenr_T top, linenr_T bot, linenr_T newbot, int reload) { linenr_T lnum; long i; u_header_T *uhp; u_header_T *old_curhead; u_entry_T *uep; u_entry_T *prev_uep; long size; if (!reload) { /* When making changes is not allowed return FAIL. It's a crude way * to make all change commands fail. */ if (!undo_allowed()) return FAIL; #ifdef FEAT_NETBEANS_INTG /* * Netbeans defines areas that cannot be modified. Bail out here when * trying to change text in a guarded area. */ if (netbeans_active()) { if (netbeans_is_guarded(top, bot)) { EMSG(_(e_guarded)); return FAIL; } if (curbuf->b_p_ro) { EMSG(_(e_nbreadonly)); return FAIL; } } #endif #ifdef FEAT_AUTOCMD /* * Saving text for undo means we are going to make a change. Give a * warning for a read-only file before making the change, so that the * FileChangedRO event can replace the buffer with a read-write version * (e.g., obtained from a source control system). */ change_warning(0); if (bot > curbuf->b_ml.ml_line_count + 1) { /* This happens when the FileChangedRO autocommand changes the * file in a way it becomes shorter. */ EMSG(_("E881: Line count changed unexpectedly")); return FAIL; } #endif } #ifdef U_DEBUG u_check(FALSE); #endif size = bot - top - 1; /* * If curbuf->b_u_synced == TRUE make a new header. */ if (curbuf->b_u_synced) { #ifdef FEAT_JUMPLIST /* Need to create new entry in b_changelist. */ curbuf->b_new_change = TRUE; #endif if (get_undolevel() >= 0) { /* * Make a new header entry. Do this first so that we don't mess * up the undo info when out of memory. */ uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) goto nomem; #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif } else uhp = NULL; /* * If we undid more than we redid, move the entry lists before and * including curbuf->b_u_curhead to an alternate branch. */ old_curhead = curbuf->b_u_curhead; if (old_curhead != NULL) { curbuf->b_u_newhead = old_curhead->uh_next.ptr; curbuf->b_u_curhead = NULL; } /* * free headers to keep the size right */ while (curbuf->b_u_numhead > get_undolevel() && curbuf->b_u_oldhead != NULL) { u_header_T *uhfree = curbuf->b_u_oldhead; if (uhfree == old_curhead) /* Can't reconnect the branch, delete all of it. */ u_freebranch(curbuf, uhfree, &old_curhead); else if (uhfree->uh_alt_next.ptr == NULL) /* There is no branch, only free one header. */ u_freeheader(curbuf, uhfree, &old_curhead); else { /* Free the oldest alternate branch as a whole. */ while (uhfree->uh_alt_next.ptr != NULL) uhfree = uhfree->uh_alt_next.ptr; u_freebranch(curbuf, uhfree, &old_curhead); } #ifdef U_DEBUG u_check(TRUE); #endif } if (uhp == NULL) /* no undo at all */ { if (old_curhead != NULL) u_freebranch(curbuf, old_curhead, NULL); curbuf->b_u_synced = FALSE; return OK; } uhp->uh_prev.ptr = NULL; uhp->uh_next.ptr = curbuf->b_u_newhead; uhp->uh_alt_next.ptr = old_curhead; if (old_curhead != NULL) { uhp->uh_alt_prev.ptr = old_curhead->uh_alt_prev.ptr; if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = uhp; old_curhead->uh_alt_prev.ptr = uhp; if (curbuf->b_u_oldhead == old_curhead) curbuf->b_u_oldhead = uhp; } else uhp->uh_alt_prev.ptr = NULL; if (curbuf->b_u_newhead != NULL) curbuf->b_u_newhead->uh_prev.ptr = uhp; uhp->uh_seq = ++curbuf->b_u_seq_last; curbuf->b_u_seq_cur = uhp->uh_seq; uhp->uh_time = vim_time(); uhp->uh_save_nr = 0; curbuf->b_u_time_cur = uhp->uh_time + 1; uhp->uh_walk = 0; uhp->uh_entry = NULL; uhp->uh_getbot_entry = NULL; uhp->uh_cursor = curwin->w_cursor; /* save cursor pos. for undo */ #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curwin->w_cursor.coladd > 0) uhp->uh_cursor_vcol = getviscol(); else uhp->uh_cursor_vcol = -1; #endif /* save changed and buffer empty flag for undo */ uhp->uh_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); /* save named marks and Visual marks for undo */ mch_memmove(uhp->uh_namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); uhp->uh_visual = curbuf->b_visual; curbuf->b_u_newhead = uhp; if (curbuf->b_u_oldhead == NULL) curbuf->b_u_oldhead = uhp; ++curbuf->b_u_numhead; } else { if (get_undolevel() < 0) /* no undo at all */ return OK; /* * When saving a single line, and it has been saved just before, it * doesn't make sense saving it again. Saves a lot of memory when * making lots of changes inside the same line. * This is only possible if the previous change didn't increase or * decrease the number of lines. * Check the ten last changes. More doesn't make sense and takes too * long. */ if (size == 1) { uep = u_get_headentry(); prev_uep = NULL; for (i = 0; i < 10; ++i) { if (uep == NULL) break; /* If lines have been inserted/deleted we give up. * Also when the line was included in a multi-line save. */ if ((curbuf->b_u_newhead->uh_getbot_entry != uep ? (uep->ue_top + uep->ue_size + 1 != (uep->ue_bot == 0 ? curbuf->b_ml.ml_line_count + 1 : uep->ue_bot)) : uep->ue_lcount != curbuf->b_ml.ml_line_count) || (uep->ue_size > 1 && top >= uep->ue_top && top + 2 <= uep->ue_top + uep->ue_size + 1)) break; /* If it's the same line we can skip saving it again. */ if (uep->ue_size == 1 && uep->ue_top == top) { if (i > 0) { /* It's not the last entry: get ue_bot for the last * entry now. Following deleted/inserted lines go to * the re-used entry. */ u_getbot(); curbuf->b_u_synced = FALSE; /* Move the found entry to become the last entry. The * order of undo/redo doesn't matter for the entries * we move it over, since they don't change the line * count and don't include this line. It does matter * for the found entry if the line count is changed by * the executed command. */ prev_uep->ue_next = uep->ue_next; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; } /* The executed command may change the line count. */ if (newbot != 0) uep->ue_bot = newbot; else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } return OK; } prev_uep = uep; uep = uep->ue_next; } } /* find line number for ue_bot for previous u_save() */ u_getbot(); } #if !defined(UNIX) && !defined(WIN32) /* * With Amiga we can't handle big undo's, because * then u_alloc_line would have to allocate a block larger than 32K */ if (size >= 8000) goto nomem; #endif /* * add lines in front of entry list */ uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) goto nomem; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_size = size; uep->ue_top = top; if (newbot != 0) uep->ue_bot = newbot; /* * Use 0 for ue_bot if bot is below last line. * Otherwise we have to compute ue_bot later. */ else if (bot > curbuf->b_ml.ml_line_count) uep->ue_bot = 0; else { uep->ue_lcount = curbuf->b_ml.ml_line_count; curbuf->b_u_newhead->uh_getbot_entry = uep; } if (size > 0) { if ((uep->ue_array = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * size)) == NULL) { u_freeentry(uep, 0L); goto nomem; } for (i = 0, lnum = top + 1; i < size; ++i) { fast_breakcheck(); if (got_int) { u_freeentry(uep, i); return FAIL; } if ((uep->ue_array[i] = u_save_line(lnum++)) == NULL) { u_freeentry(uep, i); goto nomem; } } } else uep->ue_array = NULL; uep->ue_next = curbuf->b_u_newhead->uh_entry; curbuf->b_u_newhead->uh_entry = uep; curbuf->b_u_synced = FALSE; undo_undoes = FALSE; #ifdef U_DEBUG u_check(FALSE); #endif return OK; nomem: msg_silent = 0; /* must display the prompt */ if (ask_yesno((char_u *)_("No undo possible; continue anyway"), TRUE) == 'y') { undo_off = TRUE; /* will be reset when character typed */ return OK; } do_outofmem_msg((long_u)0); return FAIL; } #if defined(FEAT_PERSISTENT_UNDO) || defined(PROTO) # define UF_START_MAGIC "Vim\237UnDo\345" /* magic at start of undofile */ # define UF_START_MAGIC_LEN 9 # define UF_HEADER_MAGIC 0x5fd0 /* magic at start of header */ # define UF_HEADER_END_MAGIC 0xe7aa /* magic after last header */ # define UF_ENTRY_MAGIC 0xf518 /* magic at start of entry */ # define UF_ENTRY_END_MAGIC 0x3581 /* magic after last entry */ # define UF_VERSION 2 /* 2-byte undofile version number */ # define UF_VERSION_CRYPT 0x8002 /* idem, encrypted */ /* extra fields for header */ # define UF_LAST_SAVE_NR 1 /* extra fields for uhp */ # define UHP_SAVE_NR 1 static char_u e_not_open[] = N_("E828: Cannot open undo file for writing: %s"); /* * Compute the hash for the current buffer text into hash[UNDO_HASH_SIZE]. */ void u_compute_hash(char_u *hash) { context_sha256_T ctx; linenr_T lnum; char_u *p; sha256_start(&ctx); for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { p = ml_get(lnum); sha256_update(&ctx, p, (UINT32_T)(STRLEN(p) + 1)); } sha256_finish(&ctx, hash); } /* * Return an allocated string of the full path of the target undofile. * When "reading" is TRUE find the file to read, go over all directories in * 'undodir'. * When "reading" is FALSE use the first name where the directory exists. * Returns NULL when there is no place to write or no file to read. */ char_u * u_get_undo_file_name(char_u *buf_ffname, int reading) { char_u *dirp; char_u dir_name[IOSIZE + 1]; char_u *munged_name = NULL; char_u *undo_file_name = NULL; int dir_len; char_u *p; stat_T st; char_u *ffname = buf_ffname; #ifdef HAVE_READLINK char_u fname_buf[MAXPATHL]; #endif if (ffname == NULL) return NULL; #ifdef HAVE_READLINK /* Expand symlink in the file name, so that we put the undo file with the * actual file instead of with the symlink. */ if (resolve_symlink(ffname, fname_buf) == OK) ffname = fname_buf; #endif /* Loop over 'undodir'. When reading find the first file that exists. * When not reading use the first directory that exists or ".". */ dirp = p_udir; while (*dirp != NUL) { dir_len = copy_option_part(&dirp, dir_name, IOSIZE, ","); if (dir_len == 1 && dir_name[0] == '.') { /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ undo_file_name = vim_strnsave(ffname, (int)(STRLEN(ffname) + 5)); if (undo_file_name == NULL) break; p = gettail(undo_file_name); #ifdef VMS /* VMS can not handle more than one dot in the filenames * use "dir/name" -> "dir/_un_name" - add _un_ * at the beginning to keep the extension */ mch_memmove(p + 4, p, STRLEN(p) + 1); mch_memmove(p, "_un_", 4); #else /* Use same directory as the ffname, * "dir/name" -> "dir/.name.un~" */ mch_memmove(p + 1, p, STRLEN(p) + 1); *p = '.'; STRCAT(p, ".un~"); #endif } else { dir_name[dir_len] = NUL; if (mch_isdir(dir_name)) { if (munged_name == NULL) { munged_name = vim_strsave(ffname); if (munged_name == NULL) return NULL; for (p = munged_name; *p != NUL; mb_ptr_adv(p)) if (vim_ispathsep(*p)) *p = '%'; } undo_file_name = concat_fnames(dir_name, munged_name, TRUE); } } /* When reading check if the file exists. */ if (undo_file_name != NULL && (!reading || mch_stat((char *)undo_file_name, &st) >= 0)) break; vim_free(undo_file_name); undo_file_name = NULL; } vim_free(munged_name); return undo_file_name; } static void corruption_error(char *mesg, char_u *file_name) { EMSG3(_("E825: Corrupted undo file (%s): %s"), mesg, file_name); } static void u_free_uhp(u_header_T *uhp) { u_entry_T *nuep; u_entry_T *uep; uep = uhp->uh_entry; while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } vim_free(uhp); } /* * Write a sequence of bytes to the undo file. * Buffers and encrypts as needed. * Returns OK or FAIL. */ static int undo_write(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { size_t len_todo = len; char_u *p = ptr; while (bi->bi_used + len_todo >= CRYPT_BUF_SIZE) { size_t n = CRYPT_BUF_SIZE - bi->bi_used; mch_memmove(bi->bi_buffer + bi->bi_used, p, n); len_todo -= n; p += n; bi->bi_used = CRYPT_BUF_SIZE; if (undo_flush(bi) == FAIL) return FAIL; } if (len_todo > 0) { mch_memmove(bi->bi_buffer + bi->bi_used, p, len_todo); bi->bi_used += len_todo; } return OK; } #endif if (fwrite(ptr, len, (size_t)1, bi->bi_fp) != 1) return FAIL; return OK; } #ifdef FEAT_CRYPT static int undo_flush(bufinfo_T *bi) { if (bi->bi_buffer != NULL && bi->bi_used > 0) { crypt_encode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_used); if (fwrite(bi->bi_buffer, bi->bi_used, (size_t)1, bi->bi_fp) != 1) return FAIL; bi->bi_used = 0; } return OK; } #endif /* * Write "ptr[len]" and crypt the bytes when needed. * Returns OK or FAIL. */ static int fwrite_crypt(bufinfo_T *bi, char_u *ptr, size_t len) { #ifdef FEAT_CRYPT char_u *copy; char_u small_buf[100]; size_t i; if (bi->bi_state != NULL && bi->bi_buffer == NULL) { /* crypting every piece of text separately */ if (len < 100) copy = small_buf; /* no malloc()/free() for short strings */ else { copy = lalloc(len, FALSE); if (copy == NULL) return 0; } crypt_encode(bi->bi_state, ptr, len, copy); i = fwrite(copy, len, (size_t)1, bi->bi_fp); if (copy != small_buf) vim_free(copy); return i == 1 ? OK : FAIL; } #endif return undo_write(bi, ptr, len); } /* * Write a number, MSB first, in "len" bytes. * Must match with undo_read_?c() functions. * Returns OK or FAIL. */ static int undo_write_bytes(bufinfo_T *bi, long_u nr, int len) { char_u buf[8]; int i; int bufi = 0; for (i = len - 1; i >= 0; --i) buf[bufi++] = (char_u)(nr >> (i * 8)); return undo_write(bi, buf, (size_t)len); } /* * Write the pointer to an undo header. Instead of writing the pointer itself * we use the sequence number of the header. This is converted back to * pointers when reading. */ static void put_header_ptr(bufinfo_T *bi, u_header_T *uhp) { undo_write_bytes(bi, (long_u)(uhp != NULL ? uhp->uh_seq : 0), 4); } static int undo_read_4c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[4]; int n; undo_read(bi, buf, (size_t)4); n = ((unsigned)buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]; return n; } #endif return get4c(bi->bi_fp); } static int undo_read_2c(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[2]; int n; undo_read(bi, buf, (size_t)2); n = (buf[0] << 8) + buf[1]; return n; } #endif return get2c(bi->bi_fp); } static int undo_read_byte(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[1]; undo_read(bi, buf, (size_t)1); return buf[0]; } #endif return getc(bi->bi_fp); } static time_t undo_read_time(bufinfo_T *bi) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { char_u buf[8]; time_t n = 0; int i; undo_read(bi, buf, (size_t)8); for (i = 0; i < 8; ++i) n = (n << 8) + buf[i]; return n; } #endif return get8ctime(bi->bi_fp); } /* * Read "buffer[size]" from the undo file. * Return OK or FAIL. */ static int undo_read(bufinfo_T *bi, char_u *buffer, size_t size) { #ifdef FEAT_CRYPT if (bi->bi_buffer != NULL) { int size_todo = (int)size; char_u *p = buffer; while (size_todo > 0) { size_t n; if (bi->bi_used >= bi->bi_avail) { n = fread(bi->bi_buffer, 1, (size_t)CRYPT_BUF_SIZE, bi->bi_fp); if (n == 0) { /* Error may be checked for only later. Fill with zeros, * so that the reader won't use garbage. */ vim_memset(p, 0, size_todo); return FAIL; } bi->bi_avail = n; bi->bi_used = 0; crypt_decode_inplace(bi->bi_state, bi->bi_buffer, bi->bi_avail); } n = size_todo; if (n > bi->bi_avail - bi->bi_used) n = bi->bi_avail - bi->bi_used; mch_memmove(p, bi->bi_buffer + bi->bi_used, n); bi->bi_used += n; size_todo -= (int)n; p += n; } return OK; } #endif if (fread(buffer, (size_t)size, 1, bi->bi_fp) != 1) return FAIL; return OK; } /* * Read a string of length "len" from "bi->bi_fd". * "len" can be zero to allocate an empty line. * Decrypt the bytes if needed. * Append a NUL. * Returns a pointer to allocated memory or NULL for failure. */ static char_u * read_string_decrypt(bufinfo_T *bi, int len) { char_u *ptr = alloc((unsigned)len + 1); if (ptr != NULL) { if (len > 0 && undo_read(bi, ptr, len) == FAIL) { vim_free(ptr); return NULL; } ptr[len] = NUL; #ifdef FEAT_CRYPT if (bi->bi_state != NULL && bi->bi_buffer == NULL) crypt_decode_inplace(bi->bi_state, ptr, len); #endif } return ptr; } /* * Writes the (not encrypted) header and initializes encryption if needed. */ static int serialize_header(bufinfo_T *bi, char_u *hash) { int len; buf_T *buf = bi->bi_buf; FILE *fp = bi->bi_fp; char_u time_buf[8]; /* Start writing, first the magic marker and undo info version. */ if (fwrite(UF_START_MAGIC, (size_t)UF_START_MAGIC_LEN, (size_t)1, fp) != 1) return FAIL; /* If the buffer is encrypted then all text bytes following will be * encrypted. Numbers and other info is not crypted. */ #ifdef FEAT_CRYPT if (*buf->b_p_key != NUL) { char_u *header; int header_len; undo_write_bytes(bi, (long_u)UF_VERSION_CRYPT, 2); bi->bi_state = crypt_create_for_writing(crypt_get_method_nr(buf), buf->b_p_key, &header, &header_len); if (bi->bi_state == NULL) return FAIL; len = (int)fwrite(header, (size_t)header_len, (size_t)1, fp); vim_free(header); if (len != 1) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } if (crypt_whole_undofile(crypt_get_method_nr(buf))) { bi->bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi->bi_buffer == NULL) { crypt_free_state(bi->bi_state); bi->bi_state = NULL; return FAIL; } bi->bi_used = 0; } } else #endif undo_write_bytes(bi, (long_u)UF_VERSION, 2); /* Write a hash of the buffer text, so that we can verify it is still the * same when reading the buffer text. */ if (undo_write(bi, hash, (size_t)UNDO_HASH_SIZE) == FAIL) return FAIL; /* buffer-specific data */ undo_write_bytes(bi, (long_u)buf->b_ml.ml_line_count, 4); len = buf->b_u_line_ptr != NULL ? (int)STRLEN(buf->b_u_line_ptr) : 0; undo_write_bytes(bi, (long_u)len, 4); if (len > 0 && fwrite_crypt(bi, buf->b_u_line_ptr, (size_t)len) == FAIL) return FAIL; undo_write_bytes(bi, (long_u)buf->b_u_line_lnum, 4); undo_write_bytes(bi, (long_u)buf->b_u_line_colnr, 4); /* Undo structures header data */ put_header_ptr(bi, buf->b_u_oldhead); put_header_ptr(bi, buf->b_u_newhead); put_header_ptr(bi, buf->b_u_curhead); undo_write_bytes(bi, (long_u)buf->b_u_numhead, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_last, 4); undo_write_bytes(bi, (long_u)buf->b_u_seq_cur, 4); time_to_bytes(buf->b_u_time_cur, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UF_LAST_SAVE_NR, 1); undo_write_bytes(bi, (long_u)buf->b_u_save_nr_last, 4); undo_write_bytes(bi, 0, 1); /* end marker */ return OK; } static int serialize_uhp(bufinfo_T *bi, u_header_T *uhp) { int i; u_entry_T *uep; char_u time_buf[8]; if (undo_write_bytes(bi, (long_u)UF_HEADER_MAGIC, 2) == FAIL) return FAIL; put_header_ptr(bi, uhp->uh_next.ptr); put_header_ptr(bi, uhp->uh_prev.ptr); put_header_ptr(bi, uhp->uh_alt_next.ptr); put_header_ptr(bi, uhp->uh_alt_prev.ptr); undo_write_bytes(bi, uhp->uh_seq, 4); serialize_pos(bi, uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)uhp->uh_cursor_vcol, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif undo_write_bytes(bi, (long_u)uhp->uh_flags, 2); /* Assume NMARKS will stay the same. */ for (i = 0; i < NMARKS; ++i) serialize_pos(bi, uhp->uh_namedm[i]); serialize_visualinfo(bi, &uhp->uh_visual); time_to_bytes(uhp->uh_time, time_buf); undo_write(bi, time_buf, 8); /* Optional fields. */ undo_write_bytes(bi, 4, 1); undo_write_bytes(bi, UHP_SAVE_NR, 1); undo_write_bytes(bi, (long_u)uhp->uh_save_nr, 4); undo_write_bytes(bi, 0, 1); /* end marker */ /* Write all the entries. */ for (uep = uhp->uh_entry; uep != NULL; uep = uep->ue_next) { undo_write_bytes(bi, (long_u)UF_ENTRY_MAGIC, 2); if (serialize_uep(bi, uep) == FAIL) return FAIL; } undo_write_bytes(bi, (long_u)UF_ENTRY_END_MAGIC, 2); return OK; } static u_header_T * unserialize_uhp(bufinfo_T *bi, char_u *file_name) { u_header_T *uhp; int i; u_entry_T *uep, *last_uep; int c; int error; uhp = (u_header_T *)U_ALLOC_LINE(sizeof(u_header_T)); if (uhp == NULL) return NULL; vim_memset(uhp, 0, sizeof(u_header_T)); #ifdef U_DEBUG uhp->uh_magic = UH_MAGIC; #endif uhp->uh_next.seq = undo_read_4c(bi); uhp->uh_prev.seq = undo_read_4c(bi); uhp->uh_alt_next.seq = undo_read_4c(bi); uhp->uh_alt_prev.seq = undo_read_4c(bi); uhp->uh_seq = undo_read_4c(bi); if (uhp->uh_seq <= 0) { corruption_error("uh_seq", file_name); vim_free(uhp); return NULL; } unserialize_pos(bi, &uhp->uh_cursor); #ifdef FEAT_VIRTUALEDIT uhp->uh_cursor_vcol = undo_read_4c(bi); #else (void)undo_read_4c(bi); #endif uhp->uh_flags = undo_read_2c(bi); for (i = 0; i < NMARKS; ++i) unserialize_pos(bi, &uhp->uh_namedm[i]); unserialize_visualinfo(bi, &uhp->uh_visual); uhp->uh_time = undo_read_time(bi); /* Optional fields. */ for (;;) { int len = undo_read_byte(bi); int what; if (len == 0) break; what = undo_read_byte(bi); switch (what) { case UHP_SAVE_NR: uhp->uh_save_nr = undo_read_4c(bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(bi); } } /* Unserialize the uep list. */ last_uep = NULL; while ((c = undo_read_2c(bi)) == UF_ENTRY_MAGIC) { error = FALSE; uep = unserialize_uep(bi, &error, file_name); if (last_uep == NULL) uhp->uh_entry = uep; else last_uep->ue_next = uep; last_uep = uep; if (uep == NULL || error) { u_free_uhp(uhp); return NULL; } } if (c != UF_ENTRY_END_MAGIC) { corruption_error("entry end", file_name); u_free_uhp(uhp); return NULL; } return uhp; } /* * Serialize "uep". */ static int serialize_uep( bufinfo_T *bi, u_entry_T *uep) { int i; size_t len; undo_write_bytes(bi, (long_u)uep->ue_top, 4); undo_write_bytes(bi, (long_u)uep->ue_bot, 4); undo_write_bytes(bi, (long_u)uep->ue_lcount, 4); undo_write_bytes(bi, (long_u)uep->ue_size, 4); for (i = 0; i < uep->ue_size; ++i) { len = STRLEN(uep->ue_array[i]); if (undo_write_bytes(bi, (long_u)len, 4) == FAIL) return FAIL; if (len > 0 && fwrite_crypt(bi, uep->ue_array[i], len) == FAIL) return FAIL; } return OK; } static u_entry_T * unserialize_uep(bufinfo_T *bi, int *error, char_u *file_name) { int i; u_entry_T *uep; char_u **array; char_u *line; int line_len; uep = (u_entry_T *)U_ALLOC_LINE(sizeof(u_entry_T)); if (uep == NULL) return NULL; vim_memset(uep, 0, sizeof(u_entry_T)); #ifdef U_DEBUG uep->ue_magic = UE_MAGIC; #endif uep->ue_top = undo_read_4c(bi); uep->ue_bot = undo_read_4c(bi); uep->ue_lcount = undo_read_4c(bi); uep->ue_size = undo_read_4c(bi); if (uep->ue_size > 0) { array = (char_u **)U_ALLOC_LINE(sizeof(char_u *) * uep->ue_size); if (array == NULL) { *error = TRUE; return uep; } vim_memset(array, 0, sizeof(char_u *) * uep->ue_size); } else array = NULL; uep->ue_array = array; for (i = 0; i < uep->ue_size; ++i) { line_len = undo_read_4c(bi); if (line_len >= 0) line = read_string_decrypt(bi, line_len); else { line = NULL; corruption_error("line length", file_name); } if (line == NULL) { *error = TRUE; return uep; } array[i] = line; } return uep; } /* * Serialize "pos". */ static void serialize_pos(bufinfo_T *bi, pos_T pos) { undo_write_bytes(bi, (long_u)pos.lnum, 4); undo_write_bytes(bi, (long_u)pos.col, 4); #ifdef FEAT_VIRTUALEDIT undo_write_bytes(bi, (long_u)pos.coladd, 4); #else undo_write_bytes(bi, (long_u)0, 4); #endif } /* * Unserialize the pos_T at the current position. */ static void unserialize_pos(bufinfo_T *bi, pos_T *pos) { pos->lnum = undo_read_4c(bi); if (pos->lnum < 0) pos->lnum = 0; pos->col = undo_read_4c(bi); if (pos->col < 0) pos->col = 0; #ifdef FEAT_VIRTUALEDIT pos->coladd = undo_read_4c(bi); if (pos->coladd < 0) pos->coladd = 0; #else (void)undo_read_4c(bi); #endif } /* * Serialize "info". */ static void serialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { serialize_pos(bi, info->vi_start); serialize_pos(bi, info->vi_end); undo_write_bytes(bi, (long_u)info->vi_mode, 4); undo_write_bytes(bi, (long_u)info->vi_curswant, 4); } /* * Unserialize the visualinfo_T at the current position. */ static void unserialize_visualinfo(bufinfo_T *bi, visualinfo_T *info) { unserialize_pos(bi, &info->vi_start); unserialize_pos(bi, &info->vi_end); info->vi_mode = undo_read_4c(bi); info->vi_curswant = undo_read_4c(bi); } /* * Write the undo tree in an undo file. * When "name" is not NULL, use it as the name of the undo file. * Otherwise use buf->b_ffname to generate the undo file name. * "buf" must never be null, buf->b_ffname is used to obtain the original file * permissions. * "forceit" is TRUE for ":wundo!", FALSE otherwise. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_write_undo( char_u *name, int forceit, buf_T *buf, char_u *hash) { u_header_T *uhp; char_u *file_name; int mark; #ifdef U_DEBUG int headers_written = 0; #endif int fd; FILE *fp = NULL; int perm; int write_ok = FALSE; #ifdef UNIX int st_old_valid = FALSE; stat_T st_old; stat_T st_new; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(buf->b_ffname, FALSE); if (file_name == NULL) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *) _("Cannot write undo file in any directory in 'undodir'")); verbose_leave(); } return; } } else file_name = name; /* * Decide about the permission to use for the undo file. If the buffer * has a name use the permission of the original file. Otherwise only * allow the user to access the undo file. */ perm = 0600; if (buf->b_ffname != NULL) { #ifdef UNIX if (mch_stat((char *)buf->b_ffname, &st_old) >= 0) { perm = st_old.st_mode; st_old_valid = TRUE; } #else perm = mch_getperm(buf->b_ffname); if (perm < 0) perm = 0600; #endif } /* strip any s-bit and executable bit */ perm = perm & 0666; /* If the undo file already exists, verify that it actually is an undo * file, and delete it. */ if (mch_getperm(file_name) >= 0) { if (name == NULL || !forceit) { /* Check we can read it and it's an undo file. */ fd = mch_open((char *)file_name, O_RDONLY|O_EXTRA, 0); if (fd < 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite with undo file, cannot read: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } else { char_u mbuf[UF_START_MAGIC_LEN]; int len; len = read_eintr(fd, mbuf, UF_START_MAGIC_LEN); close(fd); if (len < UF_START_MAGIC_LEN || memcmp(mbuf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { if (name != NULL || p_verbose > 0) { if (name == NULL) verbose_enter(); smsg((char_u *) _("Will not overwrite, this is not an undo file: %s"), file_name); if (name == NULL) verbose_leave(); } goto theend; } } } mch_remove(file_name); } /* If there is no undo information at all, quit here after deleting any * existing undo file. */ if (buf->b_u_numhead == 0 && buf->b_u_line_ptr == NULL) { if (p_verbose > 0) verb_msg((char_u *)_("Skipping undo file write, nothing to undo")); goto theend; } fd = mch_open((char *)file_name, O_CREAT|O_EXTRA|O_WRONLY|O_EXCL|O_NOFOLLOW, perm); if (fd < 0) { EMSG2(_(e_not_open), file_name); goto theend; } (void)mch_setperm(file_name, perm); if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Writing undo file: %s"), file_name); verbose_leave(); } #ifdef U_DEBUG /* Check there is no problem in undo info before writing. */ u_check(FALSE); #endif #ifdef UNIX /* * Try to set the group of the undo file same as the original file. If * this fails, set the protection bits for the group same as the * protection bits for others. */ if (st_old_valid && mch_stat((char *)file_name, &st_new) >= 0 && st_new.st_gid != st_old.st_gid # ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */ && fchown(fd, (uid_t)-1, st_old.st_gid) != 0 # endif ) mch_setperm(file_name, (perm & 0707) | ((perm & 07) << 3)); # if defined(HAVE_SELINUX) || defined(HAVE_SMACK) if (buf->b_ffname != NULL) mch_copy_sec(buf->b_ffname, file_name); # endif #endif fp = fdopen(fd, "w"); if (fp == NULL) { EMSG2(_(e_not_open), file_name); close(fd); mch_remove(file_name); goto theend; } /* Undo must be synced. */ u_sync(TRUE); /* * Write the header. Initializes encryption, if enabled. */ bi.bi_buf = buf; bi.bi_fp = fp; if (serialize_header(&bi, hash) == FAIL) goto write_error; /* * Iteratively serialize UHPs and their UEPs from the top down. */ mark = ++lastmark; uhp = buf->b_u_oldhead; while (uhp != NULL) { /* Serialize current UHP if we haven't seen it */ if (uhp->uh_walk != mark) { uhp->uh_walk = mark; #ifdef U_DEBUG ++headers_written; #endif if (serialize_uhp(&bi, uhp) == FAIL) goto write_error; } /* Now walk through the tree - algorithm from undo_time(). */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != mark) uhp = uhp->uh_next.ptr; else if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } if (undo_write_bytes(&bi, (long_u)UF_HEADER_END_MAGIC, 2) == OK) write_ok = TRUE; #ifdef U_DEBUG if (headers_written != buf->b_u_numhead) { EMSGN("Written %ld headers, ...", headers_written); EMSGN("... but numhead is %ld", buf->b_u_numhead); } #endif #ifdef FEAT_CRYPT if (bi.bi_state != NULL && undo_flush(&bi) == FAIL) write_ok = FALSE; #endif write_error: fclose(fp); if (!write_ok) EMSG2(_("E829: write error in undo file: %s"), file_name); #if defined(MACOS_CLASSIC) || defined(WIN3264) /* Copy file attributes; for systems where this can only be done after * closing the file. */ if (buf->b_ffname != NULL) (void)mch_copy_file_attribute(buf->b_ffname, file_name); #endif #ifdef HAVE_ACL if (buf->b_ffname != NULL) { vim_acl_T acl; /* For systems that support ACL: get the ACL from the original file. */ acl = mch_get_acl(buf->b_ffname); mch_set_acl(file_name, acl); mch_free_acl(acl); } #endif theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (file_name != name) vim_free(file_name); } /* * Load the undo tree from an undo file. * If "name" is not NULL use it as the undo file name. This also means being * a bit more verbose. * Otherwise use curbuf->b_ffname to generate the undo file name. * "hash[UNDO_HASH_SIZE]" must be the hash value of the buffer text. */ void u_read_undo(char_u *name, char_u *hash, char_u *orig_name) { char_u *file_name; FILE *fp; long version, str_len; char_u *line_ptr = NULL; linenr_T line_lnum; colnr_T line_colnr; linenr_T line_count; long num_head = 0; long old_header_seq, new_header_seq, cur_header_seq; long seq_last, seq_cur; long last_save_nr = 0; short old_idx = -1, new_idx = -1, cur_idx = -1; long num_read_uhps = 0; time_t seq_time; int i, j; int c; u_header_T *uhp; u_header_T **uhp_table = NULL; char_u read_hash[UNDO_HASH_SIZE]; char_u magic_buf[UF_START_MAGIC_LEN]; #ifdef U_DEBUG int *uhp_table_used; #endif #ifdef UNIX stat_T st_orig; stat_T st_undo; #endif bufinfo_T bi; vim_memset(&bi, 0, sizeof(bi)); if (name == NULL) { file_name = u_get_undo_file_name(curbuf->b_ffname, TRUE); if (file_name == NULL) return; #ifdef UNIX /* For safety we only read an undo file if the owner is equal to the * owner of the text file or equal to the current user. */ if (mch_stat((char *)orig_name, &st_orig) >= 0 && mch_stat((char *)file_name, &st_undo) >= 0 && st_orig.st_uid != st_undo.st_uid && st_undo.st_uid != getuid()) { if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Not reading undo file, owner differs: %s"), file_name); verbose_leave(); } return; } #endif } else file_name = name; if (p_verbose > 0) { verbose_enter(); smsg((char_u *)_("Reading undo file: %s"), file_name); verbose_leave(); } fp = mch_fopen((char *)file_name, "r"); if (fp == NULL) { if (name != NULL || p_verbose > 0) EMSG2(_("E822: Cannot open undo file for reading: %s"), file_name); goto error; } bi.bi_buf = curbuf; bi.bi_fp = fp; /* * Read the undo file header. */ if (fread(magic_buf, UF_START_MAGIC_LEN, 1, fp) != 1 || memcmp(magic_buf, UF_START_MAGIC, UF_START_MAGIC_LEN) != 0) { EMSG2(_("E823: Not an undo file: %s"), file_name); goto error; } version = get2c(fp); if (version == UF_VERSION_CRYPT) { #ifdef FEAT_CRYPT if (*curbuf->b_p_key == NUL) { EMSG2(_("E832: Non-encrypted file has encrypted undo file: %s"), file_name); goto error; } bi.bi_state = crypt_create_from_file(fp, curbuf->b_p_key); if (bi.bi_state == NULL) { EMSG2(_("E826: Undo file decryption failed: %s"), file_name); goto error; } if (crypt_whole_undofile(bi.bi_state->method_nr)) { bi.bi_buffer = alloc(CRYPT_BUF_SIZE); if (bi.bi_buffer == NULL) { crypt_free_state(bi.bi_state); bi.bi_state = NULL; goto error; } bi.bi_avail = 0; bi.bi_used = 0; } #else EMSG2(_("E827: Undo file is encrypted: %s"), file_name); goto error; #endif } else if (version != UF_VERSION) { EMSG2(_("E824: Incompatible undo file: %s"), file_name); goto error; } if (undo_read(&bi, read_hash, (size_t)UNDO_HASH_SIZE) == FAIL) { corruption_error("hash", file_name); goto error; } line_count = (linenr_T)undo_read_4c(&bi); if (memcmp(hash, read_hash, UNDO_HASH_SIZE) != 0 || line_count != curbuf->b_ml.ml_line_count) { if (p_verbose > 0 || name != NULL) { if (name == NULL) verbose_enter(); give_warning((char_u *) _("File contents changed, cannot use undo info"), TRUE); if (name == NULL) verbose_leave(); } goto error; } /* Read undo data for "U" command. */ str_len = undo_read_4c(&bi); if (str_len < 0) goto error; if (str_len > 0) line_ptr = read_string_decrypt(&bi, str_len); line_lnum = (linenr_T)undo_read_4c(&bi); line_colnr = (colnr_T)undo_read_4c(&bi); if (line_lnum < 0 || line_colnr < 0) { corruption_error("line lnum/col", file_name); goto error; } /* Begin general undo data */ old_header_seq = undo_read_4c(&bi); new_header_seq = undo_read_4c(&bi); cur_header_seq = undo_read_4c(&bi); num_head = undo_read_4c(&bi); seq_last = undo_read_4c(&bi); seq_cur = undo_read_4c(&bi); seq_time = undo_read_time(&bi); /* Optional header fields. */ for (;;) { int len = undo_read_byte(&bi); int what; if (len == 0 || len == EOF) break; what = undo_read_byte(&bi); switch (what) { case UF_LAST_SAVE_NR: last_save_nr = undo_read_4c(&bi); break; default: /* field not supported, skip */ while (--len >= 0) (void)undo_read_byte(&bi); } } /* uhp_table will store the freshly created undo headers we allocate * until we insert them into curbuf. The table remains sorted by the * sequence numbers of the headers. * When there are no headers uhp_table is NULL. */ if (num_head > 0) { if (num_head < LONG_MAX / (long)sizeof(u_header_T *)) uhp_table = (u_header_T **)U_ALLOC_LINE( num_head * sizeof(u_header_T *)); if (uhp_table == NULL) goto error; } while ((c = undo_read_2c(&bi)) == UF_HEADER_MAGIC) { if (num_read_uhps >= num_head) { corruption_error("num_head too small", file_name); goto error; } uhp = unserialize_uhp(&bi, file_name); if (uhp == NULL) goto error; uhp_table[num_read_uhps++] = uhp; } if (num_read_uhps != num_head) { corruption_error("num_head", file_name); goto error; } if (c != UF_HEADER_END_MAGIC) { corruption_error("end marker", file_name); goto error; } #ifdef U_DEBUG uhp_table_used = (int *)alloc_clear( (unsigned)(sizeof(int) * num_head + 1)); # define SET_FLAG(j) ++uhp_table_used[j] #else # define SET_FLAG(j) #endif /* We have put all of the headers into a table. Now we iterate through the * table and swizzle each sequence number we have stored in uh_*_seq into * a pointer corresponding to the header with that sequence number. */ for (i = 0; i < num_head; i++) { uhp = uhp_table[i]; if (uhp == NULL) continue; for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && i != j && uhp_table[i]->uh_seq == uhp_table[j]->uh_seq) { corruption_error("duplicate uh_seq", file_name); goto error; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_next.seq) { uhp->uh_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_prev.seq) { uhp->uh_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_next.seq) { uhp->uh_alt_next.ptr = uhp_table[j]; SET_FLAG(j); break; } for (j = 0; j < num_head; j++) if (uhp_table[j] != NULL && uhp_table[j]->uh_seq == uhp->uh_alt_prev.seq) { uhp->uh_alt_prev.ptr = uhp_table[j]; SET_FLAG(j); break; } if (old_header_seq > 0 && old_idx < 0 && uhp->uh_seq == old_header_seq) { old_idx = i; SET_FLAG(i); } if (new_header_seq > 0 && new_idx < 0 && uhp->uh_seq == new_header_seq) { new_idx = i; SET_FLAG(i); } if (cur_header_seq > 0 && cur_idx < 0 && uhp->uh_seq == cur_header_seq) { cur_idx = i; SET_FLAG(i); } } /* Now that we have read the undo info successfully, free the current undo * info and use the info from the file. */ u_blockfree(curbuf); curbuf->b_u_oldhead = old_idx < 0 ? NULL : uhp_table[old_idx]; curbuf->b_u_newhead = new_idx < 0 ? NULL : uhp_table[new_idx]; curbuf->b_u_curhead = cur_idx < 0 ? NULL : uhp_table[cur_idx]; curbuf->b_u_line_ptr = line_ptr; curbuf->b_u_line_lnum = line_lnum; curbuf->b_u_line_colnr = line_colnr; curbuf->b_u_numhead = num_head; curbuf->b_u_seq_last = seq_last; curbuf->b_u_seq_cur = seq_cur; curbuf->b_u_time_cur = seq_time; curbuf->b_u_save_nr_last = last_save_nr; curbuf->b_u_save_nr_cur = last_save_nr; curbuf->b_u_synced = TRUE; vim_free(uhp_table); #ifdef U_DEBUG for (i = 0; i < num_head; ++i) if (uhp_table_used[i] == 0) EMSGN("uhp_table entry %ld not used, leaking memory", i); vim_free(uhp_table_used); u_check(TRUE); #endif if (name != NULL) smsg((char_u *)_("Finished reading undo file %s"), file_name); goto theend; error: vim_free(line_ptr); if (uhp_table != NULL) { for (i = 0; i < num_read_uhps; i++) if (uhp_table[i] != NULL) u_free_uhp(uhp_table[i]); vim_free(uhp_table); } theend: #ifdef FEAT_CRYPT if (bi.bi_state != NULL) crypt_free_state(bi.bi_state); vim_free(bi.bi_buffer); #endif if (fp != NULL) fclose(fp); if (file_name != name) vim_free(file_name); return; } #endif /* FEAT_PERSISTENT_UNDO */ /* * If 'cpoptions' contains 'u': Undo the previous undo or redo (vi compatible). * If 'cpoptions' does not contain 'u': Always undo. */ void u_undo(int count) { /* * If we get an undo command while executing a macro, we behave like the * original vi. If this happens twice in one macro the result will not * be compatible. */ if (curbuf->b_u_synced == FALSE) { u_sync(TRUE); count = 1; } if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = TRUE; else undo_undoes = !undo_undoes; u_doit(count); } /* * If 'cpoptions' contains 'u': Repeat the previous undo or redo. * If 'cpoptions' does not contain 'u': Always redo. */ void u_redo(int count) { if (vim_strchr(p_cpo, CPO_UNDO) == NULL) undo_undoes = FALSE; u_doit(count); } /* * Undo or redo, depending on 'undo_undoes', 'count' times. */ static void u_doit(int startcount) { int count = startcount; if (!undo_allowed()) return; u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; while (count--) { /* Do the change warning now, so that it triggers FileChangedRO when * needed. This may cause the file to be reloaded, that must happen * before we do anything, because it may change curbuf->b_u_curhead * and more. */ change_warning(0); if (undo_undoes) { if (curbuf->b_u_curhead == NULL) /* first undo */ curbuf->b_u_curhead = curbuf->b_u_newhead; else if (get_undolevel() > 0) /* multi level undo */ /* get next undo */ curbuf->b_u_curhead = curbuf->b_u_curhead->uh_next.ptr; /* nothing to undo */ if (curbuf->b_u_numhead == 0 || curbuf->b_u_curhead == NULL) { /* stick curbuf->b_u_curhead at end */ curbuf->b_u_curhead = curbuf->b_u_oldhead; beep_flush(); if (count == startcount - 1) { MSG(_("Already at oldest change")); return; } break; } u_undoredo(TRUE); } else { if (curbuf->b_u_curhead == NULL || get_undolevel() <= 0) { beep_flush(); /* nothing to redo */ if (count == startcount - 1) { MSG(_("Already at newest change")); return; } break; } u_undoredo(FALSE); /* Advance for next redo. Set "newhead" when at the end of the * redoable changes. */ if (curbuf->b_u_curhead->uh_prev.ptr == NULL) curbuf->b_u_newhead = curbuf->b_u_curhead; curbuf->b_u_curhead = curbuf->b_u_curhead->uh_prev.ptr; } } u_undo_end(undo_undoes, FALSE); } /* * Undo or redo over the timeline. * When "step" is negative go back in time, otherwise goes forward in time. * When "sec" is FALSE make "step" steps, when "sec" is TRUE use "step" as * seconds. * When "file" is TRUE use "step" as a number of file writes. * When "absolute" is TRUE use "step" as the sequence number to jump to. * "sec" must be FALSE then. */ void undo_time( long step, int sec, int file, int absolute) { long target; long closest; long closest_start; long closest_seq = 0; long val; u_header_T *uhp; u_header_T *last; int mark; int nomark; int round; int dosec = sec; int dofile = file; int above = FALSE; int did_undo = TRUE; /* First make sure the current undoable change is synced. */ if (curbuf->b_u_synced == FALSE) u_sync(TRUE); u_newcount = 0; u_oldcount = 0; if (curbuf->b_ml.ml_flags & ML_EMPTY) u_oldcount = -1; /* "target" is the node below which we want to be. * Init "closest" to a value we can't reach. */ if (absolute) { if (step == 0) { /* target 0 does not exist, got to 1 and above it. */ target = 1; above = TRUE; } else target = step; closest = -1; } else { if (dosec) target = (long)(curbuf->b_u_time_cur) + step; else if (dofile) { if (step < 0) { /* Going back to a previous write. If there were changes after * the last write, count that as moving one file-write, so * that ":earlier 1f" undoes all changes since the last save. */ uhp = curbuf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = curbuf->b_u_newhead; if (uhp != NULL && uhp->uh_save_nr != 0) /* "uh_save_nr" was set in the last block, that means * there were no changes since the last write */ target = curbuf->b_u_save_nr_cur + step; else /* count the changes since the last write as one step */ target = curbuf->b_u_save_nr_cur + step + 1; if (target <= 0) /* Go to before first write: before the oldest change. Use * the sequence number for that. */ dofile = FALSE; } else { /* Moving forward to a newer write. */ target = curbuf->b_u_save_nr_cur + step; if (target > curbuf->b_u_save_nr_last) { /* Go to after last write: after the latest change. Use * the sequence number for that. */ target = curbuf->b_u_seq_last + 1; dofile = FALSE; } } } else target = curbuf->b_u_seq_cur + step; if (step < 0) { if (target < 0) target = 0; closest = -1; } else { if (dosec) closest = (long)(vim_time() + 1); else if (dofile) closest = curbuf->b_u_save_nr_last + 2; else closest = curbuf->b_u_seq_last + 2; if (target >= closest) target = closest - 1; } } closest_start = closest; closest_seq = curbuf->b_u_seq_cur; /* * May do this twice: * 1. Search for "target", update "closest" to the best match found. * 2. If "target" not found search for "closest". * * When using the closest time we use the sequence number in the second * round, because there may be several entries with the same time. */ for (round = 1; round <= 2; ++round) { /* Find the path from the current state to where we want to go. The * desired state can be anywhere in the undo tree, need to go all over * it. We put "nomark" in uh_walk where we have been without success, * "mark" where it could possibly be. */ mark = ++lastmark; nomark = ++lastmark; if (curbuf->b_u_curhead == NULL) /* at leaf of the tree */ uhp = curbuf->b_u_newhead; else uhp = curbuf->b_u_curhead; while (uhp != NULL) { uhp->uh_walk = mark; if (dosec) val = (long)(uhp->uh_time); else if (dofile) val = uhp->uh_save_nr; else val = uhp->uh_seq; if (round == 1 && !(dofile && val == 0)) { /* Remember the header that is closest to the target. * It must be at least in the right direction (checked with * "b_u_seq_cur"). When the timestamp is equal find the * highest/lowest sequence number. */ if ((step < 0 ? uhp->uh_seq <= curbuf->b_u_seq_cur : uhp->uh_seq > curbuf->b_u_seq_cur) && ((dosec && val == closest) ? (step < 0 ? uhp->uh_seq < closest_seq : uhp->uh_seq > closest_seq) : closest == closest_start || (val > target ? (closest > target ? val - target <= closest - target : val - target <= target - closest) : (closest > target ? target - val <= closest - target : target - val <= target - closest)))) { closest = val; closest_seq = uhp->uh_seq; } } /* Quit searching when we found a match. But when searching for a * time we need to continue looking for the best uh_seq. */ if (target == val && !dosec) { target = uhp->uh_seq; break; } /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) uhp = uhp->uh_prev.ptr; /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { /* If still at the start we don't go through this change. */ if (uhp == curbuf->b_u_curhead) uhp->uh_walk = nomark; uhp = uhp->uh_next.ptr; } else { /* need to backtrack; mark this node as useless */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else uhp = uhp->uh_next.ptr; } } if (uhp != NULL) /* found it */ break; if (absolute) { EMSGN(_("E830: Undo number %ld not found"), step); return; } if (closest == closest_start) { if (step < 0) MSG(_("Already at oldest change")); else MSG(_("Already at newest change")); return; } target = closest_seq; dosec = FALSE; dofile = FALSE; if (step < 0) above = TRUE; /* stop above the header */ } /* If we found it: Follow the path to go to where we want to be. */ if (uhp != NULL) { /* * First go up the tree as much as needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) uhp = curbuf->b_u_newhead; else uhp = uhp->uh_next.ptr; if (uhp == NULL || uhp->uh_walk != mark || (uhp->uh_seq == target && !above)) break; curbuf->b_u_curhead = uhp; u_undoredo(TRUE); uhp->uh_walk = nomark; /* don't go back down here */ } /* * And now go down the tree (redo), branching off where needed. */ while (!got_int) { /* Do the change warning now, for the same reason as above. */ change_warning(0); uhp = curbuf->b_u_curhead; if (uhp == NULL) break; /* Go back to the first branch with a mark. */ while (uhp->uh_alt_prev.ptr != NULL && uhp->uh_alt_prev.ptr->uh_walk == mark) uhp = uhp->uh_alt_prev.ptr; /* Find the last branch with a mark, that's the one. */ last = uhp; while (last->uh_alt_next.ptr != NULL && last->uh_alt_next.ptr->uh_walk == mark) last = last->uh_alt_next.ptr; if (last != uhp) { /* Make the used branch the first entry in the list of * alternatives to make "u" and CTRL-R take this branch. */ while (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; if (last->uh_alt_next.ptr != NULL) last->uh_alt_next.ptr->uh_alt_prev.ptr = last->uh_alt_prev.ptr; last->uh_alt_prev.ptr->uh_alt_next.ptr = last->uh_alt_next.ptr; last->uh_alt_prev.ptr = NULL; last->uh_alt_next.ptr = uhp; uhp->uh_alt_prev.ptr = last; if (curbuf->b_u_oldhead == uhp) curbuf->b_u_oldhead = last; uhp = last; if (uhp->uh_next.ptr != NULL) uhp->uh_next.ptr->uh_prev.ptr = uhp; } curbuf->b_u_curhead = uhp; if (uhp->uh_walk != mark) break; /* must have reached the target */ /* Stop when going backwards in time and didn't find the exact * header we were looking for. */ if (uhp->uh_seq == target && above) { curbuf->b_u_seq_cur = target - 1; break; } u_undoredo(FALSE); /* Advance "curhead" to below the header we last used. If it * becomes NULL then we need to set "newhead" to this leaf. */ if (uhp->uh_prev.ptr == NULL) curbuf->b_u_newhead = uhp; curbuf->b_u_curhead = uhp->uh_prev.ptr; did_undo = FALSE; if (uhp->uh_seq == target) /* found it! */ break; uhp = uhp->uh_prev.ptr; if (uhp == NULL || uhp->uh_walk != mark) { /* Need to redo more but can't find it... */ internal_error("undo_time()"); break; } } } u_undo_end(did_undo, absolute); } /* * u_undoredo: common code for undo and redo * * The lines in the file are replaced by the lines in the entry list at * curbuf->b_u_curhead. The replaced lines in the file are saved in the entry * list for the next undo/redo. * * When "undo" is TRUE we go up in the tree, when FALSE we go down. */ static void u_undoredo(int undo) { char_u **newarray = NULL; linenr_T oldsize; linenr_T newsize; linenr_T top, bot; linenr_T lnum; linenr_T newlnum = MAXLNUM; long i; u_entry_T *uep, *nuep; u_entry_T *newlist = NULL; int old_flags; int new_flags; pos_T namedm[NMARKS]; visualinfo_T visualinfo; int empty_buffer; /* buffer became empty */ u_header_T *curhead = curbuf->b_u_curhead; #ifdef FEAT_AUTOCMD /* Don't want autocommands using the undo structures here, they are * invalid till the end. */ block_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif old_flags = curhead->uh_flags; new_flags = (curbuf->b_changed ? UH_CHANGED : 0) + ((curbuf->b_ml.ml_flags & ML_EMPTY) ? UH_EMPTYBUF : 0); setpcmark(); /* * save marks before undo/redo */ mch_memmove(namedm, curbuf->b_namedm, sizeof(pos_T) * NMARKS); visualinfo = curbuf->b_visual; curbuf->b_op_start.lnum = curbuf->b_ml.ml_line_count; curbuf->b_op_start.col = 0; curbuf->b_op_end.lnum = 0; curbuf->b_op_end.col = 0; for (uep = curhead->uh_entry; uep != NULL; uep = nuep) { top = uep->ue_top; bot = uep->ue_bot; if (bot == 0) bot = curbuf->b_ml.ml_line_count + 1; if (top > curbuf->b_ml.ml_line_count || top >= bot || bot > curbuf->b_ml.ml_line_count + 1) { #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif IEMSG(_("E438: u_undo: line numbers wrong")); changed(); /* don't want UNCHANGED now */ return; } oldsize = bot - top - 1; /* number of lines before undo */ newsize = uep->ue_size; /* number of lines after undo */ if (top < newlnum) { /* If the saved cursor is somewhere in this undo block, move it to * the remembered position. Makes "gwap" put the cursor back * where it was. */ lnum = curhead->uh_cursor.lnum; if (lnum >= top && lnum <= top + newsize + 1) { curwin->w_cursor = curhead->uh_cursor; newlnum = curwin->w_cursor.lnum - 1; } else { /* Use the first line that actually changed. Avoids that * undoing auto-formatting puts the cursor in the previous * line. */ for (i = 0; i < newsize && i < oldsize; ++i) if (STRCMP(uep->ue_array[i], ml_get(top + 1 + i)) != 0) break; if (i == newsize && newlnum == MAXLNUM && uep->ue_next == NULL) { newlnum = top; curwin->w_cursor.lnum = newlnum + 1; } else if (i < newsize) { newlnum = top + i; curwin->w_cursor.lnum = newlnum + 1; } } } empty_buffer = FALSE; /* delete the lines between top and bot and save them in newarray */ if (oldsize > 0) { if ((newarray = (char_u **)U_ALLOC_LINE( sizeof(char_u *) * oldsize)) == NULL) { do_outofmem_msg((long_u)(sizeof(char_u *) * oldsize)); /* * We have messed up the entry list, repair is impossible. * we have to free the rest of the list. */ while (uep != NULL) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); uep = nuep; } break; } /* delete backwards, it goes faster in most cases */ for (lnum = bot - 1, i = oldsize; --i >= 0; --lnum) { /* what can we do when we run out of memory? */ if ((newarray[i] = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); /* remember we deleted the last line in the buffer, and a * dummy empty line will be inserted */ if (curbuf->b_ml.ml_line_count == 1) empty_buffer = TRUE; ml_delete(lnum, FALSE); } } else newarray = NULL; /* insert the lines in u_array between top and bot */ if (newsize) { for (lnum = top, i = 0; i < newsize; ++i, ++lnum) { /* * If the file is empty, there is an empty line 1 that we * should get rid of, by replacing it with the new line */ if (empty_buffer && lnum == 0) ml_replace((linenr_T)1, uep->ue_array[i], TRUE); else ml_append(lnum, uep->ue_array[i], (colnr_T)0, FALSE); vim_free(uep->ue_array[i]); } vim_free((char_u *)uep->ue_array); } /* adjust marks */ if (oldsize != newsize) { mark_adjust(top + 1, top + oldsize, (long)MAXLNUM, (long)newsize - (long)oldsize); if (curbuf->b_op_start.lnum > top + oldsize) curbuf->b_op_start.lnum += newsize - oldsize; if (curbuf->b_op_end.lnum > top + oldsize) curbuf->b_op_end.lnum += newsize - oldsize; } changed_lines(top + 1, 0, bot, newsize - oldsize); /* set '[ and '] mark */ if (top + 1 < curbuf->b_op_start.lnum) curbuf->b_op_start.lnum = top + 1; if (newsize == 0 && top + 1 > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + 1; else if (top + newsize > curbuf->b_op_end.lnum) curbuf->b_op_end.lnum = top + newsize; u_newcount += newsize; u_oldcount += oldsize; uep->ue_size = oldsize; uep->ue_array = newarray; uep->ue_bot = top + newsize + 1; /* * insert this entry in front of the new entry list */ nuep = uep->ue_next; uep->ue_next = newlist; newlist = uep; } curhead->uh_entry = newlist; curhead->uh_flags = new_flags; if ((old_flags & UH_EMPTYBUF) && bufempty()) curbuf->b_ml.ml_flags |= ML_EMPTY; if (old_flags & UH_CHANGED) changed(); else #ifdef FEAT_NETBEANS_INTG /* per netbeans undo rules, keep it as modified */ if (!isNetbeansModified(curbuf)) #endif unchanged(curbuf, FALSE); /* * restore marks from before undo/redo */ for (i = 0; i < NMARKS; ++i) { if (curhead->uh_namedm[i].lnum != 0) curbuf->b_namedm[i] = curhead->uh_namedm[i]; if (namedm[i].lnum != 0) curhead->uh_namedm[i] = namedm[i]; else curhead->uh_namedm[i].lnum = 0; } if (curhead->uh_visual.vi_start.lnum != 0) { curbuf->b_visual = curhead->uh_visual; curhead->uh_visual = visualinfo; } /* * If the cursor is only off by one line, put it at the same position as * before starting the change (for the "o" command). * Otherwise the cursor should go to the first undone line. */ if (curhead->uh_cursor.lnum + 1 == curwin->w_cursor.lnum && curwin->w_cursor.lnum > 1) --curwin->w_cursor.lnum; if (curwin->w_cursor.lnum <= curbuf->b_ml.ml_line_count) { if (curhead->uh_cursor.lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = curhead->uh_cursor.col; #ifdef FEAT_VIRTUALEDIT if (virtual_active() && curhead->uh_cursor_vcol >= 0) coladvance((colnr_T)curhead->uh_cursor_vcol); else curwin->w_cursor.coladd = 0; #endif } else beginline(BL_SOL | BL_FIX); } else { /* We get here with the current cursor line being past the end (eg * after adding lines at the end of the file, and then undoing it). * check_cursor() will move the cursor to the last line. Move it to * the first column here. */ curwin->w_cursor.col = 0; #ifdef FEAT_VIRTUALEDIT curwin->w_cursor.coladd = 0; #endif } /* Make sure the cursor is on an existing line and column. */ check_cursor(); /* Remember where we are for "g-" and ":earlier 10s". */ curbuf->b_u_seq_cur = curhead->uh_seq; if (undo) /* We are below the previous undo. However, to make ":earlier 1s" * work we compute this as being just above the just undone change. */ --curbuf->b_u_seq_cur; /* Remember where we are for ":earlier 1f" and ":later 1f". */ if (curhead->uh_save_nr != 0) { if (undo) curbuf->b_u_save_nr_cur = curhead->uh_save_nr - 1; else curbuf->b_u_save_nr_cur = curhead->uh_save_nr; } /* The timestamp can be the same for multiple changes, just use the one of * the undone/redone change. */ curbuf->b_u_time_cur = curhead->uh_time; #ifdef FEAT_AUTOCMD unblock_autocmds(); #endif #ifdef U_DEBUG u_check(FALSE); #endif } /* * If we deleted or added lines, report the number of less/more lines. * Otherwise, report the number of changes (this may be incorrect * in some cases, but it's better than nothing). */ static void u_undo_end( int did_undo, /* just did an undo */ int absolute) /* used ":undo N" */ { char *msgstr; u_header_T *uhp; char_u msgbuf[80]; #ifdef FEAT_FOLDING if ((fdo_flags & FDO_UNDO) && KeyTyped) foldOpenCursor(); #endif if (global_busy /* no messages now, wait until global is finished */ || !messaging()) /* 'lazyredraw' set, don't do messages now */ return; if (curbuf->b_ml.ml_flags & ML_EMPTY) --u_newcount; u_oldcount -= u_newcount; if (u_oldcount == -1) msgstr = N_("more line"); else if (u_oldcount < 0) msgstr = N_("more lines"); else if (u_oldcount == 1) msgstr = N_("line less"); else if (u_oldcount > 1) msgstr = N_("fewer lines"); else { u_oldcount = u_newcount; if (u_newcount == 1) msgstr = N_("change"); else msgstr = N_("changes"); } if (curbuf->b_u_curhead != NULL) { /* For ":undo N" we prefer a "after #N" message. */ if (absolute && curbuf->b_u_curhead->uh_next.ptr != NULL) { uhp = curbuf->b_u_curhead->uh_next.ptr; did_undo = FALSE; } else if (did_undo) uhp = curbuf->b_u_curhead; else uhp = curbuf->b_u_curhead->uh_next.ptr; } else uhp = curbuf->b_u_newhead; if (uhp == NULL) *msgbuf = NUL; else u_add_time(msgbuf, sizeof(msgbuf), uhp->uh_time); #ifdef FEAT_CONCEAL { win_T *wp; FOR_ALL_WINDOWS(wp) { if (wp->w_buffer == curbuf && wp->w_p_cole > 0) redraw_win_later(wp, NOT_VALID); } } #endif smsg((char_u *)_("%ld %s; %s #%ld %s"), u_oldcount < 0 ? -u_oldcount : u_oldcount, _(msgstr), did_undo ? _("before") : _("after"), uhp == NULL ? 0L : uhp->uh_seq, msgbuf); } /* * u_sync: stop adding to the current entry list */ void u_sync( int force) /* Also sync when no_u_sync is set. */ { /* Skip it when already synced or syncing is disabled. */ if (curbuf->b_u_synced || (!force && no_u_sync > 0)) return; #if defined(FEAT_XIM) && defined(FEAT_GUI_GTK) if (im_is_preediting()) return; /* XIM is busy, don't break an undo sequence */ #endif if (get_undolevel() < 0) curbuf->b_u_synced = TRUE; /* no entries, nothing to do */ else { u_getbot(); /* compute ue_bot of previous u_save */ curbuf->b_u_curhead = NULL; } } /* * ":undolist": List the leafs of the undo tree */ void ex_undolist(exarg_T *eap UNUSED) { garray_T ga; u_header_T *uhp; int mark; int nomark; int changes = 1; int i; /* * 1: walk the tree to find all leafs, put the info in "ga". * 2: sort the lines * 3: display the list */ mark = ++lastmark; nomark = ++lastmark; ga_init2(&ga, (int)sizeof(char *), 20); uhp = curbuf->b_u_oldhead; while (uhp != NULL) { if (uhp->uh_prev.ptr == NULL && uhp->uh_walk != nomark && uhp->uh_walk != mark) { if (ga_grow(&ga, 1) == FAIL) break; vim_snprintf((char *)IObuff, IOSIZE, "%6ld %7ld ", uhp->uh_seq, changes); u_add_time(IObuff + STRLEN(IObuff), IOSIZE - STRLEN(IObuff), uhp->uh_time); if (uhp->uh_save_nr > 0) { while (STRLEN(IObuff) < 33) STRCAT(IObuff, " "); vim_snprintf_add((char *)IObuff, IOSIZE, " %3ld", uhp->uh_save_nr); } ((char_u **)(ga.ga_data))[ga.ga_len++] = vim_strsave(IObuff); } uhp->uh_walk = mark; /* go down in the tree if we haven't been there */ if (uhp->uh_prev.ptr != NULL && uhp->uh_prev.ptr->uh_walk != nomark && uhp->uh_prev.ptr->uh_walk != mark) { uhp = uhp->uh_prev.ptr; ++changes; } /* go to alternate branch if we haven't been there */ else if (uhp->uh_alt_next.ptr != NULL && uhp->uh_alt_next.ptr->uh_walk != nomark && uhp->uh_alt_next.ptr->uh_walk != mark) uhp = uhp->uh_alt_next.ptr; /* go up in the tree if we haven't been there and we are at the * start of alternate branches */ else if (uhp->uh_next.ptr != NULL && uhp->uh_alt_prev.ptr == NULL && uhp->uh_next.ptr->uh_walk != nomark && uhp->uh_next.ptr->uh_walk != mark) { uhp = uhp->uh_next.ptr; --changes; } else { /* need to backtrack; mark this node as done */ uhp->uh_walk = nomark; if (uhp->uh_alt_prev.ptr != NULL) uhp = uhp->uh_alt_prev.ptr; else { uhp = uhp->uh_next.ptr; --changes; } } } if (ga.ga_len == 0) MSG(_("Nothing to undo")); else { sort_strings((char_u **)ga.ga_data, ga.ga_len); msg_start(); msg_puts_attr((char_u *)_("number changes when saved"), hl_attr(HLF_T)); for (i = 0; i < ga.ga_len && !got_int; ++i) { msg_putchar('\n'); if (got_int) break; msg_puts(((char_u **)ga.ga_data)[i]); } msg_end(); ga_clear_strings(&ga); } } /* * Put the timestamp of an undo header in "buf[buflen]" in a nice format. */ static void u_add_time(char_u *buf, size_t buflen, time_t tt) { #ifdef HAVE_STRFTIME struct tm *curtime; if (vim_time() - tt >= 100) { curtime = localtime(&tt); if (vim_time() - tt < (60L * 60L * 12L)) /* within 12 hours */ (void)strftime((char *)buf, buflen, "%H:%M:%S", curtime); else /* longer ago */ (void)strftime((char *)buf, buflen, "%Y/%m/%d %H:%M:%S", curtime); } else #endif vim_snprintf((char *)buf, buflen, _("%ld seconds ago"), (long)(vim_time() - tt)); } /* * ":undojoin": continue adding to the last entry list */ void ex_undojoin(exarg_T *eap UNUSED) { if (curbuf->b_u_newhead == NULL) return; /* nothing changed before */ if (curbuf->b_u_curhead != NULL) { EMSG(_("E790: undojoin is not allowed after undo")); return; } if (!curbuf->b_u_synced) return; /* already unsynced */ if (get_undolevel() < 0) return; /* no entries, nothing to do */ else /* Append next change to the last entry */ curbuf->b_u_synced = FALSE; } /* * Called after writing or reloading the file and setting b_changed to FALSE. * Now an undo means that the buffer is modified. */ void u_unchanged(buf_T *buf) { u_unch_branch(buf->b_u_oldhead); buf->b_did_warn = FALSE; } /* * After reloading a buffer which was saved for 'undoreload': Find the first * line that was changed and set the cursor there. */ void u_find_first_changed(void) { u_header_T *uhp = curbuf->b_u_newhead; u_entry_T *uep; linenr_T lnum; if (curbuf->b_u_curhead != NULL || uhp == NULL) return; /* undid something in an autocmd? */ /* Check that the last undo block was for the whole file. */ uep = uhp->uh_entry; if (uep->ue_top != 0 || uep->ue_bot != 0) return; for (lnum = 1; lnum < curbuf->b_ml.ml_line_count && lnum <= uep->ue_size; ++lnum) if (STRCMP(ml_get_buf(curbuf, lnum, FALSE), uep->ue_array[lnum - 1]) != 0) { clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; return; } if (curbuf->b_ml.ml_line_count != uep->ue_size) { /* lines added or deleted at the end, put the cursor there */ clearpos(&(uhp->uh_cursor)); uhp->uh_cursor.lnum = lnum; } } /* * Increase the write count, store it in the last undo header, what would be * used for "u". */ void u_update_save_nr(buf_T *buf) { u_header_T *uhp; ++buf->b_u_save_nr_last; buf->b_u_save_nr_cur = buf->b_u_save_nr_last; uhp = buf->b_u_curhead; if (uhp != NULL) uhp = uhp->uh_next.ptr; else uhp = buf->b_u_newhead; if (uhp != NULL) uhp->uh_save_nr = buf->b_u_save_nr_last; } static void u_unch_branch(u_header_T *uhp) { u_header_T *uh; for (uh = uhp; uh != NULL; uh = uh->uh_prev.ptr) { uh->uh_flags |= UH_CHANGED; if (uh->uh_alt_next.ptr != NULL) u_unch_branch(uh->uh_alt_next.ptr); /* recursive */ } } /* * Get pointer to last added entry. * If it's not valid, give an error message and return NULL. */ static u_entry_T * u_get_headentry(void) { if (curbuf->b_u_newhead == NULL || curbuf->b_u_newhead->uh_entry == NULL) { IEMSG(_("E439: undo list corrupt")); return NULL; } return curbuf->b_u_newhead->uh_entry; } /* * u_getbot(): compute the line number of the previous u_save * It is called only when b_u_synced is FALSE. */ static void u_getbot(void) { u_entry_T *uep; linenr_T extra; uep = u_get_headentry(); /* check for corrupt undo list */ if (uep == NULL) return; uep = curbuf->b_u_newhead->uh_getbot_entry; if (uep != NULL) { /* * the new ue_bot is computed from the number of lines that has been * inserted (0 - deleted) since calling u_save. This is equal to the * old line count subtracted from the current line count. */ extra = curbuf->b_ml.ml_line_count - uep->ue_lcount; uep->ue_bot = uep->ue_top + uep->ue_size + 1 + extra; if (uep->ue_bot < 1 || uep->ue_bot > curbuf->b_ml.ml_line_count) { IEMSG(_("E440: undo line missing")); uep->ue_bot = uep->ue_top + 1; /* assume all lines deleted, will * get all the old lines back * without deleting the current * ones */ } curbuf->b_u_newhead->uh_getbot_entry = NULL; } curbuf->b_u_synced = TRUE; } /* * Free one header "uhp" and its entry list and adjust the pointers. */ static void u_freeheader( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *uhap; /* When there is an alternate redo list free that branch completely, * because we can never go there. */ if (uhp->uh_alt_next.ptr != NULL) u_freebranch(buf, uhp->uh_alt_next.ptr, uhpp); if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; /* Update the links in the list to remove the header. */ if (uhp->uh_next.ptr == NULL) buf->b_u_oldhead = uhp->uh_prev.ptr; else uhp->uh_next.ptr->uh_prev.ptr = uhp->uh_prev.ptr; if (uhp->uh_prev.ptr == NULL) buf->b_u_newhead = uhp->uh_next.ptr; else for (uhap = uhp->uh_prev.ptr; uhap != NULL; uhap = uhap->uh_alt_next.ptr) uhap->uh_next.ptr = uhp->uh_next.ptr; u_freeentries(buf, uhp, uhpp); } /* * Free an alternate branch and any following alternate branches. */ static void u_freebranch( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_header_T *tofree, *next; /* If this is the top branch we may need to use u_freeheader() to update * all the pointers. */ if (uhp == buf->b_u_oldhead) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, uhpp); return; } if (uhp->uh_alt_prev.ptr != NULL) uhp->uh_alt_prev.ptr->uh_alt_next.ptr = NULL; next = uhp; while (next != NULL) { tofree = next; if (tofree->uh_alt_next.ptr != NULL) u_freebranch(buf, tofree->uh_alt_next.ptr, uhpp); /* recursive */ next = tofree->uh_prev.ptr; u_freeentries(buf, tofree, uhpp); } } /* * Free all the undo entries for one header and the header itself. * This means that "uhp" is invalid when returning. */ static void u_freeentries( buf_T *buf, u_header_T *uhp, u_header_T **uhpp) /* if not NULL reset when freeing this header */ { u_entry_T *uep, *nuep; /* Check for pointers to the header that become invalid now. */ if (buf->b_u_curhead == uhp) buf->b_u_curhead = NULL; if (buf->b_u_newhead == uhp) buf->b_u_newhead = NULL; /* freeing the newest entry */ if (uhpp != NULL && uhp == *uhpp) *uhpp = NULL; for (uep = uhp->uh_entry; uep != NULL; uep = nuep) { nuep = uep->ue_next; u_freeentry(uep, uep->ue_size); } #ifdef U_DEBUG uhp->uh_magic = 0; #endif vim_free((char_u *)uhp); --buf->b_u_numhead; } /* * free entry 'uep' and 'n' lines in uep->ue_array[] */ static void u_freeentry(u_entry_T *uep, long n) { while (n > 0) vim_free(uep->ue_array[--n]); vim_free((char_u *)uep->ue_array); #ifdef U_DEBUG uep->ue_magic = 0; #endif vim_free((char_u *)uep); } /* * invalidate the undo buffer; called when storage has already been released */ void u_clearall(buf_T *buf) { buf->b_u_newhead = buf->b_u_oldhead = buf->b_u_curhead = NULL; buf->b_u_synced = TRUE; buf->b_u_numhead = 0; buf->b_u_line_ptr = NULL; buf->b_u_line_lnum = 0; } /* * save the line "lnum" for the "U" command */ void u_saveline(linenr_T lnum) { if (lnum == curbuf->b_u_line_lnum) /* line is already saved */ return; if (lnum < 1 || lnum > curbuf->b_ml.ml_line_count) /* should never happen */ return; u_clearline(); curbuf->b_u_line_lnum = lnum; if (curwin->w_cursor.lnum == lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; else curbuf->b_u_line_colnr = 0; if ((curbuf->b_u_line_ptr = u_save_line(lnum)) == NULL) do_outofmem_msg((long_u)0); } /* * clear the line saved for the "U" command * (this is used externally for crossing a line while in insert mode) */ void u_clearline(void) { if (curbuf->b_u_line_ptr != NULL) { vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = NULL; curbuf->b_u_line_lnum = 0; } } /* * Implementation of the "U" command. * Differentiation from vi: "U" can be undone with the next "U". * We also allow the cursor to be in another line. * Careful: may trigger autocommands that reload the buffer. */ void u_undoline(void) { colnr_T t; char_u *oldp; if (undo_off) return; if (curbuf->b_u_line_ptr == NULL || curbuf->b_u_line_lnum > curbuf->b_ml.ml_line_count) { beep_flush(); return; } /* first save the line for the 'u' command */ if (u_savecommon(curbuf->b_u_line_lnum - 1, curbuf->b_u_line_lnum + 1, (linenr_T)0, FALSE) == FAIL) return; oldp = u_save_line(curbuf->b_u_line_lnum); if (oldp == NULL) { do_outofmem_msg((long_u)0); return; } ml_replace(curbuf->b_u_line_lnum, curbuf->b_u_line_ptr, TRUE); changed_bytes(curbuf->b_u_line_lnum, 0); vim_free(curbuf->b_u_line_ptr); curbuf->b_u_line_ptr = oldp; t = curbuf->b_u_line_colnr; if (curwin->w_cursor.lnum == curbuf->b_u_line_lnum) curbuf->b_u_line_colnr = curwin->w_cursor.col; curwin->w_cursor.col = t; curwin->w_cursor.lnum = curbuf->b_u_line_lnum; check_cursor_col(); } /* * Free all allocated memory blocks for the buffer 'buf'. */ void u_blockfree(buf_T *buf) { while (buf->b_u_oldhead != NULL) u_freeheader(buf, buf->b_u_oldhead, NULL); vim_free(buf->b_u_line_ptr); } /* * u_save_line(): allocate memory and copy line 'lnum' into it. * Returns NULL when out of memory. */ static char_u * u_save_line(linenr_T lnum) { return vim_strsave(ml_get(lnum)); } /* * Check if the 'modified' flag is set, or 'ff' has changed (only need to * check the first character, because it can only be "dos", "unix" or "mac"). * "nofile" and "scratch" type buffers are considered to always be unchanged. */ int bufIsChanged(buf_T *buf) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(buf) && #endif (buf->b_changed || file_ff_differs(buf, TRUE)); } int curbufIsChanged(void) { return #ifdef FEAT_QUICKFIX !bt_dontwrite(curbuf) && #endif (curbuf->b_changed || file_ff_differs(curbuf, TRUE)); } #if defined(FEAT_EVAL) || defined(PROTO) /* * For undotree(): Append the list of undo blocks at "first_uhp" to "list". * Recursive. */ void u_eval_tree(u_header_T *first_uhp, list_T *list) { u_header_T *uhp = first_uhp; dict_T *dict; while (uhp != NULL) { dict = dict_alloc(); if (dict == NULL) return; dict_add_nr_str(dict, "seq", uhp->uh_seq, NULL); dict_add_nr_str(dict, "time", (long)uhp->uh_time, NULL); if (uhp == curbuf->b_u_newhead) dict_add_nr_str(dict, "newhead", 1, NULL); if (uhp == curbuf->b_u_curhead) dict_add_nr_str(dict, "curhead", 1, NULL); if (uhp->uh_save_nr > 0) dict_add_nr_str(dict, "save", uhp->uh_save_nr, NULL); if (uhp->uh_alt_next.ptr != NULL) { list_T *alt_list = list_alloc(); if (alt_list != NULL) { /* Recursive call to add alternate undo tree. */ u_eval_tree(uhp->uh_alt_next.ptr, alt_list); dict_add_list(dict, "alt", alt_list); } } list_append_dict(list, dict); uhp = uhp->uh_prev.ptr; } } #endif
./CrossVul/dataset_final_sorted/CWE-190/c/good_3178_0